You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@magpie.apache.org by "potiuk (via GitHub)" <gi...@apache.org> on 2026/09/20 20:33:55 UTC
[PR] feat(container-gateway): run podman and docker from inside the sandbox through a policy proxy [magpie]
potiuk opened a new pull request, #1298:
URL: https://github.com/apache/magpie/pull/1298
## What this adds
A **container gateway**: a per-project policy proxy in front of the podman / docker daemon socket, so shell commands run by a sandboxed agent can drive containers without the daemon being reachable.
Today an adopter has two options, and both hand over the daemon. Excluding `docker` from the sandbox (upstream's advice) or allowing the daemon socket in `sandbox.network.allowUnixSockets` both grant what upstream's own documentation calls "access to the host system through the Docker socket". On macOS the default Podman machine mounts `/Users` read-write, so that is a bind mount away from `~/.ssh`.
The gateway runs outside the sandbox, listens on two unix sockets inside the project tree, and forwards the Docker-compatible API after enforcing policy. It gives three properties:
1. **Containers only.** A create body is an allow-list: unknown fields are refused, and the fields that turn a container into host access (privileged, capabilities, devices, host namespaces, unconfined security options, `rootfs`, overlay volumes, volume-driver configurations, bind mounts outside the project) are denied by name. The build query, exec bodies and act-by-name queries are policed the same way.
2. **This project's containers only.** Every container, pod, volume and network is labelled with the project; every list, act and remove is filtered or checked against that label, resolved by ID so a rename cannot race it.
3. **The same egress policy as the shell.** Containers and builds get the framework's egress gateway as their HTTP proxy. This is a friction layer, not a wall, and says so.
Both backends are optional; the gateway serves the docker CLI from a podman backend when Docker is absent, and exits quietly when neither exists.
## What is in the branch
Tool `tools/container-gateway/` (stdlib only): routing, policy, the HTTP relay with streaming and hijack support, backend discovery, the daemon and its CLI. A `SessionStart` / `SessionEnd` hook in `tools/agent-isolation/`. Reference settings plus a sandbox-lint invariant that rejects a daemon socket in the allow-list. Documentation in the setup guide and the troubleshooting catalog, a row in RFC-AI-0004 and a cross-reference in RFC-AI-0003. Doctor probe, verify check and install step, with eval fixtures. 581 unit tests and an integration suite that runs against a real daemon.
## How it was built and reviewed
Spec first, then fifteen planned tasks, each implemented and reviewed independently; the security-bearing parts took several fix rounds each. A whole-branch review then found four bypasses that per-component review could not see, all of the same shape: the policy enumerated what was forbidden rather than what was allowed. That is why the create body is now an allow-list.
An integration run against a live daemon found a fifth defect that no test against fakes had caught, and the fix round found a sixth.
## Limits
`tool.md` and the README carry a *Limits and residual risks* section. The ones worth repeating: bind sources are checked on the host at decision time and re-resolved by the daemon at mount time, so a symlink swapped in that window is not caught; images are shared across projects by design; container egress that bypasses proxy variables is not intercepted; backend discovery happens at gateway start.
## Follow-ups
Automating the per-project socket entries in `/magpie-setup config` (documented as manual for now), and exercising the libpod volume-label path against podman.
## Generative AI disclosure
Written with Claude Code (Opus 5) under human direction: spec, plan, per-task implementation and review, and the final review passes. Every commit was reviewed by a separate agent and by the author before landing.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@magpie.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(container-gateway): run podman and docker from inside the sandbox through a policy proxy [magpie]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #1298:
URL: https://github.com/apache/magpie/pull/1298#issuecomment-5752506863
The **last** security layer added - container gateway. It allows to safely (and without prompts) run containers inside your agentic CLI. It will keep containers separated "per-project" so that they are not reachable from inside the sandbox.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@magpie.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(container-gateway): run podman and docker from inside the sandbox through a policy proxy [magpie]
Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #1298:
URL: https://github.com/apache/magpie/pull/1298#discussion_r4058166020
##########
tools/container-gateway/tests/test_daemon.py:
##########
@@ -0,0 +1,1315 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Daemon plumbing: paths, guards, idle exit, status and stop.
+
+Threat model exercised throughout this file: the daemon runs OUTSIDE the
+sandbox with the operator's own privileges, while the sandboxed agent
+can create, delete and symlink anything under the project tree,
+including ``.apache-magpie-local/run/``. Every guard test below plants
+exactly the kind of hostile filesystem state that threat model implies
+and checks the guard refuses it -- no bind needed for any of them.
+
+No ``pytest-asyncio`` in the ``magpie-dev`` dependency group, so each
+async scenario is a plain ``def`` test driving its coroutine through the
+``run()`` helper, exactly as ``test_http.py`` and ``test_relay.py`` do.
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import contextlib
+import json
+import os
+import shutil
+import signal
+import subprocess
+import sys
+import tempfile
+from collections.abc import AsyncIterator, Coroutine, Iterator
+from pathlib import Path
+from typing import Any, TypeVar
+
+import pytest
+
+from container_gateway import __main__ as cli
+from container_gateway import daemon
+from container_gateway.backends import Backend
+
+from .fakebackend import FakeBackend
+
+SRC = Path(__file__).resolve().parents[1] / "src"
+
+_T = TypeVar("_T")
+
+# Every scenario in this file is bounded. A daemon test that wedges --
+# waiting on a bind that never completes, a socket nobody answers, an
+# idle timer that never fires -- must fail in seconds, naming itself,
+# rather than hang the whole run until CI's job limit kills it with no
+# output at all. Generous enough that no healthy scenario can reach it:
+# the longest one here idles out after 1.5s.
+SCENARIO_TIMEOUT = 15.0
+# The same bound for the subprocess-level CLI tests further down.
+SUBPROCESS_TIMEOUT = 30
+
+
+def run(coro: Coroutine[Any, Any, _T], timeout: float = SCENARIO_TIMEOUT) -> _T:
+ """Drive a coroutine to completion without pytest-asyncio, under a hard bound."""
+
+ async def bounded() -> _T:
+ return await asyncio.wait_for(coro, timeout)
+
+ return asyncio.run(bounded())
+
+
+async def _tcp_listener_or_skip() -> asyncio.AbstractServer:
Review Comment:
## CodeQL / Explicit returns mixed with implicit (fall through) returns
Mixing implicit and explicit returns may indicate an error, as implicit returns always return None.
[Show more details](https://github.com/apache/magpie/security/code-scanning/80)
##########
tools/container-gateway/tests/test_relay.py:
##########
@@ -0,0 +1,739 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""The relay end to end against the fake backend.
+
+No ``pytest-asyncio`` in the ``magpie-dev`` dependency group, so each
+scenario is a plain ``def`` test driving its coroutine through ``run()``,
+exactly as ``test_http.py`` does. The relay is driven directly over a
+``socket.socketpair()`` rather than through a bound gateway socket: the
+sandbox refuses ``bind()`` on a unix-domain path, and ``serve_unix`` (the
+only piece that binds) gets its own smoke test below.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import json
+from collections.abc import Awaitable, Callable, Coroutine
+from pathlib import Path
+from typing import Any, TypeVar
+
+import pytest
+
+from container_gateway import relay as relay_module
+from container_gateway.labels import LABEL_KEY
+from container_gateway.policy import PolicyContext
+from container_gateway.relay import Relay, _rewrite_name, serve_unix
+
+from .fakebackend import FakeBackend, socket_pair
+
+_T = TypeVar("_T")
+
+
+def run(coro: Coroutine[Any, Any, _T]) -> _T:
+ """Drive a coroutine to completion without pytest-asyncio."""
+ return asyncio.run(coro)
+
+
+async def _serve_unix_or_skip(
+ sock: Path, handler: Callable[[asyncio.StreamReader, asyncio.StreamWriter], Awaitable[None]]
+) -> asyncio.AbstractServer:
Review Comment:
## CodeQL / Explicit returns mixed with implicit (fall through) returns
Mixing implicit and explicit returns may indicate an error, as implicit returns always return None.
[Show more details](https://github.com/apache/magpie/security/code-scanning/81)
##########
tools/container-gateway/tests/test_daemon.py:
##########
@@ -0,0 +1,1315 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Daemon plumbing: paths, guards, idle exit, status and stop.
+
+Threat model exercised throughout this file: the daemon runs OUTSIDE the
+sandbox with the operator's own privileges, while the sandboxed agent
+can create, delete and symlink anything under the project tree,
+including ``.apache-magpie-local/run/``. Every guard test below plants
+exactly the kind of hostile filesystem state that threat model implies
+and checks the guard refuses it -- no bind needed for any of them.
+
+No ``pytest-asyncio`` in the ``magpie-dev`` dependency group, so each
+async scenario is a plain ``def`` test driving its coroutine through the
+``run()`` helper, exactly as ``test_http.py`` and ``test_relay.py`` do.
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import contextlib
+import json
+import os
+import shutil
+import signal
+import subprocess
+import sys
+import tempfile
+from collections.abc import AsyncIterator, Coroutine, Iterator
+from pathlib import Path
+from typing import Any, TypeVar
+
+import pytest
+
+from container_gateway import __main__ as cli
+from container_gateway import daemon
+from container_gateway.backends import Backend
+
+from .fakebackend import FakeBackend
+
+SRC = Path(__file__).resolve().parents[1] / "src"
+
+_T = TypeVar("_T")
+
+# Every scenario in this file is bounded. A daemon test that wedges --
+# waiting on a bind that never completes, a socket nobody answers, an
+# idle timer that never fires -- must fail in seconds, naming itself,
+# rather than hang the whole run until CI's job limit kills it with no
+# output at all. Generous enough that no healthy scenario can reach it:
+# the longest one here idles out after 1.5s.
+SCENARIO_TIMEOUT = 15.0
+# The same bound for the subprocess-level CLI tests further down.
+SUBPROCESS_TIMEOUT = 30
+
+
+def run(coro: Coroutine[Any, Any, _T], timeout: float = SCENARIO_TIMEOUT) -> _T:
+ """Drive a coroutine to completion without pytest-asyncio, under a hard bound."""
+
+ async def bounded() -> _T:
+ return await asyncio.wait_for(coro, timeout)
+
+ return asyncio.run(bounded())
+
+
+async def _tcp_listener_or_skip() -> asyncio.AbstractServer:
+ """A loopback TCP listener, skipping the caller where the sandbox refuses ``bind()``.
+
+ Returning the server rather than binding inside the caller's ``try``
+ keeps the caller's ``finally`` from ever referencing a name that was
+ never assigned.
+ """
+ try:
+ return await asyncio.start_server(lambda r, w: None, host="127.0.0.1", port=0)
+ except PermissionError:
+ pytest.skip("sandbox denies TCP bind; runs in CI")
+
+
+def _ns(project: Path, run_dir: Path, **extra: Any) -> argparse.Namespace:
+ """A minimal argparse.Namespace for calling cmd_serve/cmd_stop/cmd_status directly."""
+ base = {"project": project, "run_dir": run_dir, "pid_file": None}
+ base.update(extra)
+ return argparse.Namespace(**base)
+
+
+class _HeldPidLock:
+ """A pid lock the test body may hand back early, at most once.
+
+ The ``stop``-path tests below release the lock mid-test, from inside
+ a fake ``os.kill``, to simulate the daemon exiting and dropping its
+ flock. ``released`` is how ``held_pid_lock`` knows not to close the
+ same descriptor a second time on the way out -- by then the number
+ may belong to something else entirely.
+ """
+
+ def __init__(self, fd: int) -> None:
+ self._fd = fd
+ self.released = False
+
+ def close(self) -> None:
+ if not self.released:
+ self.released = True
+ os.close(self._fd)
+
+
+@contextlib.contextmanager
+def held_pid_lock(pid_file: Path) -> Iterator[_HeldPidLock]:
+ """Hold ``pid_file``'s lock for the body, releasing it however the body ends."""
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ lock = _HeldPidLock(fd)
+ try:
+ yield lock
+ finally:
+ if not lock.released:
+ lock.released = True
+ os.close(fd)
+
+
+@pytest.fixture
+def short_run_dir() -> Iterator[Path]:
+ """A run directory short enough to hold a unix-socket path.
+
+ ``pytest``'s own ``tmp_path`` fixture nests under
+ ``pytest-of-<user>/pytest-<n>/<test-name>/`` inside ``$TMPDIR``, which
+ in this sandboxed dev environment is already long enough on its own
+ to blow the ~103-byte ``sun_path`` limit before ``run_dir`` even adds
+ ``podman.sock``. ``tempfile.mkdtemp()`` sits directly under
+ ``$TMPDIR`` with none of that nesting, so it stays short everywhere
+ ``tmp_path`` might not. It is also already 0700 and owned by us, so
+ it satisfies ``check_run_dir``'s "custom run-dir" branch as-is.
+ """
+ d = Path(tempfile.mkdtemp(prefix="cg-"))
+ try:
+ yield d
+ finally:
+ shutil.rmtree(d, ignore_errors=True)
+
+
+class _RealSocketBackend:
+ """A ``FakeBackend`` served over a real filesystem unix socket.
+
+ ``tests/fakebackend.FakeBackend`` only ever hands out in-process
+ ``socket.socketpair()`` connections (the sandbox refuses ``bind()``,
+ so it never listens on a path) -- but ``daemon.run()`` needs a real
+ socket path to hand to ``unix_connector`` for a ``Backend``. This
+ thin wrapper does the one real bind these daemon tests need, so it
+ can hit the same ``PermissionError`` the sandbox raises and skip
+ exactly like every other bind-touching test in this suite.
+ """
+
+ def __init__(self, socket_path: Path) -> None:
+ self.socket = socket_path
+ self._fake = FakeBackend()
+ self._server: asyncio.AbstractServer | None = None
+
+ async def start(self) -> None:
+ self._server = await asyncio.start_unix_server(self._fake._handle, path=str(self.socket))
+
+ async def stop(self) -> None:
+ """Stop serving, without waiting on a connection nobody will close.
+
+ ``wait_closed`` waits for every accepted connection's handler
+ too (Python 3.12.1 and later), and the fake's handler sits
+ reading the next request on a keep-alive connection the gateway
+ has not closed yet. Teardown is bounded so a test that leaves
+ one open fails on its own assertion rather than wedging the run.
+ """
+ if self._server is not None:
+ self._server.close()
+ with contextlib.suppress(TimeoutError):
+ await asyncio.wait_for(self._server.wait_closed(), 5)
+
+
+@contextlib.asynccontextmanager
+async def _gateway(
+ project_root: Path, run_dir: Path, idle_timeout: float
+) -> AsyncIterator[tuple[daemon.Config, asyncio.Task[int]]]:
+ """A running ``daemon.run()`` task with a real backend socket behind it.
+
+ Skips the caller wherever the sandbox refuses the binds this needs,
+ exactly like every other bind-touching test in this suite: the
+ backend's own listener up front, the gateway's two sockets via the
+ task's early exception.
+ """
+ backend = _RealSocketBackend(run_dir / "d.sock")
+ try:
+ await asyncio.wait_for(backend.start(), 5)
+ except PermissionError:
+ pytest.skip("sandbox denies unix bind; runs in CI")
+ try:
+ cfg = daemon.Config(
+ project_root,
+ run_dir,
+ ("podman", "docker"),
+ "off",
+ 8899,
+ None,
+ (),
+ idle_timeout,
+ "INFO",
+ run_dir / "pid",
+ )
+ found = [Backend("podman", backend.socket, "host.containers.internal")]
+ task = asyncio.create_task(daemon.run(cfg, discover_fn=lambda *a, **k: found, platform="Darwin"))
+ await asyncio.sleep(0.3)
+ if task.done():
+ exc = task.exception()
+ if isinstance(exc, PermissionError):
+ pytest.skip("sandbox denies unix bind; runs in CI")
+ if exc is not None:
+ raise exc
+ try:
+ yield cfg, task
+ finally:
+ # Only reached when the body did not get the daemon to exit
+ # on its own -- the failure is the body's to report, so the
+ # teardown just makes sure nothing is left running behind it.
+ if not task.done():
+ task.cancel()
+ await asyncio.wait([task], timeout=5)
+ finally:
+ await asyncio.wait_for(backend.stop(), 5)
+
+
+async def _ping(sock_path: Path) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]:
+ """Ping the gateway over a fresh client connection, and leave it open.
+
+ The response is read by its framing rather than to EOF: the gateway
+ keeps the connection alive after a ``/_ping``, so a read to EOF
+ would only return once the daemon tore the connection down, which
+ is the very thing the callers below are measuring.
+ """
+ try:
+ r, w = await asyncio.wait_for(asyncio.open_unix_connection(str(sock_path)), 5)
+ except PermissionError:
+ pytest.skip("sandbox denies unix socket connections; runs in CI")
+ w.write(b"GET /_ping HTTP/1.1\r\nHost: x\r\n\r\n")
Review Comment:
## CodeQL / Potentially uninitialized local variable
Local variable 'w' may be used before it is initialized.
[Show more details](https://github.com/apache/magpie/security/code-scanning/82)
##########
tools/container-gateway/tests/test_daemon.py:
##########
@@ -0,0 +1,1315 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Daemon plumbing: paths, guards, idle exit, status and stop.
+
+Threat model exercised throughout this file: the daemon runs OUTSIDE the
+sandbox with the operator's own privileges, while the sandboxed agent
+can create, delete and symlink anything under the project tree,
+including ``.apache-magpie-local/run/``. Every guard test below plants
+exactly the kind of hostile filesystem state that threat model implies
+and checks the guard refuses it -- no bind needed for any of them.
+
+No ``pytest-asyncio`` in the ``magpie-dev`` dependency group, so each
+async scenario is a plain ``def`` test driving its coroutine through the
+``run()`` helper, exactly as ``test_http.py`` and ``test_relay.py`` do.
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import contextlib
+import json
+import os
+import shutil
+import signal
+import subprocess
+import sys
+import tempfile
+from collections.abc import AsyncIterator, Coroutine, Iterator
+from pathlib import Path
+from typing import Any, TypeVar
+
+import pytest
+
+from container_gateway import __main__ as cli
+from container_gateway import daemon
+from container_gateway.backends import Backend
+
+from .fakebackend import FakeBackend
+
+SRC = Path(__file__).resolve().parents[1] / "src"
+
+_T = TypeVar("_T")
+
+# Every scenario in this file is bounded. A daemon test that wedges --
+# waiting on a bind that never completes, a socket nobody answers, an
+# idle timer that never fires -- must fail in seconds, naming itself,
+# rather than hang the whole run until CI's job limit kills it with no
+# output at all. Generous enough that no healthy scenario can reach it:
+# the longest one here idles out after 1.5s.
+SCENARIO_TIMEOUT = 15.0
+# The same bound for the subprocess-level CLI tests further down.
+SUBPROCESS_TIMEOUT = 30
+
+
+def run(coro: Coroutine[Any, Any, _T], timeout: float = SCENARIO_TIMEOUT) -> _T:
+ """Drive a coroutine to completion without pytest-asyncio, under a hard bound."""
+
+ async def bounded() -> _T:
+ return await asyncio.wait_for(coro, timeout)
+
+ return asyncio.run(bounded())
+
+
+async def _tcp_listener_or_skip() -> asyncio.AbstractServer:
+ """A loopback TCP listener, skipping the caller where the sandbox refuses ``bind()``.
+
+ Returning the server rather than binding inside the caller's ``try``
+ keeps the caller's ``finally`` from ever referencing a name that was
+ never assigned.
+ """
+ try:
+ return await asyncio.start_server(lambda r, w: None, host="127.0.0.1", port=0)
+ except PermissionError:
+ pytest.skip("sandbox denies TCP bind; runs in CI")
+
+
+def _ns(project: Path, run_dir: Path, **extra: Any) -> argparse.Namespace:
+ """A minimal argparse.Namespace for calling cmd_serve/cmd_stop/cmd_status directly."""
+ base = {"project": project, "run_dir": run_dir, "pid_file": None}
+ base.update(extra)
+ return argparse.Namespace(**base)
+
+
+class _HeldPidLock:
+ """A pid lock the test body may hand back early, at most once.
+
+ The ``stop``-path tests below release the lock mid-test, from inside
+ a fake ``os.kill``, to simulate the daemon exiting and dropping its
+ flock. ``released`` is how ``held_pid_lock`` knows not to close the
+ same descriptor a second time on the way out -- by then the number
+ may belong to something else entirely.
+ """
+
+ def __init__(self, fd: int) -> None:
+ self._fd = fd
+ self.released = False
+
+ def close(self) -> None:
+ if not self.released:
+ self.released = True
+ os.close(self._fd)
+
+
+@contextlib.contextmanager
+def held_pid_lock(pid_file: Path) -> Iterator[_HeldPidLock]:
+ """Hold ``pid_file``'s lock for the body, releasing it however the body ends."""
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ lock = _HeldPidLock(fd)
+ try:
+ yield lock
+ finally:
+ if not lock.released:
+ lock.released = True
+ os.close(fd)
+
+
+@pytest.fixture
+def short_run_dir() -> Iterator[Path]:
+ """A run directory short enough to hold a unix-socket path.
+
+ ``pytest``'s own ``tmp_path`` fixture nests under
+ ``pytest-of-<user>/pytest-<n>/<test-name>/`` inside ``$TMPDIR``, which
+ in this sandboxed dev environment is already long enough on its own
+ to blow the ~103-byte ``sun_path`` limit before ``run_dir`` even adds
+ ``podman.sock``. ``tempfile.mkdtemp()`` sits directly under
+ ``$TMPDIR`` with none of that nesting, so it stays short everywhere
+ ``tmp_path`` might not. It is also already 0700 and owned by us, so
+ it satisfies ``check_run_dir``'s "custom run-dir" branch as-is.
+ """
+ d = Path(tempfile.mkdtemp(prefix="cg-"))
+ try:
+ yield d
+ finally:
+ shutil.rmtree(d, ignore_errors=True)
+
+
+class _RealSocketBackend:
+ """A ``FakeBackend`` served over a real filesystem unix socket.
+
+ ``tests/fakebackend.FakeBackend`` only ever hands out in-process
+ ``socket.socketpair()`` connections (the sandbox refuses ``bind()``,
+ so it never listens on a path) -- but ``daemon.run()`` needs a real
+ socket path to hand to ``unix_connector`` for a ``Backend``. This
+ thin wrapper does the one real bind these daemon tests need, so it
+ can hit the same ``PermissionError`` the sandbox raises and skip
+ exactly like every other bind-touching test in this suite.
+ """
+
+ def __init__(self, socket_path: Path) -> None:
+ self.socket = socket_path
+ self._fake = FakeBackend()
+ self._server: asyncio.AbstractServer | None = None
+
+ async def start(self) -> None:
+ self._server = await asyncio.start_unix_server(self._fake._handle, path=str(self.socket))
+
+ async def stop(self) -> None:
+ """Stop serving, without waiting on a connection nobody will close.
+
+ ``wait_closed`` waits for every accepted connection's handler
+ too (Python 3.12.1 and later), and the fake's handler sits
+ reading the next request on a keep-alive connection the gateway
+ has not closed yet. Teardown is bounded so a test that leaves
+ one open fails on its own assertion rather than wedging the run.
+ """
+ if self._server is not None:
+ self._server.close()
+ with contextlib.suppress(TimeoutError):
+ await asyncio.wait_for(self._server.wait_closed(), 5)
+
+
+@contextlib.asynccontextmanager
+async def _gateway(
+ project_root: Path, run_dir: Path, idle_timeout: float
+) -> AsyncIterator[tuple[daemon.Config, asyncio.Task[int]]]:
+ """A running ``daemon.run()`` task with a real backend socket behind it.
+
+ Skips the caller wherever the sandbox refuses the binds this needs,
+ exactly like every other bind-touching test in this suite: the
+ backend's own listener up front, the gateway's two sockets via the
+ task's early exception.
+ """
+ backend = _RealSocketBackend(run_dir / "d.sock")
+ try:
+ await asyncio.wait_for(backend.start(), 5)
+ except PermissionError:
+ pytest.skip("sandbox denies unix bind; runs in CI")
+ try:
+ cfg = daemon.Config(
+ project_root,
+ run_dir,
+ ("podman", "docker"),
+ "off",
+ 8899,
+ None,
+ (),
+ idle_timeout,
+ "INFO",
+ run_dir / "pid",
+ )
+ found = [Backend("podman", backend.socket, "host.containers.internal")]
+ task = asyncio.create_task(daemon.run(cfg, discover_fn=lambda *a, **k: found, platform="Darwin"))
+ await asyncio.sleep(0.3)
+ if task.done():
+ exc = task.exception()
+ if isinstance(exc, PermissionError):
+ pytest.skip("sandbox denies unix bind; runs in CI")
+ if exc is not None:
+ raise exc
+ try:
+ yield cfg, task
+ finally:
+ # Only reached when the body did not get the daemon to exit
+ # on its own -- the failure is the body's to report, so the
+ # teardown just makes sure nothing is left running behind it.
+ if not task.done():
+ task.cancel()
+ await asyncio.wait([task], timeout=5)
+ finally:
+ await asyncio.wait_for(backend.stop(), 5)
+
+
+async def _ping(sock_path: Path) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]:
+ """Ping the gateway over a fresh client connection, and leave it open.
+
+ The response is read by its framing rather than to EOF: the gateway
+ keeps the connection alive after a ``/_ping``, so a read to EOF
+ would only return once the daemon tore the connection down, which
+ is the very thing the callers below are measuring.
+ """
+ try:
+ r, w = await asyncio.wait_for(asyncio.open_unix_connection(str(sock_path)), 5)
+ except PermissionError:
+ pytest.skip("sandbox denies unix socket connections; runs in CI")
+ w.write(b"GET /_ping HTTP/1.1\r\nHost: x\r\n\r\n")
+ await asyncio.wait_for(w.drain(), 5)
+ # Every await here is bounded: a gateway that accepts the connection
+ # and then never answers must fail the test, not wedge the run.
+ assert b"200 OK" in await asyncio.wait_for(r.readuntil(b"\r\n\r\n"), 5)
Review Comment:
## CodeQL / Potentially uninitialized local variable
Local variable 'r' may be used before it is initialized.
[Show more details](https://github.com/apache/magpie/security/code-scanning/83)
##########
tools/container-gateway/tests/test_daemon.py:
##########
@@ -0,0 +1,1315 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Daemon plumbing: paths, guards, idle exit, status and stop.
+
+Threat model exercised throughout this file: the daemon runs OUTSIDE the
+sandbox with the operator's own privileges, while the sandboxed agent
+can create, delete and symlink anything under the project tree,
+including ``.apache-magpie-local/run/``. Every guard test below plants
+exactly the kind of hostile filesystem state that threat model implies
+and checks the guard refuses it -- no bind needed for any of them.
+
+No ``pytest-asyncio`` in the ``magpie-dev`` dependency group, so each
+async scenario is a plain ``def`` test driving its coroutine through the
+``run()`` helper, exactly as ``test_http.py`` and ``test_relay.py`` do.
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import contextlib
+import json
+import os
+import shutil
+import signal
+import subprocess
+import sys
+import tempfile
+from collections.abc import AsyncIterator, Coroutine, Iterator
+from pathlib import Path
+from typing import Any, TypeVar
+
+import pytest
+
+from container_gateway import __main__ as cli
+from container_gateway import daemon
+from container_gateway.backends import Backend
+
+from .fakebackend import FakeBackend
+
+SRC = Path(__file__).resolve().parents[1] / "src"
+
+_T = TypeVar("_T")
+
+# Every scenario in this file is bounded. A daemon test that wedges --
+# waiting on a bind that never completes, a socket nobody answers, an
+# idle timer that never fires -- must fail in seconds, naming itself,
+# rather than hang the whole run until CI's job limit kills it with no
+# output at all. Generous enough that no healthy scenario can reach it:
+# the longest one here idles out after 1.5s.
+SCENARIO_TIMEOUT = 15.0
+# The same bound for the subprocess-level CLI tests further down.
+SUBPROCESS_TIMEOUT = 30
+
+
+def run(coro: Coroutine[Any, Any, _T], timeout: float = SCENARIO_TIMEOUT) -> _T:
+ """Drive a coroutine to completion without pytest-asyncio, under a hard bound."""
+
+ async def bounded() -> _T:
+ return await asyncio.wait_for(coro, timeout)
+
+ return asyncio.run(bounded())
+
+
+async def _tcp_listener_or_skip() -> asyncio.AbstractServer:
+ """A loopback TCP listener, skipping the caller where the sandbox refuses ``bind()``.
+
+ Returning the server rather than binding inside the caller's ``try``
+ keeps the caller's ``finally`` from ever referencing a name that was
+ never assigned.
+ """
+ try:
+ return await asyncio.start_server(lambda r, w: None, host="127.0.0.1", port=0)
+ except PermissionError:
+ pytest.skip("sandbox denies TCP bind; runs in CI")
+
+
+def _ns(project: Path, run_dir: Path, **extra: Any) -> argparse.Namespace:
+ """A minimal argparse.Namespace for calling cmd_serve/cmd_stop/cmd_status directly."""
+ base = {"project": project, "run_dir": run_dir, "pid_file": None}
+ base.update(extra)
+ return argparse.Namespace(**base)
+
+
+class _HeldPidLock:
+ """A pid lock the test body may hand back early, at most once.
+
+ The ``stop``-path tests below release the lock mid-test, from inside
+ a fake ``os.kill``, to simulate the daemon exiting and dropping its
+ flock. ``released`` is how ``held_pid_lock`` knows not to close the
+ same descriptor a second time on the way out -- by then the number
+ may belong to something else entirely.
+ """
+
+ def __init__(self, fd: int) -> None:
+ self._fd = fd
+ self.released = False
+
+ def close(self) -> None:
+ if not self.released:
+ self.released = True
+ os.close(self._fd)
+
+
+@contextlib.contextmanager
+def held_pid_lock(pid_file: Path) -> Iterator[_HeldPidLock]:
+ """Hold ``pid_file``'s lock for the body, releasing it however the body ends."""
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ lock = _HeldPidLock(fd)
+ try:
+ yield lock
+ finally:
+ if not lock.released:
+ lock.released = True
+ os.close(fd)
+
+
+@pytest.fixture
+def short_run_dir() -> Iterator[Path]:
+ """A run directory short enough to hold a unix-socket path.
+
+ ``pytest``'s own ``tmp_path`` fixture nests under
+ ``pytest-of-<user>/pytest-<n>/<test-name>/`` inside ``$TMPDIR``, which
+ in this sandboxed dev environment is already long enough on its own
+ to blow the ~103-byte ``sun_path`` limit before ``run_dir`` even adds
+ ``podman.sock``. ``tempfile.mkdtemp()`` sits directly under
+ ``$TMPDIR`` with none of that nesting, so it stays short everywhere
+ ``tmp_path`` might not. It is also already 0700 and owned by us, so
+ it satisfies ``check_run_dir``'s "custom run-dir" branch as-is.
+ """
+ d = Path(tempfile.mkdtemp(prefix="cg-"))
+ try:
+ yield d
+ finally:
+ shutil.rmtree(d, ignore_errors=True)
+
+
+class _RealSocketBackend:
+ """A ``FakeBackend`` served over a real filesystem unix socket.
+
+ ``tests/fakebackend.FakeBackend`` only ever hands out in-process
+ ``socket.socketpair()`` connections (the sandbox refuses ``bind()``,
+ so it never listens on a path) -- but ``daemon.run()`` needs a real
+ socket path to hand to ``unix_connector`` for a ``Backend``. This
+ thin wrapper does the one real bind these daemon tests need, so it
+ can hit the same ``PermissionError`` the sandbox raises and skip
+ exactly like every other bind-touching test in this suite.
+ """
+
+ def __init__(self, socket_path: Path) -> None:
+ self.socket = socket_path
+ self._fake = FakeBackend()
+ self._server: asyncio.AbstractServer | None = None
+
+ async def start(self) -> None:
+ self._server = await asyncio.start_unix_server(self._fake._handle, path=str(self.socket))
+
+ async def stop(self) -> None:
+ """Stop serving, without waiting on a connection nobody will close.
+
+ ``wait_closed`` waits for every accepted connection's handler
+ too (Python 3.12.1 and later), and the fake's handler sits
+ reading the next request on a keep-alive connection the gateway
+ has not closed yet. Teardown is bounded so a test that leaves
+ one open fails on its own assertion rather than wedging the run.
+ """
+ if self._server is not None:
+ self._server.close()
+ with contextlib.suppress(TimeoutError):
+ await asyncio.wait_for(self._server.wait_closed(), 5)
+
+
+@contextlib.asynccontextmanager
+async def _gateway(
+ project_root: Path, run_dir: Path, idle_timeout: float
+) -> AsyncIterator[tuple[daemon.Config, asyncio.Task[int]]]:
+ """A running ``daemon.run()`` task with a real backend socket behind it.
+
+ Skips the caller wherever the sandbox refuses the binds this needs,
+ exactly like every other bind-touching test in this suite: the
+ backend's own listener up front, the gateway's two sockets via the
+ task's early exception.
+ """
+ backend = _RealSocketBackend(run_dir / "d.sock")
+ try:
+ await asyncio.wait_for(backend.start(), 5)
+ except PermissionError:
+ pytest.skip("sandbox denies unix bind; runs in CI")
+ try:
+ cfg = daemon.Config(
+ project_root,
+ run_dir,
+ ("podman", "docker"),
+ "off",
+ 8899,
+ None,
+ (),
+ idle_timeout,
+ "INFO",
+ run_dir / "pid",
+ )
+ found = [Backend("podman", backend.socket, "host.containers.internal")]
+ task = asyncio.create_task(daemon.run(cfg, discover_fn=lambda *a, **k: found, platform="Darwin"))
+ await asyncio.sleep(0.3)
+ if task.done():
+ exc = task.exception()
+ if isinstance(exc, PermissionError):
+ pytest.skip("sandbox denies unix bind; runs in CI")
+ if exc is not None:
+ raise exc
+ try:
+ yield cfg, task
+ finally:
+ # Only reached when the body did not get the daemon to exit
+ # on its own -- the failure is the body's to report, so the
+ # teardown just makes sure nothing is left running behind it.
+ if not task.done():
+ task.cancel()
+ await asyncio.wait([task], timeout=5)
+ finally:
+ await asyncio.wait_for(backend.stop(), 5)
+
+
+async def _ping(sock_path: Path) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]:
+ """Ping the gateway over a fresh client connection, and leave it open.
+
+ The response is read by its framing rather than to EOF: the gateway
+ keeps the connection alive after a ``/_ping``, so a read to EOF
+ would only return once the daemon tore the connection down, which
+ is the very thing the callers below are measuring.
+ """
+ try:
+ r, w = await asyncio.wait_for(asyncio.open_unix_connection(str(sock_path)), 5)
+ except PermissionError:
+ pytest.skip("sandbox denies unix socket connections; runs in CI")
+ w.write(b"GET /_ping HTTP/1.1\r\nHost: x\r\n\r\n")
+ await asyncio.wait_for(w.drain(), 5)
+ # Every await here is bounded: a gateway that accepts the connection
+ # and then never answers must fail the test, not wedge the run.
+ assert b"200 OK" in await asyncio.wait_for(r.readuntil(b"\r\n\r\n"), 5)
+ assert await asyncio.wait_for(r.readexactly(2), 5) == b"OK"
+ return r, w
+
+
+async def _close_client(w: asyncio.StreamWriter) -> None:
+ """Close a client connection and wait for the close to land.
+
+ Guarded twice over: the peer may already be gone (``OSError``), and
+ a close that does not complete must not wedge a test that has
+ finished with the connection anyway.
+ """
+ w.close()
+ with contextlib.suppress(OSError, TimeoutError):
+ await asyncio.wait_for(w.wait_closed(), 5)
+
+
+# --------------------------------------------------------------- paths
+
+
+def test_paths_and_socket_length(tmp_path: Path) -> None:
+ p = daemon.paths(tmp_path)
+ assert p["podman"].name == "podman.sock" and p["docker"].name == "docker.sock"
+ # A literal short path, not tmp_path: with TMPDIR unset, tmp_path's
+ # pytest-of-<user>/pytest-<n>/<test-name>/ nesting is already long
+ # enough to exceed the ~103-byte sun_path limit on its own, and
+ # check_socket_path only measures byte length.
+ daemon.check_socket_path(Path("/tmp/ok.sock"))
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_socket_path(Path("/" + "x" * 120 + "/podman.sock"))
+ assert exc.value.code == 2
+
+
+# ------------------------------------------------ C2: run dir / symlinks
+
+
+def test_check_run_dir_default_layout_creates_both_dirs_0700(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ run_dir = project_root / ".apache-magpie-local" / "run"
+ daemon.check_run_dir(run_dir, project_root)
+ assert (project_root / ".apache-magpie-local").stat().st_mode & 0o777 == 0o700
+ assert run_dir.stat().st_mode & 0o777 == 0o700
+
+
+def test_check_run_dir_refuses_world_writable_existing_dir(tmp_path: Path) -> None:
+ project_root = tmp_path
+ run_dir = tmp_path / "custom-run"
+ daemon.check_run_dir(run_dir, project_root)
+ assert run_dir.stat().st_mode & 0o777 == 0o700
+ run_dir.chmod(0o777)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(run_dir, project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_run(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ magpie_local = project_root / ".apache-magpie-local"
+ magpie_local.mkdir(parents=True, mode=0o700)
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (magpie_local / "run").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(magpie_local / "run", project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_apache_magpie_local(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (project_root / ".apache-magpie-local").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(project_root / ".apache-magpie-local" / "run", project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_custom_run_dir(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ custom = tmp_path / "custom-run"
+ custom.symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(custom, project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_accepts_a_symlinked_ancestor_above_the_project_root(tmp_path: Path) -> None:
+ """The host's own layout is not the threat model.
+
+ ``/tmp`` is a symlink to ``/private/tmp`` on macOS, ``/var`` likewise,
+ and a home directory can sit on a linked volume -- a project reached
+ through any of those must be served, not refused. The same shape is
+ built portably here, so it runs on Linux too: a symlinked directory
+ with a real project tree underneath it.
+ """
+ real = tmp_path / "real"
+ real.mkdir()
+ link = tmp_path / "link"
+ link.symlink_to(real)
+ project_root = link / "proj"
+ project_root.mkdir()
+ run_dir = project_root / ".apache-magpie-local" / "run"
+ daemon.check_run_dir(run_dir, project_root)
+ assert (real / "proj" / ".apache-magpie-local" / "run").is_dir()
+ assert daemon.validate_run_dir(run_dir, project_root) is True
+
+
+def test_check_run_dir_accepts_a_custom_run_dir_under_a_symlinked_ancestor(tmp_path: Path) -> None:
+ """``--run-dir /tmp/whatever`` on macOS: the parent chain resolves, it is not refused."""
+ real = tmp_path / "real"
+ real.mkdir()
+ link = tmp_path / "link"
+ link.symlink_to(real)
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ run_dir = link / "custom-run"
+ daemon.check_run_dir(run_dir, project_root)
+ assert (real / "custom-run").is_dir()
+ assert (real / "custom-run").stat().st_mode & 0o777 == 0o700
+ assert daemon.validate_run_dir(run_dir, project_root) is True
+
+
+def test_check_run_dir_refuses_a_symlinked_run_under_a_symlinked_ancestor(tmp_path: Path) -> None:
+ """Resolving the chain above the anchor does not excuse a symlink AT an owned component."""
+ real = tmp_path / "real"
+ real.mkdir()
+ link = tmp_path / "link"
+ link.symlink_to(real)
+ project_root = link / "proj"
+ magpie_local = project_root / ".apache-magpie-local"
+ magpie_local.mkdir(parents=True, mode=0o700)
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (magpie_local / "run").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(magpie_local / "run", project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_a_foreign_owned_intermediate_component(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Ownership is still checked on every component the gateway owns, not just the last one."""
+ project_root = tmp_path / "proj"
+ (project_root / ".apache-magpie-local").mkdir(parents=True, mode=0o700)
+ foreign = os.geteuid() + 1 # captured before the patch, or the lambda recurses
+ monkeypatch.setattr(os, "geteuid", lambda: foreign)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(project_root / ".apache-magpie-local" / "run", project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_a_group_writable_intermediate_component(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ magpie_local = project_root / ".apache-magpie-local"
+ magpie_local.mkdir(parents=True, mode=0o700)
+ magpie_local.chmod(0o770)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(magpie_local / "run", project_root)
+ assert exc.value.code == 2
+
+
+def test_validate_run_dir_refuses_a_group_writable_intermediate_component(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ magpie_local = project_root / ".apache-magpie-local"
+ (magpie_local / "run").mkdir(parents=True, mode=0o700)
+ magpie_local.chmod(0o770)
+ with pytest.raises(SystemExit) as exc:
+ daemon.validate_run_dir(magpie_local / "run", project_root)
+ assert exc.value.code == 2
+
+
+# ------------------------------------------- D5: missing ancestors refuse
+
+
+def test_check_run_dir_refuses_missing_project_root(tmp_path: Path) -> None:
+ missing_root = tmp_path / "does-not-exist"
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(missing_root / ".apache-magpie-local" / "run", missing_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_missing_custom_run_dir_parent(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ missing_parent_run_dir = tmp_path / "does-not-exist" / "run"
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(missing_parent_run_dir, project_root)
+ assert exc.value.code == 2
+
+
+def test_validate_run_dir_false_when_project_root_missing(tmp_path: Path) -> None:
+ missing_root = tmp_path / "does-not-exist"
+ assert daemon.validate_run_dir(missing_root / ".apache-magpie-local" / "run", missing_root) is False
+
+
+def test_validate_run_dir_false_when_custom_parent_missing(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ missing_parent_run_dir = tmp_path / "does-not-exist" / "run"
+ assert daemon.validate_run_dir(missing_parent_run_dir, project_root) is False
+
+
+# --------------------------------------- D6: lstat-then-mkdir race safety
+
+
+def test_ensure_owned_private_dir_handles_mkdir_race_with_planted_symlink(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ target = tmp_path / "custom-run"
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ real_mkdir = Path.mkdir
+
+ def racy_mkdir(self: Path, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None:
+ if self == target:
+ target.symlink_to(evil) # someone (or something) won the race and planted a symlink
+ raise FileExistsError(f"[Errno 17] File exists: '{target}'")
+ real_mkdir(self, mode, parents=parents, exist_ok=exist_ok)
+
+ monkeypatch.setattr(Path, "mkdir", racy_mkdir)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(target, tmp_path)
+ assert exc.value.code == 2
+
+
+# --------------------------------------------------- C2: socket guards
+
+
+def test_check_socket_type_refuses_non_socket(tmp_path: Path) -> None:
+ p = tmp_path / "podman.sock"
+ p.write_text("not a socket")
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_socket_type(p)
+ assert exc.value.code == 2
+
+
+def test_check_socket_type_allows_missing_path(tmp_path: Path) -> None:
+ daemon.check_socket_type(tmp_path / "missing.sock") # nothing there yet: fine
+
+
+# ------------------------------------------------------ C2: pid / log fd
+
+
+def test_acquire_pid_lock_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.pid"
+ target.write_text("")
+ link = tmp_path / "container-gateway.pid"
+ link.symlink_to(target)
+ # `fd` stays None because the refusal fires before the open returns;
+ # the `finally` is what keeps this test from leaking a descriptor if
+ # `acquire_pid_lock` ever stops refusing.
+ fd: int | None = None
+ try:
+ with pytest.raises(SystemExit) as exc:
+ fd = daemon.acquire_pid_lock(link)
+ assert exc.value.code == 2
+ finally:
+ if fd is not None:
+ os.close(fd)
+
+
+def test_probe_pid_lock_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.pid"
+ target.write_text("")
+ link = tmp_path / "container-gateway.pid"
+ link.symlink_to(target)
+ with pytest.raises(SystemExit) as exc:
+ daemon.probe_pid_lock(link)
+ assert exc.value.code == 2
+
+
+def test_probe_pid_lock_not_running_when_run_dir_absent(tmp_path: Path) -> None:
+ never_created = tmp_path / "never" / "container-gateway.pid"
+ assert daemon.probe_pid_lock(never_created) == (False, None)
+
+
+def test_open_log_fd_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.log"
+ target.write_text("")
+ link = tmp_path / "container-gateway.log"
+ link.symlink_to(target)
+ # Same shape as the pid-lock refusal above: nothing should be opened,
+ # and the `finally` proves it rather than assuming it.
+ fd: int | None = None
+ try:
+ with pytest.raises(SystemExit) as exc:
+ fd = cli._open_log_fd(link)
+ assert exc.value.code == 2
+ finally:
+ if fd is not None:
+ os.close(fd)
+
+
+# --------------------- D2: acquire_pid_lock never blanks a live pid file
+
+
+def test_acquire_pid_lock_does_not_blank_a_live_daemons_pid_file(tmp_path: Path) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ second: int | None = None
+ try:
+ os.ftruncate(fd, 0)
+ os.lseek(fd, 0, 0)
+ os.write(fd, b"4242\n")
+ os.fsync(fd)
+ second = daemon.acquire_pid_lock(pid_file)
+ assert second is None
+ assert pid_file.read_text() == "4242\n"
+ finally:
+ if second is not None:
+ os.close(second) # only reachable if the contended probe ever won the lock
+ os.close(fd)
+
+
+# ------------------------------------- D1: status/stop bypassed check_run_dir
+
+
+def test_pid_file_is_trustworthy_none_when_missing(tmp_path: Path) -> None:
+ assert daemon.pid_file_is_trustworthy(tmp_path / "container-gateway.pid") is None
+
+
+def test_pid_file_is_trustworthy_true_for_a_lock_created_file(tmp_path: Path) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ assert daemon.pid_file_is_trustworthy(pid_file) is True
+ finally:
+ os.close(fd)
+
+
+def test_pid_file_is_trustworthy_false_for_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.pid"
+ target.write_text("4242\n")
+ target.chmod(0o600)
+ link = tmp_path / "container-gateway.pid"
+ link.symlink_to(target)
+ assert daemon.pid_file_is_trustworthy(link) is False
+
+
+def test_pid_file_is_trustworthy_false_for_wrong_mode(tmp_path: Path) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ pid_file.write_text("4242\n")
+ pid_file.chmod(0o644)
+ assert daemon.pid_file_is_trustworthy(pid_file) is False
+
+
+def test_cli_status_refuses_symlinked_run_dir(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ magpie_local = project_root / ".apache-magpie-local"
+ magpie_local.mkdir(parents=True, mode=0o700)
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (magpie_local / "run").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ cli.cmd_status(_ns(project_root, magpie_local / "run"))
+ assert exc.value.code == 2
+
+
+def test_cli_stop_refuses_symlinked_run_dir_without_signalling(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ project_root = tmp_path / "proj"
+ magpie_local = project_root / ".apache-magpie-local"
+ magpie_local.mkdir(parents=True, mode=0o700)
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (magpie_local / "run").symlink_to(evil)
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ with pytest.raises(SystemExit) as exc:
+ cli.cmd_stop(_ns(project_root, magpie_local / "run"))
+ assert exc.value.code == 2
+ assert calls == []
+
+
+def test_cli_stop_refuses_pid_file_with_wrong_mode(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ pid_file.write_text("4242\n")
+ pid_file.chmod(0o644)
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ with pytest.raises(SystemExit) as exc:
+ cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert exc.value.code == 2
+ assert calls == []
+
+
+def test_cli_status_treats_wrong_mode_pid_file_as_not_running(
+ tmp_path: Path, short_run_dir: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ pid_file.write_text("4242\n")
+ pid_file.chmod(0o644)
+ rc = cli.cmd_status(_ns(tmp_path, short_run_dir))
+ out = json.loads(capsys.readouterr().out)
+ assert rc == 3
+ assert out["running"] is False
+ # Untrustworthy content is left alone, not deleted, by `status`.
+ assert pid_file.exists()
+
+
+# -------------------------------- D4: stop verifies the signalled process
+
+
+def test_cli_stop_refuses_when_process_does_not_look_like_gateway(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ monkeypatch.setattr("container_gateway.backends.default_runner", lambda argv: "bash -c sleep 100")
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+def test_cli_stop_refuses_a_process_that_merely_mentions_the_module_name(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """An editor opened on a file named ``container_gateway.py`` is not the gateway.
+
+ A substring check on the ``ps`` line would wrongly treat this as a
+ match; the argv-shape check must not.
+ """
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ monkeypatch.setattr(
+ "container_gateway.backends.default_runner", lambda argv: "vim container_gateway.py"
+ )
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+def test_cli_stop_checks_only_the_first_line_of_ps_output(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A gateway-shaped second line must not rescue a non-gateway first line."""
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ monkeypatch.setattr(
+ "container_gateway.backends.default_runner",
+ lambda argv: "bash -c sleep 100\npython3 -m container_gateway serve --project /x",
+ )
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+def test_cli_stop_signals_when_process_is_the_console_script(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The installed ``container-gateway`` console script is also recognised, not just ``python -m``."""
+ pid_file = short_run_dir / "container-gateway.pid"
+ our_pid = os.getpid()
+ calls: list[tuple[int, int]] = []
+ terminated = False
+
+ with held_pid_lock(pid_file) as lock:
+
+ def fake_kill(pid: int, sig: int) -> None:
+ nonlocal terminated
+ calls.append((pid, sig))
+ if sig == signal.SIGTERM:
+ terminated = True
+ lock.close() # simulate the daemon exiting: release the flock
+ elif terminated:
+ raise ProcessLookupError
+
+ monkeypatch.setattr(os, "kill", fake_kill)
+ monkeypatch.setattr(
+ "container_gateway.backends.default_runner",
+ lambda argv: "/usr/local/bin/container-gateway serve --project /x",
+ )
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert rc == 0
+ assert (our_pid, signal.SIGTERM) in calls
+
+
+@pytest.mark.parametrize(
+ "command_line",
+ [
+ "python3 -u -m container_gateway serve --project /x",
+ "uv run python -m container_gateway serve --project /x",
+ ],
+)
+def test_cli_stop_signals_a_python_dash_m_invocation_with_extra_argv(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch, command_line: str
+) -> None:
+ """Interpreter flags (``-u``) and a runner prefix (``uv run``) do not defeat the argv-shape match."""
+ pid_file = short_run_dir / "container-gateway.pid"
+ our_pid = os.getpid()
+ calls: list[tuple[int, int]] = []
+ terminated = False
+
+ with held_pid_lock(pid_file) as lock:
+
+ def fake_kill(pid: int, sig: int) -> None:
+ nonlocal terminated
+ calls.append((pid, sig))
+ if sig == signal.SIGTERM:
+ terminated = True
+ lock.close() # simulate the daemon exiting: release the flock
+ elif terminated:
+ raise ProcessLookupError
+
+ monkeypatch.setattr(os, "kill", fake_kill)
+ monkeypatch.setattr("container_gateway.backends.default_runner", lambda argv: command_line)
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert rc == 0
+ assert (our_pid, signal.SIGTERM) in calls
+
+
+def test_cli_stop_refuses_when_ps_is_unavailable(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ monkeypatch.setattr("container_gateway.backends.default_runner", lambda argv: None)
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+# --------------------------------------------------------------- C1: pid
+
+
+@pytest.mark.parametrize("content", ["-1", "0", "1", "abc", "12 34", "99999999999", ""])
+def test_read_pid_rejects_unsafe_content(tmp_path: Path, content: str) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ pid_file.write_text(content)
+ assert daemon.read_pid(pid_file) is None
+
+
+def test_read_pid_accepts_a_real_pid(tmp_path: Path) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ pid_file.write_text("42\n")
+ assert daemon.read_pid(pid_file) == 42
+
+
+def test_pid_alive_false_for_pid_le_1() -> None:
+ assert daemon.pid_alive(0) is False
+ assert daemon.pid_alive(1) is False
+ assert daemon.pid_alive(-1) is False
+
+
+@pytest.mark.parametrize("content", ["-1", "0", "1", "abc", "12 34"])
+def test_cli_stop_with_unsafe_pid_file_does_not_signal(
+ tmp_path: Path, short_run_dir: Path, content: str, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ pid_file.write_text(content)
+ pid_file.chmod(0o600) # a trustworthy *file*; the *content* is what's unsafe here
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 0
+
+
+def test_cli_stop_does_not_signal_when_lock_held_but_pid_content_poisoned(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A live, lock-holding instance whose pid-file *content* was overwritten afterwards.
+
+ ``stop`` must refuse to guess: something is clearly running (the
+ lock says so), but nothing safe to signal can be read back out of
+ the file.
+ """
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ os.ftruncate(fd, 0)
+ os.lseek(fd, 0, 0)
+ os.write(fd, b"-1\n")
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+# --------------------------------------------- I3+I4: flock single instance
+
+
+def test_cli_serve_short_circuits_when_lock_already_held(tmp_path: Path, short_run_dir: Path) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ ns = _ns(
+ tmp_path,
+ short_run_dir,
+ daemon=False,
+ backend=None,
+ egress="off",
+ egress_port=8899,
+ egress_host=None,
+ extra_bind_root=None,
+ idle_timeout=5.0,
+ backend_timeout=60.0,
+ log_level="INFO",
+ )
+ assert cli.cmd_serve(ns) == 0
+ assert not (short_run_dir / "podman.sock").exists()
+ assert not (short_run_dir / "docker.sock").exists()
+ finally:
+ os.close(fd)
+
+
+def test_cli_status_reports_running_when_lock_held(
+ tmp_path: Path, short_run_dir: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ rc = cli.cmd_status(_ns(tmp_path, short_run_dir))
+ out = json.loads(capsys.readouterr().out)
+ finally:
+ os.close(fd)
+ assert rc == 0
+ assert out["running"] is True
+ assert out["pid"] == os.getpid()
+ assert out["serving"] == [] # no sockets actually bound in this test
+
+
+def test_cli_status_removes_stale_pid_file_when_no_lock_held(
+ tmp_path: Path, short_run_dir: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ pid_file.write_text("424242\n") # a stale pid; nobody holds its lock
+ pid_file.chmod(0o600) # a trustworthy, well-formed pid file -- just stale
+ rc = cli.cmd_status(_ns(tmp_path, short_run_dir))
+ out = json.loads(capsys.readouterr().out)
+ assert rc == 3
+ assert out["running"] is False
+ assert out["pid"] is None
+ assert not pid_file.exists()
+
+
+def test_cli_stop_signals_the_pid_and_reports_stopped(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ our_pid = os.getpid()
+ calls: list[tuple[int, int]] = []
+ terminated = False
+
+ with held_pid_lock(pid_file) as lock:
+
+ def fake_kill(pid: int, sig: int) -> None:
+ nonlocal terminated
+ calls.append((pid, sig))
+ if sig == signal.SIGTERM:
+ terminated = True
+ lock.close() # simulate the daemon exiting: release the flock
+ elif terminated:
+ raise ProcessLookupError
+
+ monkeypatch.setattr(os, "kill", fake_kill)
+ monkeypatch.setattr(
+ "container_gateway.backends.default_runner",
+ lambda argv: "python3 -m container_gateway serve --project /x",
+ )
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert rc == 0
+ assert (our_pid, signal.SIGTERM) in calls
+
+
+def test_cli_stop_when_lock_never_held_is_a_noop(tmp_path: Path, short_run_dir: Path) -> None:
+ assert cli.cmd_stop(_ns(tmp_path, short_run_dir)) == 0
+
+
+def test_cli_stop_prints_a_message_when_project_root_does_not_exist(
+ tmp_path: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ """A --project value that names nothing gets its own message, not the run-directory one."""
+ missing_root = tmp_path / "never-served"
+ run_dir = missing_root / ".apache-magpie-local" / "run"
+ rc = cli.cmd_stop(_ns(missing_root, run_dir))
+ out = capsys.readouterr().out
+ assert rc == 0
+ assert f"no project root at {missing_root}: nothing to stop" in out
+
+
+def test_cli_stop_prints_a_message_when_no_run_directory_ever_existed(
+ tmp_path: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ """A project that exists but was never served must not look identical to "stopped successfully"."""
+ project_root = tmp_path / "served-project"
+ project_root.mkdir()
+ run_dir = project_root / ".apache-magpie-local" / "run"
+ rc = cli.cmd_stop(_ns(project_root, run_dir))
+ out = capsys.readouterr().out
+ assert rc == 0
+ assert f"no run directory at {run_dir}: nothing to stop" in out
+
+
+# ------------------------- D3: unlink the pid file before closing its fd
+
+
+def test_run_unlinks_pid_file_before_closing_the_lock_fd(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ events: list[str] = []
+ real_unlink = Path.unlink
+ real_close = os.close
+ pid_file = short_run_dir / "pid"
+
+ def recording_unlink(self: Path, missing_ok: bool = False) -> None:
+ if self == pid_file:
+ events.append("unlink")
+ real_unlink(self, missing_ok=missing_ok)
+
+ def recording_close(fd: int) -> None:
+ events.append("close")
+ real_close(fd)
+
+ monkeypatch.setattr(Path, "unlink", recording_unlink)
+ monkeypatch.setattr(os, "close", recording_close)
+
+ cfg = daemon.Config(
+ tmp_path, short_run_dir, ("podman", "docker"), "off", 8899, None, (), 5.0, "INFO", pid_file
+ )
+
+ async def scenario() -> None:
+ rc = await asyncio.wait_for(daemon.run(cfg, discover_fn=lambda *a, **k: [], platform="Darwin"), 5)
+ assert rc == 0
+
+ run(scenario())
+ assert "unlink" in events
+ assert "close" in events
+ assert events.index("unlink") < events.index("close")
+
+
+# ---------------------------------------------------------------- I5
+
+
+def test_partial_bind_failure_cleans_up_first_socket_and_server(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ calls: list[Path] = []
+ closed: list[bool] = []
+
+ class _FakeServer:
+ def close(self) -> None:
+ closed.append(True)
+
+ async def wait_closed(self) -> None:
+ return None
+
+ async def fake_serve_unix(path: Path, handler: Any) -> _FakeServer:
+ calls.append(path)
+ if len(calls) == 2:
+ raise OSError("simulated bind failure")
+ path.write_text("") # stand in for "a socket file now exists here"
+ return _FakeServer()
+
+ monkeypatch.setattr(daemon, "serve_unix", fake_serve_unix)
+ cfg = daemon.Config(
+ tmp_path,
+ short_run_dir,
+ ("podman", "docker"),
+ "off",
+ 8899,
+ None,
+ (),
+ 5.0,
+ "INFO",
+ short_run_dir / "pid",
+ )
+ found = [Backend("podman", short_run_dir / "upstream.sock", "host.containers.internal")]
+
+ async def scenario() -> None:
+ with pytest.raises(OSError, match="simulated bind failure"):
+ await asyncio.wait_for(daemon.run(cfg, discover_fn=lambda *a, **k: found, platform="Darwin"), 5)
+
+ run(scenario())
+ assert closed == [True]
+ assert not (short_run_dir / "podman.sock").exists()
+ assert not cfg.pid_file.exists()
+
+
+# ------------------------------------------------------- M9: probe_egress
+
+
+def test_probe_egress_true_when_something_listens() -> None:
+ async def scenario() -> None:
+ server = await _tcp_listener_or_skip()
+ try:
+ port = server.sockets[0].getsockname()[1]
+ assert await daemon.probe_egress("host.containers.internal", port) is True
+ finally:
+ server.close()
+ await server.wait_closed()
+
+ run(scenario())
+
+
+def test_probe_egress_false_when_nothing_listens() -> None:
+ async def scenario() -> None:
+ server = await _tcp_listener_or_skip()
+ port = server.sockets[0].getsockname()[1]
+ server.close()
+ await server.wait_closed()
+ assert await daemon.probe_egress("host.containers.internal", port) is False
+
+ run(scenario())
+
+
+# ------------------------------------------------------------ full run()
+
+
+def test_run_without_backends_exits_zero(tmp_path: Path, short_run_dir: Path) -> None:
+ async def scenario() -> None:
+ cfg = daemon.Config(
+ tmp_path,
+ short_run_dir,
+ ("podman", "docker"),
+ "off",
+ 8899,
+ None,
+ (),
+ 5.0,
+ "INFO",
+ short_run_dir / "pid",
+ )
+ rc = await asyncio.wait_for(daemon.run(cfg, discover_fn=lambda *a, **k: [], platform="Darwin"), 5)
+ assert rc == 0
+ assert not (short_run_dir / "podman.sock").exists()
+
+ run(scenario())
+
+
+def test_run_serves_both_sockets_from_podman_only_and_idles_out(tmp_path: Path, short_run_dir: Path) -> None:
+ async def scenario() -> None:
+ async with _gateway(tmp_path, short_run_dir, 1.5) as (cfg, task):
+ clients = [await _ping(short_run_dir / name) for name in ("podman.sock", "docker.sock")]
+ assert daemon.read_pid(cfg.pid_file) == os.getpid()
+ # What is being measured below is the daemon's own exit, so
+ # the test's connections go first and the idle clock runs
+ # against nothing but the daemon. The test after this one is
+ # the one that leaves a connection open on purpose.
+ for _, w in clients:
+ await _close_client(w)
+ rc = await asyncio.wait_for(task, 10) # idle timeout fires 1.5s after the last close
+ assert rc == 0
+ assert not cfg.pid_file.exists()
+
+ run(scenario())
+
+
+def test_handlers_cancel_all_lets_wait_closed_return() -> None:
+ """The one mechanism the two idle-exit tests around this one rest on.
+
+ Since Python 3.12.1 ``Server.wait_closed()`` returns only once every
+ accepted connection's handler has finished, so a handler parked on a
+ client that sends nothing more holds the server -- and the process
+ -- open indefinitely. The loopback listener here stands in for the
+ gateway's unix sockets: the same ``asyncio.Server``, over a bind
+ this sandbox allows where it refuses a unix one.
+ """
+
+ async def scenario() -> None:
+ handlers = daemon._Handlers()
+ started = asyncio.Event()
+ unwound = asyncio.Event()
+
+ async def blocked(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
+ started.set()
+ try:
+ await reader.read() # the next keep-alive request, which never comes
+ finally:
+ unwound.set()
+
+ try:
+ server = await asyncio.start_server(handlers.track(blocked), host="127.0.0.1", port=0)
+ except PermissionError:
+ pytest.skip("sandbox denies TCP bind; runs in CI")
+ try:
+ port = server.sockets[0].getsockname()[1]
Review Comment:
## CodeQL / Potentially uninitialized local variable
Local variable 'server' may be used before it is initialized.
[Show more details](https://github.com/apache/magpie/security/code-scanning/84)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@magpie.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(container-gateway): run podman and docker from inside the sandbox through a policy proxy [magpie]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk merged PR #1298:
URL: https://github.com/apache/magpie/pull/1298
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@magpie.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(container-gateway): run podman and docker from inside the sandbox through a policy proxy [magpie]
Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #1298:
URL: https://github.com/apache/magpie/pull/1298#discussion_r4058025294
##########
tools/container-gateway/tests/test_relay.py:
##########
@@ -0,0 +1,730 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""The relay end to end against the fake backend.
+
+No ``pytest-asyncio`` in the ``magpie-dev`` dependency group, so each
+scenario is a plain ``def`` test driving its coroutine through ``run()``,
+exactly as ``test_http.py`` does. The relay is driven directly over a
+``socket.socketpair()`` rather than through a bound gateway socket: the
+sandbox refuses ``bind()`` on a unix-domain path, and ``serve_unix`` (the
+only piece that binds) gets its own smoke test below.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import json
+from collections.abc import Coroutine
+from pathlib import Path
+from typing import Any, TypeVar
+
+import pytest
+
+from container_gateway import relay as relay_module
+from container_gateway.labels import LABEL_KEY
+from container_gateway.policy import PolicyContext
+from container_gateway.relay import Relay, _rewrite_name, serve_unix
+
+from .fakebackend import FakeBackend, socket_pair
+
+_T = TypeVar("_T")
+
+
+def run(coro: Coroutine[Any, Any, _T]) -> _T:
+ """Drive a coroutine to completion without pytest-asyncio."""
+ return asyncio.run(coro)
+
+
+def stack(root: Path) -> tuple[FakeBackend, Relay]:
+ """A fake daemon holding one owned and one foreign resource of each kind."""
+ backend = FakeBackend()
+ backend.add_container("aaa111", "mine", {LABEL_KEY: "-p"})
+ backend.add_container("bbb222", "theirs", {LABEL_KEY: "-q"})
+ backend.execs["ex1"] = "aaa111"
+ backend.execs["ex2"] = "bbb222"
+ backend.add_volume("myvol", {LABEL_KEY: "-p"})
+ backend.add_volume("theirvol", {LABEL_KEY: "-q"})
+ backend.add_network("mynet", {LABEL_KEY: "-p"})
+ backend.add_network("theirnet", {LABEL_KEY: "-q"})
+ ctx = PolicyContext("-p", root, (root,), {"HTTP_PROXY": "http://h:1"}, "inject-if-available")
+ return backend, Relay(backend.connect, ctx, backend_label=str(root / "d.sock"))
+
+
+async def call(relay: Relay, raw: bytes) -> tuple[int, bytes, bytes]:
+ """Send one request over a fresh client connection; return status, head, body."""
+ (reader, writer), server = await socket_pair()
+ served = asyncio.create_task(relay.handle(*server))
+ writer.write(raw)
+ await writer.drain()
+ writer.write_eof()
+ data = await asyncio.wait_for(reader.read(), 5)
+ await asyncio.wait_for(served, 5)
+ writer.close()
+ head, _, body = data.partition(b"\r\n\r\n")
+ return int(head.split(b" ")[1]), head, body
+
+
+async def call_raw(relay: Relay, raw: bytes) -> bytes:
+ """Like ``call``, but returns every byte the relay wrote, interim heads included."""
+ (reader, writer), server = await socket_pair()
+ served = asyncio.create_task(relay.handle(*server))
+ writer.write(raw)
+ await writer.drain()
+ writer.write_eof()
+ data = await asyncio.wait_for(reader.read(), 5)
+ await asyncio.wait_for(served, 5)
+ writer.close()
+ return data
+
+
+def dechunk(body: bytes) -> bytes:
+ out, rest = b"", body
+ while rest:
+ size, _, rest = rest.partition(b"\r\n")
+ n = int(size, 16)
+ if n == 0:
+ break
+ out, rest = out + rest[:n], rest[n + 2 :]
+ return out
+
+
+def create_request(payload: dict[str, Any], extra: bytes = b"") -> bytes:
+ body = json.dumps(payload).encode()
+ head = (
+ b"POST /v1.45/containers/create HTTP/1.1\r\nHost: x\r\n"
+ + extra
+ + b"Content-Type: application/json\r\nContent-Length: %d\r\n\r\n" % len(body)
+ )
+ return head + body
+
+
+def test_ping_passes_through(tmp_path: Path) -> None:
+ async def scenario() -> None:
+ _, relay = stack(tmp_path)
+ status, _, body = await call(relay, b"GET /_ping HTTP/1.1\r\nHost: x\r\n\r\n")
+ assert (status, body) == (200, b"OK")
+
+ run(scenario())
+
+
+def test_serve_unix_binds_owner_only(tmp_path: Path) -> None:
+ async def scenario() -> None:
+ async def handler(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
+ writer.close()
+
+ sock = tmp_path / "gw.sock"
+ try:
+ server = await serve_unix(sock, handler)
+ except PermissionError:
+ pytest.skip("sandbox denies unix bind; runs in CI")
+ try:
+ assert sock.stat().st_mode & 0o777 == 0o600
+ finally:
+ server.close()
Review Comment:
## CodeQL / Potentially uninitialized local variable
Local variable 'server' may be used before it is initialized.
[Show more details](https://github.com/apache/magpie/security/code-scanning/79)
##########
tools/container-gateway/tests/test_daemon.py:
##########
@@ -0,0 +1,1013 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Daemon plumbing: paths, guards, idle exit, status and stop.
+
+Threat model exercised throughout this file: the daemon runs OUTSIDE the
+sandbox with the operator's own privileges, while the sandboxed agent
+can create, delete and symlink anything under the project tree,
+including ``.apache-magpie-local/run/``. Every guard test below plants
+exactly the kind of hostile filesystem state that threat model implies
+and checks the guard refuses it -- no bind needed for any of them.
+
+No ``pytest-asyncio`` in the ``magpie-dev`` dependency group, so each
+async scenario is a plain ``def`` test driving its coroutine through the
+``run()`` helper, exactly as ``test_http.py`` and ``test_relay.py`` do.
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import json
+import os
+import shutil
+import signal
+import subprocess
+import sys
+import tempfile
+from collections.abc import Coroutine, Iterator
+from pathlib import Path
+from typing import Any, TypeVar
+
+import pytest
+
+from container_gateway import __main__ as cli
+from container_gateway import daemon
+from container_gateway.backends import Backend
+
+from .fakebackend import FakeBackend
+
+SRC = Path(__file__).resolve().parents[1] / "src"
+
+_T = TypeVar("_T")
+
+
+def run(coro: Coroutine[Any, Any, _T]) -> _T:
+ """Drive a coroutine to completion without pytest-asyncio."""
+ return asyncio.run(coro)
+
+
+def _ns(project: Path, run_dir: Path, **extra: Any) -> argparse.Namespace:
+ """A minimal argparse.Namespace for calling cmd_serve/cmd_stop/cmd_status directly."""
+ base = {"project": project, "run_dir": run_dir, "pid_file": None}
+ base.update(extra)
+ return argparse.Namespace(**base)
+
+
+@pytest.fixture
+def short_run_dir() -> Iterator[Path]:
+ """A run directory short enough to hold a unix-socket path.
+
+ ``pytest``'s own ``tmp_path`` fixture nests under
+ ``pytest-of-<user>/pytest-<n>/<test-name>/`` inside ``$TMPDIR``, which
+ in this sandboxed dev environment is already long enough on its own
+ to blow the ~103-byte ``sun_path`` limit before ``run_dir`` even adds
+ ``podman.sock``. ``tempfile.mkdtemp()`` sits directly under
+ ``$TMPDIR`` with none of that nesting, so it stays short everywhere
+ ``tmp_path`` might not. It is also already 0700 and owned by us, so
+ it satisfies ``check_run_dir``'s "custom run-dir" branch as-is.
+ """
+ d = Path(tempfile.mkdtemp(prefix="cg-"))
+ try:
+ yield d
+ finally:
+ shutil.rmtree(d, ignore_errors=True)
+
+
+class _RealSocketBackend:
+ """A ``FakeBackend`` served over a real filesystem unix socket.
+
+ ``tests/fakebackend.FakeBackend`` only ever hands out in-process
+ ``socket.socketpair()`` connections (the sandbox refuses ``bind()``,
+ so it never listens on a path) -- but ``daemon.run()`` needs a real
+ socket path to hand to ``unix_connector`` for a ``Backend``. This
+ thin wrapper does the one real bind these daemon tests need, so it
+ can hit the same ``PermissionError`` the sandbox raises and skip
+ exactly like every other bind-touching test in this suite.
+ """
+
+ def __init__(self, socket_path: Path) -> None:
+ self.socket = socket_path
+ self._fake = FakeBackend()
+ self._server: asyncio.AbstractServer | None = None
+
+ async def start(self) -> None:
+ self._server = await asyncio.start_unix_server(self._fake._handle, path=str(self.socket))
+
+ async def stop(self) -> None:
+ if self._server is not None:
+ self._server.close()
+ await self._server.wait_closed()
+
+
+# --------------------------------------------------------------- paths
+
+
+def test_paths_and_socket_length(tmp_path: Path) -> None:
+ p = daemon.paths(tmp_path)
+ assert p["podman"].name == "podman.sock" and p["docker"].name == "docker.sock"
+ # A literal short path, not tmp_path: with TMPDIR unset, tmp_path's
+ # pytest-of-<user>/pytest-<n>/<test-name>/ nesting is already long
+ # enough to exceed the ~103-byte sun_path limit on its own, and
+ # check_socket_path only measures byte length.
+ daemon.check_socket_path(Path("/tmp/ok.sock"))
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_socket_path(Path("/" + "x" * 120 + "/podman.sock"))
+ assert exc.value.code == 2
+
+
+# ------------------------------------------------ C2: run dir / symlinks
+
+
+def test_check_run_dir_default_layout_creates_both_dirs_0700(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ run_dir = project_root / ".apache-magpie-local" / "run"
+ daemon.check_run_dir(run_dir, project_root)
+ assert (project_root / ".apache-magpie-local").stat().st_mode & 0o777 == 0o700
+ assert run_dir.stat().st_mode & 0o777 == 0o700
+
+
+def test_check_run_dir_refuses_world_writable_existing_dir(tmp_path: Path) -> None:
+ project_root = tmp_path
+ run_dir = tmp_path / "custom-run"
+ daemon.check_run_dir(run_dir, project_root)
+ assert run_dir.stat().st_mode & 0o777 == 0o700
+ run_dir.chmod(0o777)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(run_dir, project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_run(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ magpie_local = project_root / ".apache-magpie-local"
+ magpie_local.mkdir(parents=True, mode=0o700)
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (magpie_local / "run").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(magpie_local / "run", project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_apache_magpie_local(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (project_root / ".apache-magpie-local").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(project_root / ".apache-magpie-local" / "run", project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_custom_run_dir(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ custom = tmp_path / "custom-run"
+ custom.symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(custom, project_root)
+ assert exc.value.code == 2
+
+
+# ------------------------------------------- D5: missing ancestors refuse
+
+
+def test_check_run_dir_refuses_missing_project_root(tmp_path: Path) -> None:
+ missing_root = tmp_path / "does-not-exist"
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(missing_root / ".apache-magpie-local" / "run", missing_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_missing_custom_run_dir_parent(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ missing_parent_run_dir = tmp_path / "does-not-exist" / "run"
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(missing_parent_run_dir, project_root)
+ assert exc.value.code == 2
+
+
+def test_validate_run_dir_false_when_project_root_missing(tmp_path: Path) -> None:
+ missing_root = tmp_path / "does-not-exist"
+ assert daemon.validate_run_dir(missing_root / ".apache-magpie-local" / "run", missing_root) is False
+
+
+def test_validate_run_dir_false_when_custom_parent_missing(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ missing_parent_run_dir = tmp_path / "does-not-exist" / "run"
+ assert daemon.validate_run_dir(missing_parent_run_dir, project_root) is False
+
+
+# --------------------------------------- D6: lstat-then-mkdir race safety
+
+
+def test_ensure_owned_private_dir_handles_mkdir_race_with_planted_symlink(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ target = tmp_path / "custom-run"
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ real_mkdir = Path.mkdir
+
+ def racy_mkdir(self: Path, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None:
+ if self == target:
+ target.symlink_to(evil) # someone (or something) won the race and planted a symlink
+ raise FileExistsError(f"[Errno 17] File exists: '{target}'")
+ real_mkdir(self, mode, parents=parents, exist_ok=exist_ok)
+
+ monkeypatch.setattr(Path, "mkdir", racy_mkdir)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(target, tmp_path)
+ assert exc.value.code == 2
+
+
+# --------------------------------------------------- C2: socket guards
+
+
+def test_check_socket_type_refuses_non_socket(tmp_path: Path) -> None:
+ p = tmp_path / "podman.sock"
+ p.write_text("not a socket")
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_socket_type(p)
+ assert exc.value.code == 2
+
+
+def test_check_socket_type_allows_missing_path(tmp_path: Path) -> None:
+ daemon.check_socket_type(tmp_path / "missing.sock") # nothing there yet: fine
+
+
+# ------------------------------------------------------ C2: pid / log fd
+
+
+def test_acquire_pid_lock_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.pid"
+ target.write_text("")
+ link = tmp_path / "container-gateway.pid"
+ link.symlink_to(target)
+ with pytest.raises(SystemExit) as exc:
+ daemon.acquire_pid_lock(link)
+ assert exc.value.code == 2
+
+
+def test_probe_pid_lock_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.pid"
+ target.write_text("")
+ link = tmp_path / "container-gateway.pid"
+ link.symlink_to(target)
+ with pytest.raises(SystemExit) as exc:
+ daemon.probe_pid_lock(link)
+ assert exc.value.code == 2
+
+
+def test_probe_pid_lock_not_running_when_run_dir_absent(tmp_path: Path) -> None:
+ never_created = tmp_path / "never" / "container-gateway.pid"
+ assert daemon.probe_pid_lock(never_created) == (False, None)
+
+
+def test_open_log_fd_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.log"
+ target.write_text("")
+ link = tmp_path / "container-gateway.log"
+ link.symlink_to(target)
+ with pytest.raises(SystemExit) as exc:
+ cli._open_log_fd(link)
Review Comment:
## CodeQL / File is not always closed
File is opened but is not closed.
[Show more details](https://github.com/apache/magpie/security/code-scanning/71)
##########
tools/container-gateway/src/container_gateway/http.py:
##########
@@ -0,0 +1,386 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Just enough HTTP/1.1 to relay the Docker API over unix streams.
+
+Principle enforced throughout this module: anything the gateway cannot frame
+identically to the daemon is refused with :class:`HttpError`, never forwarded
+as best-effort. That covers request-smuggling shapes (bare CR/LF/NUL inside a
+header, a request line the policy layer would parse differently than the
+daemon, duplicate or ambiguous Content-Length/Transfer-Encoding) as well as
+plain transport failures (``ValueError`` from ``int()``,
+``asyncio.IncompleteReadError``, ``asyncio.LimitOverrunError``) -- every one
+of those is caught at the boundary and re-raised as ``HttpError`` so the relay
+has exactly one exception type to catch and answer with ``error_response``.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import re
+from dataclasses import dataclass, field
+from urllib.parse import parse_qs, urlsplit
+
+_REASONS = {
+ 200: "OK",
+ 400: "Bad Request",
+ 403: "Forbidden",
+ 404: "Not Found",
+ 500: "Internal Server Error",
+ 502: "Bad Gateway",
+}
+
+# Control characters (excluding the CR/LF that terminate a line, which are
+# handled structurally by the line-splitting itself) that must never appear
+# inside a header name, header value, or start line. Includes CR/LF/NUL so
+# that a value smuggled *inside* a single already-split line -- a bare LF or
+# CR not paired as "\r\n", or an embedded NUL -- is caught explicitly, not
+# just control characters in general.
+_CTL = frozenset(chr(c) for c in (*range(0x00, 0x20), 0x7F))
+
+_METHOD_RE = re.compile(r"[A-Z]+")
+_VERSION_RE = re.compile(r"HTTP/1\.[01]")
+_STATUS_RE = re.compile(r"[1-5][0-9]{2}")
+_CONTENT_LENGTH_RE = re.compile(r"[0-9]{1,18}")
+_CHUNK_SIZE_RE = re.compile(rb"[0-9A-Fa-f]{1,8}")
+
+
+class HttpError(Exception):
+ pass
+
+
+def _check_no_control_chars(s: str, what: str) -> None:
+ if any(c in _CTL for c in s):
+ raise HttpError(f"control character in {what}: {s!r}")
+
+
+def _check_header_name(name: str) -> None:
+ if not name:
+ raise HttpError("empty header name")
+ _check_no_control_chars(name, "header name")
+ if any(c.isspace() for c in name):
+ raise HttpError(f"whitespace in header name: {name!r}")
+
+
+def _check_header_value(value: str) -> None:
+ _check_no_control_chars(value, "header value")
+ try:
+ value.encode("latin-1")
+ except UnicodeEncodeError as exc:
+ raise HttpError(f"non-latin-1 header value: {value!r}") from exc
+
+
+def _validate_head_start_line(line: str) -> None:
+ """Validate a request- or status-line the way the daemon would parse it.
+
+ ``read_head`` parses both requests (sent to the daemon) and responses
+ (received back from it), so this accepts either shape. The shape is
+ detected from the *first* token: if it looks like an HTTP version, this
+ is a status line (``HTTP/1.x SP status [SP reason]``), whose reason
+ phrase is free-form -- it may be empty or contain further spaces
+ (``404 Not Found``, `` 500 Internal Server Error``) -- so it is split
+ with ``maxsplit=2`` rather than demanding exactly three tokens. Anything
+ else is a request line (``METHOD SP target SP HTTP/1.x``), which keeps
+ the strict exactly-three-tokens rule: a request target legitimately
+ never contains an unencoded space, so a fourth token there is always a
+ smuggling shape, not a value the gateway should tolerate. Control
+ characters are rejected in either shape, over the whole line up front,
+ so a tab or bogus extra space cannot silently shift which token is
+ which.
+ """
+ _check_no_control_chars(line, "start line")
+ head_token = line.split(" ", 1)[0]
+ if _VERSION_RE.fullmatch(head_token):
+ parts = line.split(" ", 2)
+ if len(parts) < 2 or not _STATUS_RE.fullmatch(parts[1]):
+ raise HttpError(f"bad status line: {line!r}")
+ return
+ parts = line.split(" ")
+ if len(parts) != 3 or not _METHOD_RE.fullmatch(parts[0]) or not _VERSION_RE.fullmatch(parts[2]):
+ raise HttpError(f"bad start line: {line!r}")
+
+
+@dataclass
+class Head:
+ start_line: str
+ headers: list[tuple[str, str]] = field(default_factory=list)
+
+ def get(self, name: str) -> str | None:
+ name = name.lower()
+ for k, v in self.headers:
+ if k.lower() == name:
+ return v
+ return None
+
+ def set(self, name: str, value: str) -> None:
+ _check_header_name(name)
+ _check_header_value(value)
+ self.remove(name)
+ self.headers.append((name, value))
+
+ def remove(self, name: str) -> None:
+ name = name.lower()
+ self.headers = [(k, v) for k, v in self.headers if k.lower() != name]
+
+ @property
+ def content_length(self) -> int | None:
+ v = self.get("content-length")
+ if v is None or not _CONTENT_LENGTH_RE.fullmatch(v):
+ return None
+ return int(v)
+
+ @property
+ def chunked(self) -> bool:
+ v = self.get("transfer-encoding")
+ return v is not None and v.casefold() == "chunked"
+
+ @property
+ def upgrade(self) -> bool:
+ return self.get("upgrade") is not None or "upgrade" in (self.get("connection") or "").lower()
+
+ def validate_framing(self) -> None:
+ """Reject the request-smuggling shapes RFC 7230 §3.3.3 permits refusing.
+
+ Called by ``read_head`` before it hands a ``Head`` back to a caller, so
+ every parsed head -- request or response -- has already been checked
+ by the time policy code sees it. Synthesised heads (``error_response``)
+ are not run through this automatically; nothing this module builds
+ itself needs it.
+ """
+ cls = [v for k, v in self.headers if k.lower() == "content-length"]
+ tes = [v for k, v in self.headers if k.lower() == "transfer-encoding"]
+ if len(cls) > 1:
+ raise HttpError("duplicate Content-Length")
+ if len(tes) > 1:
+ raise HttpError("duplicate Transfer-Encoding")
+ if cls and not _CONTENT_LENGTH_RE.fullmatch(cls[0]):
+ raise HttpError(f"bad Content-Length: {cls[0]!r}")
+ if tes and tes[0].casefold() != "chunked":
+ raise HttpError(f"bad Transfer-Encoding: {tes[0]!r}")
+ if cls and tes:
+ raise HttpError("Content-Length and Transfer-Encoding both present")
+
+ def encode(self) -> bytes:
+ # Defence in depth: re-check the start line and headers even though
+ # `set()` and `read_head` already validate on the way in, so a `Head`
+ # built by setting `.start_line`/appending to `.headers` directly
+ # (bypassing both) still cannot smuggle a control character or a
+ # non-latin-1 value out onto the wire.
+ _check_no_control_chars(self.start_line, "start line")
+ for k, v in self.headers:
+ _check_header_name(k)
+ _check_header_value(v)
+ lines = [self.start_line, *[f"{k}: {v}" for k, v in self.headers], "", ""]
+ try:
+ return "\r\n".join(lines).encode("latin-1")
+ except UnicodeEncodeError as exc:
+ raise HttpError(f"non-latin-1 start line: {self.start_line!r}") from exc
+
+
+async def read_head(reader: asyncio.StreamReader, limit: int = 65536) -> Head | None:
+ """Read and validate one HTTP head (request or response).
+
+ ``limit`` is enforced against the fully-buffered head (``len(raw) >
+ limit``) independently of the ``asyncio.StreamReader``'s own internal
+ buffer limit (set at construction, default 64 KiB): a `limit` larger
+ than the reader's own cannot be honoured -- ``readuntil`` will raise
+ ``asyncio.LimitOverrunError`` (wrapped below as ``HttpError``) before
+ this function's own check ever runs. Callers that want *this* function's
+ limit to be the one that fires must construct the reader with a
+ correspondingly larger internal limit.
+ """
+ try:
+ raw = await reader.readuntil(b"\r\n\r\n")
+ except asyncio.IncompleteReadError as exc:
+ if not exc.partial.strip():
+ return None
+ raise HttpError("truncated head") from exc
+ except asyncio.LimitOverrunError as exc:
+ raise HttpError("head too large") from exc
+ if len(raw) > limit:
+ raise HttpError("head too large")
+ text = raw.decode("latin-1")
+ first, _, rest = text.partition("\r\n")
+ _validate_head_start_line(first)
+ headers: list[tuple[str, str]] = []
+ for line in rest.split("\r\n"):
+ if not line:
+ continue
+ if line[0] in " \t":
+ raise HttpError(f"obsolete line folding: {line!r}")
+ k, sep, v = line.partition(":")
+ if not sep:
+ raise HttpError(f"bad header line: {line!r}")
+ name, value = k.strip(), v.strip()
+ _check_header_name(name)
+ _check_header_value(value)
+ headers.append((name, value))
+ head = Head(first, headers)
+ head.validate_framing()
+ return head
+
+
+def parse_request_line(line: str) -> tuple[str, str, dict[str, list[str]]]:
+ _check_no_control_chars(line, "request line")
+ parts = line.split(" ")
+ if len(parts) != 3 or not _METHOD_RE.fullmatch(parts[0]) or not _VERSION_RE.fullmatch(parts[2]):
+ raise HttpError(f"bad request line: {line!r}")
+ target = parts[1]
+ if not target or "\\" in target:
+ raise HttpError(f"bad request target: {line!r}")
+ url = urlsplit(target)
+ return parts[0], url.path or "/", parse_qs(url.query, keep_blank_values=True)
+
+
+async def _read_chunked(reader: asyncio.StreamReader, sink: asyncio.StreamWriter | None, limit: int) -> bytes:
+ out = bytearray()
+ while True:
+ try:
+ size_line = await reader.readuntil(b"\r\n")
+ except asyncio.IncompleteReadError as exc:
+ raise HttpError("truncated chunk size") from exc
+ except asyncio.LimitOverrunError as exc:
+ raise HttpError("chunk size line too large") from exc
+ size_token = size_line.split(b";", 1)[0].split(b"\r", 1)[0]
+ if not _CHUNK_SIZE_RE.fullmatch(size_token):
+ raise HttpError(f"bad chunk size: {size_token!r}")
+ size = int(size_token, 16)
+ if sink is None and len(out) + size > limit:
+ raise HttpError("body too large")
+ chunk = b""
+ if size:
+ try:
+ chunk = await reader.readexactly(size + 2)
+ except asyncio.IncompleteReadError as exc:
+ raise HttpError("truncated chunk data") from exc
+ if chunk[-2:] != b"\r\n":
+ raise HttpError("bad chunk terminator")
+ if sink is not None:
+ sink.write(size_line + chunk)
+ await sink.drain()
+ else:
+ out += chunk[:-2] if chunk else b""
+ if size == 0:
+ # trailers, if any, end with an empty line
+ while True:
+ try:
+ line = await reader.readuntil(b"\r\n")
+ except (asyncio.IncompleteReadError, asyncio.LimitOverrunError) as exc:
+ raise HttpError("bad chunk trailer") from exc
+ if sink is not None:
+ sink.write(line)
+ if line == b"\r\n":
+ break
+ if sink is not None:
+ await sink.drain()
+ return bytes(out)
+
+
+async def read_body(reader: asyncio.StreamReader, head: Head, limit: int) -> bytes:
+ if head.chunked:
+ return await _read_chunked(reader, None, limit)
+ n = head.content_length or 0
+ if n > limit:
+ raise HttpError("body too large")
+ if not n:
+ return b""
+ try:
+ return await reader.readexactly(n)
+ except asyncio.IncompleteReadError as exc:
+ raise HttpError("body truncated") from exc
+
+
+async def pump(reader: asyncio.StreamReader, writer: asyncio.StreamWriter, head: Head) -> None:
+ """Stream a body from ``reader`` to ``writer`` exactly as framed by ``head``."""
+ if head.chunked:
+ await _read_chunked(reader, writer, 0)
+ return
+ n = head.content_length
+ if n is None:
+ while chunk := await reader.read(65536):
+ writer.write(chunk)
+ await writer.drain()
+ return
+ while n > 0:
+ chunk = await reader.read(min(65536, n))
+ if not chunk:
+ raise HttpError("body truncated")
+ n -= len(chunk)
+ writer.write(chunk)
+ await writer.drain()
+
+
+def _try_write_eof(writer: asyncio.StreamWriter) -> None:
+ try:
+ if writer.can_write_eof():
+ writer.write_eof()
+ except (OSError, RuntimeError, NotImplementedError):
Review Comment:
## CodeQL / Empty except
'except' clause does nothing but pass and there is no explanatory comment.
[Show more details](https://github.com/apache/magpie/security/code-scanning/76)
##########
tools/container-gateway/tests/test_daemon.py:
##########
@@ -0,0 +1,1013 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Daemon plumbing: paths, guards, idle exit, status and stop.
+
+Threat model exercised throughout this file: the daemon runs OUTSIDE the
+sandbox with the operator's own privileges, while the sandboxed agent
+can create, delete and symlink anything under the project tree,
+including ``.apache-magpie-local/run/``. Every guard test below plants
+exactly the kind of hostile filesystem state that threat model implies
+and checks the guard refuses it -- no bind needed for any of them.
+
+No ``pytest-asyncio`` in the ``magpie-dev`` dependency group, so each
+async scenario is a plain ``def`` test driving its coroutine through the
+``run()`` helper, exactly as ``test_http.py`` and ``test_relay.py`` do.
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import json
+import os
+import shutil
+import signal
+import subprocess
+import sys
+import tempfile
+from collections.abc import Coroutine, Iterator
+from pathlib import Path
+from typing import Any, TypeVar
+
+import pytest
+
+from container_gateway import __main__ as cli
+from container_gateway import daemon
+from container_gateway.backends import Backend
+
+from .fakebackend import FakeBackend
+
+SRC = Path(__file__).resolve().parents[1] / "src"
+
+_T = TypeVar("_T")
+
+
+def run(coro: Coroutine[Any, Any, _T]) -> _T:
+ """Drive a coroutine to completion without pytest-asyncio."""
+ return asyncio.run(coro)
+
+
+def _ns(project: Path, run_dir: Path, **extra: Any) -> argparse.Namespace:
+ """A minimal argparse.Namespace for calling cmd_serve/cmd_stop/cmd_status directly."""
+ base = {"project": project, "run_dir": run_dir, "pid_file": None}
+ base.update(extra)
+ return argparse.Namespace(**base)
+
+
+@pytest.fixture
+def short_run_dir() -> Iterator[Path]:
+ """A run directory short enough to hold a unix-socket path.
+
+ ``pytest``'s own ``tmp_path`` fixture nests under
+ ``pytest-of-<user>/pytest-<n>/<test-name>/`` inside ``$TMPDIR``, which
+ in this sandboxed dev environment is already long enough on its own
+ to blow the ~103-byte ``sun_path`` limit before ``run_dir`` even adds
+ ``podman.sock``. ``tempfile.mkdtemp()`` sits directly under
+ ``$TMPDIR`` with none of that nesting, so it stays short everywhere
+ ``tmp_path`` might not. It is also already 0700 and owned by us, so
+ it satisfies ``check_run_dir``'s "custom run-dir" branch as-is.
+ """
+ d = Path(tempfile.mkdtemp(prefix="cg-"))
+ try:
+ yield d
+ finally:
+ shutil.rmtree(d, ignore_errors=True)
+
+
+class _RealSocketBackend:
+ """A ``FakeBackend`` served over a real filesystem unix socket.
+
+ ``tests/fakebackend.FakeBackend`` only ever hands out in-process
+ ``socket.socketpair()`` connections (the sandbox refuses ``bind()``,
+ so it never listens on a path) -- but ``daemon.run()`` needs a real
+ socket path to hand to ``unix_connector`` for a ``Backend``. This
+ thin wrapper does the one real bind these daemon tests need, so it
+ can hit the same ``PermissionError`` the sandbox raises and skip
+ exactly like every other bind-touching test in this suite.
+ """
+
+ def __init__(self, socket_path: Path) -> None:
+ self.socket = socket_path
+ self._fake = FakeBackend()
+ self._server: asyncio.AbstractServer | None = None
+
+ async def start(self) -> None:
+ self._server = await asyncio.start_unix_server(self._fake._handle, path=str(self.socket))
+
+ async def stop(self) -> None:
+ if self._server is not None:
+ self._server.close()
+ await self._server.wait_closed()
+
+
+# --------------------------------------------------------------- paths
+
+
+def test_paths_and_socket_length(tmp_path: Path) -> None:
+ p = daemon.paths(tmp_path)
+ assert p["podman"].name == "podman.sock" and p["docker"].name == "docker.sock"
+ # A literal short path, not tmp_path: with TMPDIR unset, tmp_path's
+ # pytest-of-<user>/pytest-<n>/<test-name>/ nesting is already long
+ # enough to exceed the ~103-byte sun_path limit on its own, and
+ # check_socket_path only measures byte length.
+ daemon.check_socket_path(Path("/tmp/ok.sock"))
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_socket_path(Path("/" + "x" * 120 + "/podman.sock"))
+ assert exc.value.code == 2
+
+
+# ------------------------------------------------ C2: run dir / symlinks
+
+
+def test_check_run_dir_default_layout_creates_both_dirs_0700(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ run_dir = project_root / ".apache-magpie-local" / "run"
+ daemon.check_run_dir(run_dir, project_root)
+ assert (project_root / ".apache-magpie-local").stat().st_mode & 0o777 == 0o700
+ assert run_dir.stat().st_mode & 0o777 == 0o700
+
+
+def test_check_run_dir_refuses_world_writable_existing_dir(tmp_path: Path) -> None:
+ project_root = tmp_path
+ run_dir = tmp_path / "custom-run"
+ daemon.check_run_dir(run_dir, project_root)
+ assert run_dir.stat().st_mode & 0o777 == 0o700
+ run_dir.chmod(0o777)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(run_dir, project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_run(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ magpie_local = project_root / ".apache-magpie-local"
+ magpie_local.mkdir(parents=True, mode=0o700)
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (magpie_local / "run").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(magpie_local / "run", project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_apache_magpie_local(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (project_root / ".apache-magpie-local").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(project_root / ".apache-magpie-local" / "run", project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_custom_run_dir(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ custom = tmp_path / "custom-run"
+ custom.symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(custom, project_root)
+ assert exc.value.code == 2
+
+
+# ------------------------------------------- D5: missing ancestors refuse
+
+
+def test_check_run_dir_refuses_missing_project_root(tmp_path: Path) -> None:
+ missing_root = tmp_path / "does-not-exist"
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(missing_root / ".apache-magpie-local" / "run", missing_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_missing_custom_run_dir_parent(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ missing_parent_run_dir = tmp_path / "does-not-exist" / "run"
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(missing_parent_run_dir, project_root)
+ assert exc.value.code == 2
+
+
+def test_validate_run_dir_false_when_project_root_missing(tmp_path: Path) -> None:
+ missing_root = tmp_path / "does-not-exist"
+ assert daemon.validate_run_dir(missing_root / ".apache-magpie-local" / "run", missing_root) is False
+
+
+def test_validate_run_dir_false_when_custom_parent_missing(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ missing_parent_run_dir = tmp_path / "does-not-exist" / "run"
+ assert daemon.validate_run_dir(missing_parent_run_dir, project_root) is False
+
+
+# --------------------------------------- D6: lstat-then-mkdir race safety
+
+
+def test_ensure_owned_private_dir_handles_mkdir_race_with_planted_symlink(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ target = tmp_path / "custom-run"
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ real_mkdir = Path.mkdir
+
+ def racy_mkdir(self: Path, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None:
+ if self == target:
+ target.symlink_to(evil) # someone (or something) won the race and planted a symlink
+ raise FileExistsError(f"[Errno 17] File exists: '{target}'")
+ real_mkdir(self, mode, parents=parents, exist_ok=exist_ok)
+
+ monkeypatch.setattr(Path, "mkdir", racy_mkdir)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(target, tmp_path)
+ assert exc.value.code == 2
+
+
+# --------------------------------------------------- C2: socket guards
+
+
+def test_check_socket_type_refuses_non_socket(tmp_path: Path) -> None:
+ p = tmp_path / "podman.sock"
+ p.write_text("not a socket")
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_socket_type(p)
+ assert exc.value.code == 2
+
+
+def test_check_socket_type_allows_missing_path(tmp_path: Path) -> None:
+ daemon.check_socket_type(tmp_path / "missing.sock") # nothing there yet: fine
+
+
+# ------------------------------------------------------ C2: pid / log fd
+
+
+def test_acquire_pid_lock_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.pid"
+ target.write_text("")
+ link = tmp_path / "container-gateway.pid"
+ link.symlink_to(target)
+ with pytest.raises(SystemExit) as exc:
+ daemon.acquire_pid_lock(link)
Review Comment:
## CodeQL / File is not always closed
File is opened but is not closed.
[Show more details](https://github.com/apache/magpie/security/code-scanning/70)
##########
tools/container-gateway/tests/test_daemon.py:
##########
@@ -0,0 +1,1013 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Daemon plumbing: paths, guards, idle exit, status and stop.
+
+Threat model exercised throughout this file: the daemon runs OUTSIDE the
+sandbox with the operator's own privileges, while the sandboxed agent
+can create, delete and symlink anything under the project tree,
+including ``.apache-magpie-local/run/``. Every guard test below plants
+exactly the kind of hostile filesystem state that threat model implies
+and checks the guard refuses it -- no bind needed for any of them.
+
+No ``pytest-asyncio`` in the ``magpie-dev`` dependency group, so each
+async scenario is a plain ``def`` test driving its coroutine through the
+``run()`` helper, exactly as ``test_http.py`` and ``test_relay.py`` do.
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import json
+import os
+import shutil
+import signal
+import subprocess
+import sys
+import tempfile
+from collections.abc import Coroutine, Iterator
+from pathlib import Path
+from typing import Any, TypeVar
+
+import pytest
+
+from container_gateway import __main__ as cli
+from container_gateway import daemon
+from container_gateway.backends import Backend
+
+from .fakebackend import FakeBackend
+
+SRC = Path(__file__).resolve().parents[1] / "src"
+
+_T = TypeVar("_T")
+
+
+def run(coro: Coroutine[Any, Any, _T]) -> _T:
+ """Drive a coroutine to completion without pytest-asyncio."""
+ return asyncio.run(coro)
+
+
+def _ns(project: Path, run_dir: Path, **extra: Any) -> argparse.Namespace:
+ """A minimal argparse.Namespace for calling cmd_serve/cmd_stop/cmd_status directly."""
+ base = {"project": project, "run_dir": run_dir, "pid_file": None}
+ base.update(extra)
+ return argparse.Namespace(**base)
+
+
+@pytest.fixture
+def short_run_dir() -> Iterator[Path]:
+ """A run directory short enough to hold a unix-socket path.
+
+ ``pytest``'s own ``tmp_path`` fixture nests under
+ ``pytest-of-<user>/pytest-<n>/<test-name>/`` inside ``$TMPDIR``, which
+ in this sandboxed dev environment is already long enough on its own
+ to blow the ~103-byte ``sun_path`` limit before ``run_dir`` even adds
+ ``podman.sock``. ``tempfile.mkdtemp()`` sits directly under
+ ``$TMPDIR`` with none of that nesting, so it stays short everywhere
+ ``tmp_path`` might not. It is also already 0700 and owned by us, so
+ it satisfies ``check_run_dir``'s "custom run-dir" branch as-is.
+ """
+ d = Path(tempfile.mkdtemp(prefix="cg-"))
+ try:
+ yield d
+ finally:
+ shutil.rmtree(d, ignore_errors=True)
+
+
+class _RealSocketBackend:
+ """A ``FakeBackend`` served over a real filesystem unix socket.
+
+ ``tests/fakebackend.FakeBackend`` only ever hands out in-process
+ ``socket.socketpair()`` connections (the sandbox refuses ``bind()``,
+ so it never listens on a path) -- but ``daemon.run()`` needs a real
+ socket path to hand to ``unix_connector`` for a ``Backend``. This
+ thin wrapper does the one real bind these daemon tests need, so it
+ can hit the same ``PermissionError`` the sandbox raises and skip
+ exactly like every other bind-touching test in this suite.
+ """
+
+ def __init__(self, socket_path: Path) -> None:
+ self.socket = socket_path
+ self._fake = FakeBackend()
+ self._server: asyncio.AbstractServer | None = None
+
+ async def start(self) -> None:
+ self._server = await asyncio.start_unix_server(self._fake._handle, path=str(self.socket))
+
+ async def stop(self) -> None:
+ if self._server is not None:
+ self._server.close()
+ await self._server.wait_closed()
+
+
+# --------------------------------------------------------------- paths
+
+
+def test_paths_and_socket_length(tmp_path: Path) -> None:
+ p = daemon.paths(tmp_path)
+ assert p["podman"].name == "podman.sock" and p["docker"].name == "docker.sock"
+ # A literal short path, not tmp_path: with TMPDIR unset, tmp_path's
+ # pytest-of-<user>/pytest-<n>/<test-name>/ nesting is already long
+ # enough to exceed the ~103-byte sun_path limit on its own, and
+ # check_socket_path only measures byte length.
+ daemon.check_socket_path(Path("/tmp/ok.sock"))
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_socket_path(Path("/" + "x" * 120 + "/podman.sock"))
+ assert exc.value.code == 2
+
+
+# ------------------------------------------------ C2: run dir / symlinks
+
+
+def test_check_run_dir_default_layout_creates_both_dirs_0700(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ run_dir = project_root / ".apache-magpie-local" / "run"
+ daemon.check_run_dir(run_dir, project_root)
+ assert (project_root / ".apache-magpie-local").stat().st_mode & 0o777 == 0o700
+ assert run_dir.stat().st_mode & 0o777 == 0o700
+
+
+def test_check_run_dir_refuses_world_writable_existing_dir(tmp_path: Path) -> None:
+ project_root = tmp_path
+ run_dir = tmp_path / "custom-run"
+ daemon.check_run_dir(run_dir, project_root)
+ assert run_dir.stat().st_mode & 0o777 == 0o700
+ run_dir.chmod(0o777)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(run_dir, project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_run(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ magpie_local = project_root / ".apache-magpie-local"
+ magpie_local.mkdir(parents=True, mode=0o700)
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (magpie_local / "run").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(magpie_local / "run", project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_apache_magpie_local(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (project_root / ".apache-magpie-local").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(project_root / ".apache-magpie-local" / "run", project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_custom_run_dir(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ custom = tmp_path / "custom-run"
+ custom.symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(custom, project_root)
+ assert exc.value.code == 2
+
+
+# ------------------------------------------- D5: missing ancestors refuse
+
+
+def test_check_run_dir_refuses_missing_project_root(tmp_path: Path) -> None:
+ missing_root = tmp_path / "does-not-exist"
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(missing_root / ".apache-magpie-local" / "run", missing_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_missing_custom_run_dir_parent(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ missing_parent_run_dir = tmp_path / "does-not-exist" / "run"
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(missing_parent_run_dir, project_root)
+ assert exc.value.code == 2
+
+
+def test_validate_run_dir_false_when_project_root_missing(tmp_path: Path) -> None:
+ missing_root = tmp_path / "does-not-exist"
+ assert daemon.validate_run_dir(missing_root / ".apache-magpie-local" / "run", missing_root) is False
+
+
+def test_validate_run_dir_false_when_custom_parent_missing(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ missing_parent_run_dir = tmp_path / "does-not-exist" / "run"
+ assert daemon.validate_run_dir(missing_parent_run_dir, project_root) is False
+
+
+# --------------------------------------- D6: lstat-then-mkdir race safety
+
+
+def test_ensure_owned_private_dir_handles_mkdir_race_with_planted_symlink(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ target = tmp_path / "custom-run"
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ real_mkdir = Path.mkdir
+
+ def racy_mkdir(self: Path, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None:
+ if self == target:
+ target.symlink_to(evil) # someone (or something) won the race and planted a symlink
+ raise FileExistsError(f"[Errno 17] File exists: '{target}'")
+ real_mkdir(self, mode, parents=parents, exist_ok=exist_ok)
+
+ monkeypatch.setattr(Path, "mkdir", racy_mkdir)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(target, tmp_path)
+ assert exc.value.code == 2
+
+
+# --------------------------------------------------- C2: socket guards
+
+
+def test_check_socket_type_refuses_non_socket(tmp_path: Path) -> None:
+ p = tmp_path / "podman.sock"
+ p.write_text("not a socket")
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_socket_type(p)
+ assert exc.value.code == 2
+
+
+def test_check_socket_type_allows_missing_path(tmp_path: Path) -> None:
+ daemon.check_socket_type(tmp_path / "missing.sock") # nothing there yet: fine
+
+
+# ------------------------------------------------------ C2: pid / log fd
+
+
+def test_acquire_pid_lock_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.pid"
+ target.write_text("")
+ link = tmp_path / "container-gateway.pid"
+ link.symlink_to(target)
+ with pytest.raises(SystemExit) as exc:
+ daemon.acquire_pid_lock(link)
+ assert exc.value.code == 2
+
+
+def test_probe_pid_lock_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.pid"
+ target.write_text("")
+ link = tmp_path / "container-gateway.pid"
+ link.symlink_to(target)
+ with pytest.raises(SystemExit) as exc:
+ daemon.probe_pid_lock(link)
+ assert exc.value.code == 2
+
+
+def test_probe_pid_lock_not_running_when_run_dir_absent(tmp_path: Path) -> None:
+ never_created = tmp_path / "never" / "container-gateway.pid"
+ assert daemon.probe_pid_lock(never_created) == (False, None)
+
+
+def test_open_log_fd_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.log"
+ target.write_text("")
+ link = tmp_path / "container-gateway.log"
+ link.symlink_to(target)
+ with pytest.raises(SystemExit) as exc:
+ cli._open_log_fd(link)
+ assert exc.value.code == 2
+
+
+# --------------------- D2: acquire_pid_lock never blanks a live pid file
+
+
+def test_acquire_pid_lock_does_not_blank_a_live_daemons_pid_file(tmp_path: Path) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ os.ftruncate(fd, 0)
+ os.lseek(fd, 0, 0)
+ os.write(fd, b"4242\n")
+ os.fsync(fd)
+ second = daemon.acquire_pid_lock(pid_file)
+ assert second is None
+ assert pid_file.read_text() == "4242\n"
+ finally:
+ os.close(fd)
+
+
+# ------------------------------------- D1: status/stop bypassed check_run_dir
+
+
+def test_pid_file_is_trustworthy_none_when_missing(tmp_path: Path) -> None:
+ assert daemon.pid_file_is_trustworthy(tmp_path / "container-gateway.pid") is None
+
+
+def test_pid_file_is_trustworthy_true_for_a_lock_created_file(tmp_path: Path) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ assert daemon.pid_file_is_trustworthy(pid_file) is True
+ finally:
+ os.close(fd)
+
+
+def test_pid_file_is_trustworthy_false_for_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.pid"
+ target.write_text("4242\n")
+ target.chmod(0o600)
+ link = tmp_path / "container-gateway.pid"
+ link.symlink_to(target)
+ assert daemon.pid_file_is_trustworthy(link) is False
+
+
+def test_pid_file_is_trustworthy_false_for_wrong_mode(tmp_path: Path) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ pid_file.write_text("4242\n")
+ pid_file.chmod(0o644)
+ assert daemon.pid_file_is_trustworthy(pid_file) is False
+
+
+def test_cli_status_refuses_symlinked_run_dir(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ magpie_local = project_root / ".apache-magpie-local"
+ magpie_local.mkdir(parents=True, mode=0o700)
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (magpie_local / "run").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ cli.cmd_status(_ns(project_root, magpie_local / "run"))
+ assert exc.value.code == 2
+
+
+def test_cli_stop_refuses_symlinked_run_dir_without_signalling(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ project_root = tmp_path / "proj"
+ magpie_local = project_root / ".apache-magpie-local"
+ magpie_local.mkdir(parents=True, mode=0o700)
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (magpie_local / "run").symlink_to(evil)
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ with pytest.raises(SystemExit) as exc:
+ cli.cmd_stop(_ns(project_root, magpie_local / "run"))
+ assert exc.value.code == 2
+ assert calls == []
+
+
+def test_cli_stop_refuses_pid_file_with_wrong_mode(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ pid_file.write_text("4242\n")
+ pid_file.chmod(0o644)
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ with pytest.raises(SystemExit) as exc:
+ cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert exc.value.code == 2
+ assert calls == []
+
+
+def test_cli_status_treats_wrong_mode_pid_file_as_not_running(
+ tmp_path: Path, short_run_dir: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ pid_file.write_text("4242\n")
+ pid_file.chmod(0o644)
+ rc = cli.cmd_status(_ns(tmp_path, short_run_dir))
+ out = json.loads(capsys.readouterr().out)
+ assert rc == 3
+ assert out["running"] is False
+ # Untrustworthy content is left alone, not deleted, by `status`.
+ assert pid_file.exists()
+
+
+# -------------------------------- D4: stop verifies the signalled process
+
+
+def test_cli_stop_refuses_when_process_does_not_look_like_gateway(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ monkeypatch.setattr("container_gateway.backends.default_runner", lambda argv: "bash -c sleep 100")
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+def test_cli_stop_refuses_a_process_that_merely_mentions_the_module_name(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """An editor opened on a file named ``container_gateway.py`` is not the gateway.
+
+ A substring check on the ``ps`` line would wrongly treat this as a
+ match; the argv-shape check must not.
+ """
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ monkeypatch.setattr(
+ "container_gateway.backends.default_runner", lambda argv: "vim container_gateway.py"
+ )
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+def test_cli_stop_checks_only_the_first_line_of_ps_output(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A gateway-shaped second line must not rescue a non-gateway first line."""
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ monkeypatch.setattr(
+ "container_gateway.backends.default_runner",
+ lambda argv: "bash -c sleep 100\npython3 -m container_gateway serve --project /x",
+ )
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+def test_cli_stop_signals_when_process_is_the_console_script(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The installed ``container-gateway`` console script is also recognised, not just ``python -m``."""
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ our_pid = os.getpid()
+ calls: list[tuple[int, int]] = []
+ terminated = False
+
+ def fake_kill(pid: int, sig: int) -> None:
+ nonlocal terminated
+ calls.append((pid, sig))
+ if sig == signal.SIGTERM:
+ terminated = True
+ os.close(fd) # simulate the daemon exiting: release the flock
+ elif terminated:
+ raise ProcessLookupError
+
+ monkeypatch.setattr(os, "kill", fake_kill)
+ monkeypatch.setattr(
+ "container_gateway.backends.default_runner",
+ lambda argv: "/usr/local/bin/container-gateway serve --project /x",
+ )
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert rc == 0
+ assert (our_pid, signal.SIGTERM) in calls
+
+
+@pytest.mark.parametrize(
+ "command_line",
+ [
+ "python3 -u -m container_gateway serve --project /x",
+ "uv run python -m container_gateway serve --project /x",
+ ],
+)
+def test_cli_stop_signals_a_python_dash_m_invocation_with_extra_argv(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch, command_line: str
+) -> None:
+ """Interpreter flags (``-u``) and a runner prefix (``uv run``) do not defeat the argv-shape match."""
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ our_pid = os.getpid()
+ calls: list[tuple[int, int]] = []
+ terminated = False
+
+ def fake_kill(pid: int, sig: int) -> None:
+ nonlocal terminated
+ calls.append((pid, sig))
+ if sig == signal.SIGTERM:
+ terminated = True
+ os.close(fd) # simulate the daemon exiting: release the flock
+ elif terminated:
+ raise ProcessLookupError
+
+ monkeypatch.setattr(os, "kill", fake_kill)
+ monkeypatch.setattr("container_gateway.backends.default_runner", lambda argv: command_line)
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert rc == 0
+ assert (our_pid, signal.SIGTERM) in calls
+
+
+def test_cli_stop_refuses_when_ps_is_unavailable(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ monkeypatch.setattr("container_gateway.backends.default_runner", lambda argv: None)
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+# --------------------------------------------------------------- C1: pid
+
+
+@pytest.mark.parametrize("content", ["-1", "0", "1", "abc", "12 34", "99999999999", ""])
+def test_read_pid_rejects_unsafe_content(tmp_path: Path, content: str) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ pid_file.write_text(content)
+ assert daemon.read_pid(pid_file) is None
+
+
+def test_read_pid_accepts_a_real_pid(tmp_path: Path) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ pid_file.write_text("42\n")
+ assert daemon.read_pid(pid_file) == 42
+
+
+def test_pid_alive_false_for_pid_le_1() -> None:
+ assert daemon.pid_alive(0) is False
+ assert daemon.pid_alive(1) is False
+ assert daemon.pid_alive(-1) is False
+
+
+@pytest.mark.parametrize("content", ["-1", "0", "1", "abc", "12 34"])
+def test_cli_stop_with_unsafe_pid_file_does_not_signal(
+ tmp_path: Path, short_run_dir: Path, content: str, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ pid_file.write_text(content)
+ pid_file.chmod(0o600) # a trustworthy *file*; the *content* is what's unsafe here
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 0
+
+
+def test_cli_stop_does_not_signal_when_lock_held_but_pid_content_poisoned(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A live, lock-holding instance whose pid-file *content* was overwritten afterwards.
+
+ ``stop`` must refuse to guess: something is clearly running (the
+ lock says so), but nothing safe to signal can be read back out of
+ the file.
+ """
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ os.ftruncate(fd, 0)
+ os.lseek(fd, 0, 0)
+ os.write(fd, b"-1\n")
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+# --------------------------------------------- I3+I4: flock single instance
+
+
+def test_cli_serve_short_circuits_when_lock_already_held(tmp_path: Path, short_run_dir: Path) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ ns = _ns(
+ tmp_path,
+ short_run_dir,
+ daemon=False,
+ backend=None,
+ egress="off",
+ egress_port=8899,
+ egress_host=None,
+ extra_bind_root=None,
+ idle_timeout=5.0,
+ backend_timeout=60.0,
+ log_level="INFO",
+ )
+ assert cli.cmd_serve(ns) == 0
+ assert not (short_run_dir / "podman.sock").exists()
+ assert not (short_run_dir / "docker.sock").exists()
+ finally:
+ os.close(fd)
+
+
+def test_cli_status_reports_running_when_lock_held(
+ tmp_path: Path, short_run_dir: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ rc = cli.cmd_status(_ns(tmp_path, short_run_dir))
+ out = json.loads(capsys.readouterr().out)
+ finally:
+ os.close(fd)
+ assert rc == 0
+ assert out["running"] is True
+ assert out["pid"] == os.getpid()
+ assert out["serving"] == [] # no sockets actually bound in this test
+
+
+def test_cli_status_removes_stale_pid_file_when_no_lock_held(
+ tmp_path: Path, short_run_dir: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ pid_file.write_text("424242\n") # a stale pid; nobody holds its lock
+ pid_file.chmod(0o600) # a trustworthy, well-formed pid file -- just stale
+ rc = cli.cmd_status(_ns(tmp_path, short_run_dir))
+ out = json.loads(capsys.readouterr().out)
+ assert rc == 3
+ assert out["running"] is False
+ assert out["pid"] is None
+ assert not pid_file.exists()
+
+
+def test_cli_stop_signals_the_pid_and_reports_stopped(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ our_pid = os.getpid()
+ calls: list[tuple[int, int]] = []
+ terminated = False
+
+ def fake_kill(pid: int, sig: int) -> None:
+ nonlocal terminated
+ calls.append((pid, sig))
+ if sig == signal.SIGTERM:
+ terminated = True
+ os.close(fd) # simulate the daemon exiting: release the flock
+ elif terminated:
+ raise ProcessLookupError
+
+ monkeypatch.setattr(os, "kill", fake_kill)
+ monkeypatch.setattr(
+ "container_gateway.backends.default_runner",
+ lambda argv: "python3 -m container_gateway serve --project /x",
+ )
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert rc == 0
+ assert (our_pid, signal.SIGTERM) in calls
+
+
+def test_cli_stop_when_lock_never_held_is_a_noop(tmp_path: Path, short_run_dir: Path) -> None:
+ assert cli.cmd_stop(_ns(tmp_path, short_run_dir)) == 0
+
+
+def test_cli_stop_prints_a_message_when_project_root_does_not_exist(
+ tmp_path: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ """A --project value that names nothing gets its own message, not the run-directory one."""
+ missing_root = tmp_path / "never-served"
+ run_dir = missing_root / ".apache-magpie-local" / "run"
+ rc = cli.cmd_stop(_ns(missing_root, run_dir))
+ out = capsys.readouterr().out
+ assert rc == 0
+ assert f"no project root at {missing_root}: nothing to stop" in out
+
+
+def test_cli_stop_prints_a_message_when_no_run_directory_ever_existed(
+ tmp_path: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ """A project that exists but was never served must not look identical to "stopped successfully"."""
+ project_root = tmp_path / "served-project"
+ project_root.mkdir()
+ run_dir = project_root / ".apache-magpie-local" / "run"
+ rc = cli.cmd_stop(_ns(project_root, run_dir))
+ out = capsys.readouterr().out
+ assert rc == 0
+ assert f"no run directory at {run_dir}: nothing to stop" in out
+
+
+# ------------------------- D3: unlink the pid file before closing its fd
+
+
+def test_run_unlinks_pid_file_before_closing_the_lock_fd(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ events: list[str] = []
+ real_unlink = Path.unlink
+ real_close = os.close
+ pid_file = short_run_dir / "pid"
+
+ def recording_unlink(self: Path, missing_ok: bool = False) -> None:
+ if self == pid_file:
+ events.append("unlink")
+ real_unlink(self, missing_ok=missing_ok)
+
+ def recording_close(fd: int) -> None:
+ events.append("close")
+ real_close(fd)
+
+ monkeypatch.setattr(Path, "unlink", recording_unlink)
+ monkeypatch.setattr(os, "close", recording_close)
+
+ cfg = daemon.Config(
+ tmp_path, short_run_dir, ("podman", "docker"), "off", 8899, None, (), 5.0, "INFO", pid_file
+ )
+
+ async def scenario() -> None:
+ rc = await daemon.run(cfg, discover_fn=lambda *a, **k: [], platform="Darwin")
+ assert rc == 0
+
+ run(scenario())
+ assert "unlink" in events
+ assert "close" in events
+ assert events.index("unlink") < events.index("close")
+
+
+# ---------------------------------------------------------------- I5
+
+
+def test_partial_bind_failure_cleans_up_first_socket_and_server(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ calls: list[Path] = []
+ closed: list[bool] = []
+
+ class _FakeServer:
+ def close(self) -> None:
+ closed.append(True)
+
+ async def wait_closed(self) -> None:
+ return None
+
+ async def fake_serve_unix(path: Path, handler: Any) -> _FakeServer:
+ calls.append(path)
+ if len(calls) == 2:
+ raise OSError("simulated bind failure")
+ path.write_text("") # stand in for "a socket file now exists here"
+ return _FakeServer()
+
+ monkeypatch.setattr(daemon, "serve_unix", fake_serve_unix)
+ cfg = daemon.Config(
+ tmp_path,
+ short_run_dir,
+ ("podman", "docker"),
+ "off",
+ 8899,
+ None,
+ (),
+ 5.0,
+ "INFO",
+ short_run_dir / "pid",
+ )
+ found = [Backend("podman", short_run_dir / "upstream.sock", "host.containers.internal")]
+
+ async def scenario() -> None:
+ with pytest.raises(OSError, match="simulated bind failure"):
+ await daemon.run(cfg, discover_fn=lambda *a, **k: found, platform="Darwin")
+
+ run(scenario())
+ assert closed == [True]
+ assert not (short_run_dir / "podman.sock").exists()
+ assert not cfg.pid_file.exists()
+
+
+# ------------------------------------------------------- M9: probe_egress
+
+
+def test_probe_egress_true_when_something_listens() -> None:
+ async def scenario() -> None:
+ try:
+ server = await asyncio.start_server(lambda r, w: None, host="127.0.0.1", port=0)
+ except PermissionError:
+ pytest.skip("sandbox denies TCP bind; runs in CI")
+ try:
+ port = server.sockets[0].getsockname()[1]
+ assert await daemon.probe_egress("host.containers.internal", port) is True
+ finally:
+ server.close()
+ await server.wait_closed()
+
+ run(scenario())
+
+
+def test_probe_egress_false_when_nothing_listens() -> None:
+ async def scenario() -> None:
+ try:
+ server = await asyncio.start_server(lambda r, w: None, host="127.0.0.1", port=0)
+ except PermissionError:
+ pytest.skip("sandbox denies TCP bind; runs in CI")
+ port = server.sockets[0].getsockname()[1]
Review Comment:
## CodeQL / Potentially uninitialized local variable
Local variable 'server' may be used before it is initialized.
[Show more details](https://github.com/apache/magpie/security/code-scanning/78)
##########
tools/container-gateway/tests/test_daemon.py:
##########
@@ -0,0 +1,1013 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Daemon plumbing: paths, guards, idle exit, status and stop.
+
+Threat model exercised throughout this file: the daemon runs OUTSIDE the
+sandbox with the operator's own privileges, while the sandboxed agent
+can create, delete and symlink anything under the project tree,
+including ``.apache-magpie-local/run/``. Every guard test below plants
+exactly the kind of hostile filesystem state that threat model implies
+and checks the guard refuses it -- no bind needed for any of them.
+
+No ``pytest-asyncio`` in the ``magpie-dev`` dependency group, so each
+async scenario is a plain ``def`` test driving its coroutine through the
+``run()`` helper, exactly as ``test_http.py`` and ``test_relay.py`` do.
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import json
+import os
+import shutil
+import signal
+import subprocess
+import sys
+import tempfile
+from collections.abc import Coroutine, Iterator
+from pathlib import Path
+from typing import Any, TypeVar
+
+import pytest
+
+from container_gateway import __main__ as cli
+from container_gateway import daemon
+from container_gateway.backends import Backend
+
+from .fakebackend import FakeBackend
+
+SRC = Path(__file__).resolve().parents[1] / "src"
+
+_T = TypeVar("_T")
+
+
+def run(coro: Coroutine[Any, Any, _T]) -> _T:
+ """Drive a coroutine to completion without pytest-asyncio."""
+ return asyncio.run(coro)
+
+
+def _ns(project: Path, run_dir: Path, **extra: Any) -> argparse.Namespace:
+ """A minimal argparse.Namespace for calling cmd_serve/cmd_stop/cmd_status directly."""
+ base = {"project": project, "run_dir": run_dir, "pid_file": None}
+ base.update(extra)
+ return argparse.Namespace(**base)
+
+
+@pytest.fixture
+def short_run_dir() -> Iterator[Path]:
+ """A run directory short enough to hold a unix-socket path.
+
+ ``pytest``'s own ``tmp_path`` fixture nests under
+ ``pytest-of-<user>/pytest-<n>/<test-name>/`` inside ``$TMPDIR``, which
+ in this sandboxed dev environment is already long enough on its own
+ to blow the ~103-byte ``sun_path`` limit before ``run_dir`` even adds
+ ``podman.sock``. ``tempfile.mkdtemp()`` sits directly under
+ ``$TMPDIR`` with none of that nesting, so it stays short everywhere
+ ``tmp_path`` might not. It is also already 0700 and owned by us, so
+ it satisfies ``check_run_dir``'s "custom run-dir" branch as-is.
+ """
+ d = Path(tempfile.mkdtemp(prefix="cg-"))
+ try:
+ yield d
+ finally:
+ shutil.rmtree(d, ignore_errors=True)
+
+
+class _RealSocketBackend:
+ """A ``FakeBackend`` served over a real filesystem unix socket.
+
+ ``tests/fakebackend.FakeBackend`` only ever hands out in-process
+ ``socket.socketpair()`` connections (the sandbox refuses ``bind()``,
+ so it never listens on a path) -- but ``daemon.run()`` needs a real
+ socket path to hand to ``unix_connector`` for a ``Backend``. This
+ thin wrapper does the one real bind these daemon tests need, so it
+ can hit the same ``PermissionError`` the sandbox raises and skip
+ exactly like every other bind-touching test in this suite.
+ """
+
+ def __init__(self, socket_path: Path) -> None:
+ self.socket = socket_path
+ self._fake = FakeBackend()
+ self._server: asyncio.AbstractServer | None = None
+
+ async def start(self) -> None:
+ self._server = await asyncio.start_unix_server(self._fake._handle, path=str(self.socket))
+
+ async def stop(self) -> None:
+ if self._server is not None:
+ self._server.close()
+ await self._server.wait_closed()
+
+
+# --------------------------------------------------------------- paths
+
+
+def test_paths_and_socket_length(tmp_path: Path) -> None:
+ p = daemon.paths(tmp_path)
+ assert p["podman"].name == "podman.sock" and p["docker"].name == "docker.sock"
+ # A literal short path, not tmp_path: with TMPDIR unset, tmp_path's
+ # pytest-of-<user>/pytest-<n>/<test-name>/ nesting is already long
+ # enough to exceed the ~103-byte sun_path limit on its own, and
+ # check_socket_path only measures byte length.
+ daemon.check_socket_path(Path("/tmp/ok.sock"))
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_socket_path(Path("/" + "x" * 120 + "/podman.sock"))
+ assert exc.value.code == 2
+
+
+# ------------------------------------------------ C2: run dir / symlinks
+
+
+def test_check_run_dir_default_layout_creates_both_dirs_0700(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ run_dir = project_root / ".apache-magpie-local" / "run"
+ daemon.check_run_dir(run_dir, project_root)
+ assert (project_root / ".apache-magpie-local").stat().st_mode & 0o777 == 0o700
+ assert run_dir.stat().st_mode & 0o777 == 0o700
+
+
+def test_check_run_dir_refuses_world_writable_existing_dir(tmp_path: Path) -> None:
+ project_root = tmp_path
+ run_dir = tmp_path / "custom-run"
+ daemon.check_run_dir(run_dir, project_root)
+ assert run_dir.stat().st_mode & 0o777 == 0o700
+ run_dir.chmod(0o777)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(run_dir, project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_run(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ magpie_local = project_root / ".apache-magpie-local"
+ magpie_local.mkdir(parents=True, mode=0o700)
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (magpie_local / "run").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(magpie_local / "run", project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_apache_magpie_local(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (project_root / ".apache-magpie-local").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(project_root / ".apache-magpie-local" / "run", project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_custom_run_dir(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ custom = tmp_path / "custom-run"
+ custom.symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(custom, project_root)
+ assert exc.value.code == 2
+
+
+# ------------------------------------------- D5: missing ancestors refuse
+
+
+def test_check_run_dir_refuses_missing_project_root(tmp_path: Path) -> None:
+ missing_root = tmp_path / "does-not-exist"
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(missing_root / ".apache-magpie-local" / "run", missing_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_missing_custom_run_dir_parent(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ missing_parent_run_dir = tmp_path / "does-not-exist" / "run"
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(missing_parent_run_dir, project_root)
+ assert exc.value.code == 2
+
+
+def test_validate_run_dir_false_when_project_root_missing(tmp_path: Path) -> None:
+ missing_root = tmp_path / "does-not-exist"
+ assert daemon.validate_run_dir(missing_root / ".apache-magpie-local" / "run", missing_root) is False
+
+
+def test_validate_run_dir_false_when_custom_parent_missing(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ missing_parent_run_dir = tmp_path / "does-not-exist" / "run"
+ assert daemon.validate_run_dir(missing_parent_run_dir, project_root) is False
+
+
+# --------------------------------------- D6: lstat-then-mkdir race safety
+
+
+def test_ensure_owned_private_dir_handles_mkdir_race_with_planted_symlink(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ target = tmp_path / "custom-run"
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ real_mkdir = Path.mkdir
+
+ def racy_mkdir(self: Path, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None:
+ if self == target:
+ target.symlink_to(evil) # someone (or something) won the race and planted a symlink
+ raise FileExistsError(f"[Errno 17] File exists: '{target}'")
+ real_mkdir(self, mode, parents=parents, exist_ok=exist_ok)
+
+ monkeypatch.setattr(Path, "mkdir", racy_mkdir)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(target, tmp_path)
+ assert exc.value.code == 2
+
+
+# --------------------------------------------------- C2: socket guards
+
+
+def test_check_socket_type_refuses_non_socket(tmp_path: Path) -> None:
+ p = tmp_path / "podman.sock"
+ p.write_text("not a socket")
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_socket_type(p)
+ assert exc.value.code == 2
+
+
+def test_check_socket_type_allows_missing_path(tmp_path: Path) -> None:
+ daemon.check_socket_type(tmp_path / "missing.sock") # nothing there yet: fine
+
+
+# ------------------------------------------------------ C2: pid / log fd
+
+
+def test_acquire_pid_lock_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.pid"
+ target.write_text("")
+ link = tmp_path / "container-gateway.pid"
+ link.symlink_to(target)
+ with pytest.raises(SystemExit) as exc:
+ daemon.acquire_pid_lock(link)
+ assert exc.value.code == 2
+
+
+def test_probe_pid_lock_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.pid"
+ target.write_text("")
+ link = tmp_path / "container-gateway.pid"
+ link.symlink_to(target)
+ with pytest.raises(SystemExit) as exc:
+ daemon.probe_pid_lock(link)
+ assert exc.value.code == 2
+
+
+def test_probe_pid_lock_not_running_when_run_dir_absent(tmp_path: Path) -> None:
+ never_created = tmp_path / "never" / "container-gateway.pid"
+ assert daemon.probe_pid_lock(never_created) == (False, None)
+
+
+def test_open_log_fd_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.log"
+ target.write_text("")
+ link = tmp_path / "container-gateway.log"
+ link.symlink_to(target)
+ with pytest.raises(SystemExit) as exc:
+ cli._open_log_fd(link)
+ assert exc.value.code == 2
+
+
+# --------------------- D2: acquire_pid_lock never blanks a live pid file
+
+
+def test_acquire_pid_lock_does_not_blank_a_live_daemons_pid_file(tmp_path: Path) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ os.ftruncate(fd, 0)
+ os.lseek(fd, 0, 0)
+ os.write(fd, b"4242\n")
+ os.fsync(fd)
+ second = daemon.acquire_pid_lock(pid_file)
+ assert second is None
+ assert pid_file.read_text() == "4242\n"
+ finally:
+ os.close(fd)
+
+
+# ------------------------------------- D1: status/stop bypassed check_run_dir
+
+
+def test_pid_file_is_trustworthy_none_when_missing(tmp_path: Path) -> None:
+ assert daemon.pid_file_is_trustworthy(tmp_path / "container-gateway.pid") is None
+
+
+def test_pid_file_is_trustworthy_true_for_a_lock_created_file(tmp_path: Path) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ assert daemon.pid_file_is_trustworthy(pid_file) is True
+ finally:
+ os.close(fd)
+
+
+def test_pid_file_is_trustworthy_false_for_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.pid"
+ target.write_text("4242\n")
+ target.chmod(0o600)
+ link = tmp_path / "container-gateway.pid"
+ link.symlink_to(target)
+ assert daemon.pid_file_is_trustworthy(link) is False
+
+
+def test_pid_file_is_trustworthy_false_for_wrong_mode(tmp_path: Path) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ pid_file.write_text("4242\n")
+ pid_file.chmod(0o644)
+ assert daemon.pid_file_is_trustworthy(pid_file) is False
+
+
+def test_cli_status_refuses_symlinked_run_dir(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ magpie_local = project_root / ".apache-magpie-local"
+ magpie_local.mkdir(parents=True, mode=0o700)
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (magpie_local / "run").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ cli.cmd_status(_ns(project_root, magpie_local / "run"))
+ assert exc.value.code == 2
+
+
+def test_cli_stop_refuses_symlinked_run_dir_without_signalling(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ project_root = tmp_path / "proj"
+ magpie_local = project_root / ".apache-magpie-local"
+ magpie_local.mkdir(parents=True, mode=0o700)
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (magpie_local / "run").symlink_to(evil)
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ with pytest.raises(SystemExit) as exc:
+ cli.cmd_stop(_ns(project_root, magpie_local / "run"))
+ assert exc.value.code == 2
+ assert calls == []
+
+
+def test_cli_stop_refuses_pid_file_with_wrong_mode(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ pid_file.write_text("4242\n")
+ pid_file.chmod(0o644)
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ with pytest.raises(SystemExit) as exc:
+ cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert exc.value.code == 2
+ assert calls == []
+
+
+def test_cli_status_treats_wrong_mode_pid_file_as_not_running(
+ tmp_path: Path, short_run_dir: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ pid_file.write_text("4242\n")
+ pid_file.chmod(0o644)
+ rc = cli.cmd_status(_ns(tmp_path, short_run_dir))
+ out = json.loads(capsys.readouterr().out)
+ assert rc == 3
+ assert out["running"] is False
+ # Untrustworthy content is left alone, not deleted, by `status`.
+ assert pid_file.exists()
+
+
+# -------------------------------- D4: stop verifies the signalled process
+
+
+def test_cli_stop_refuses_when_process_does_not_look_like_gateway(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ monkeypatch.setattr("container_gateway.backends.default_runner", lambda argv: "bash -c sleep 100")
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+def test_cli_stop_refuses_a_process_that_merely_mentions_the_module_name(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """An editor opened on a file named ``container_gateway.py`` is not the gateway.
+
+ A substring check on the ``ps`` line would wrongly treat this as a
+ match; the argv-shape check must not.
+ """
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ monkeypatch.setattr(
+ "container_gateway.backends.default_runner", lambda argv: "vim container_gateway.py"
+ )
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+def test_cli_stop_checks_only_the_first_line_of_ps_output(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A gateway-shaped second line must not rescue a non-gateway first line."""
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ monkeypatch.setattr(
+ "container_gateway.backends.default_runner",
+ lambda argv: "bash -c sleep 100\npython3 -m container_gateway serve --project /x",
+ )
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+def test_cli_stop_signals_when_process_is_the_console_script(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The installed ``container-gateway`` console script is also recognised, not just ``python -m``."""
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ our_pid = os.getpid()
+ calls: list[tuple[int, int]] = []
+ terminated = False
+
+ def fake_kill(pid: int, sig: int) -> None:
+ nonlocal terminated
+ calls.append((pid, sig))
+ if sig == signal.SIGTERM:
+ terminated = True
+ os.close(fd) # simulate the daemon exiting: release the flock
+ elif terminated:
+ raise ProcessLookupError
+
+ monkeypatch.setattr(os, "kill", fake_kill)
+ monkeypatch.setattr(
+ "container_gateway.backends.default_runner",
+ lambda argv: "/usr/local/bin/container-gateway serve --project /x",
+ )
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert rc == 0
+ assert (our_pid, signal.SIGTERM) in calls
+
+
+@pytest.mark.parametrize(
+ "command_line",
+ [
+ "python3 -u -m container_gateway serve --project /x",
+ "uv run python -m container_gateway serve --project /x",
+ ],
+)
+def test_cli_stop_signals_a_python_dash_m_invocation_with_extra_argv(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch, command_line: str
+) -> None:
+ """Interpreter flags (``-u``) and a runner prefix (``uv run``) do not defeat the argv-shape match."""
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ our_pid = os.getpid()
+ calls: list[tuple[int, int]] = []
+ terminated = False
+
+ def fake_kill(pid: int, sig: int) -> None:
+ nonlocal terminated
+ calls.append((pid, sig))
+ if sig == signal.SIGTERM:
+ terminated = True
+ os.close(fd) # simulate the daemon exiting: release the flock
+ elif terminated:
+ raise ProcessLookupError
+
+ monkeypatch.setattr(os, "kill", fake_kill)
+ monkeypatch.setattr("container_gateway.backends.default_runner", lambda argv: command_line)
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert rc == 0
+ assert (our_pid, signal.SIGTERM) in calls
+
+
+def test_cli_stop_refuses_when_ps_is_unavailable(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ monkeypatch.setattr("container_gateway.backends.default_runner", lambda argv: None)
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+# --------------------------------------------------------------- C1: pid
+
+
+@pytest.mark.parametrize("content", ["-1", "0", "1", "abc", "12 34", "99999999999", ""])
+def test_read_pid_rejects_unsafe_content(tmp_path: Path, content: str) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ pid_file.write_text(content)
+ assert daemon.read_pid(pid_file) is None
+
+
+def test_read_pid_accepts_a_real_pid(tmp_path: Path) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ pid_file.write_text("42\n")
+ assert daemon.read_pid(pid_file) == 42
+
+
+def test_pid_alive_false_for_pid_le_1() -> None:
+ assert daemon.pid_alive(0) is False
+ assert daemon.pid_alive(1) is False
+ assert daemon.pid_alive(-1) is False
+
+
+@pytest.mark.parametrize("content", ["-1", "0", "1", "abc", "12 34"])
+def test_cli_stop_with_unsafe_pid_file_does_not_signal(
+ tmp_path: Path, short_run_dir: Path, content: str, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ pid_file.write_text(content)
+ pid_file.chmod(0o600) # a trustworthy *file*; the *content* is what's unsafe here
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 0
+
+
+def test_cli_stop_does_not_signal_when_lock_held_but_pid_content_poisoned(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A live, lock-holding instance whose pid-file *content* was overwritten afterwards.
+
+ ``stop`` must refuse to guess: something is clearly running (the
+ lock says so), but nothing safe to signal can be read back out of
+ the file.
+ """
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ os.ftruncate(fd, 0)
+ os.lseek(fd, 0, 0)
+ os.write(fd, b"-1\n")
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+# --------------------------------------------- I3+I4: flock single instance
+
+
+def test_cli_serve_short_circuits_when_lock_already_held(tmp_path: Path, short_run_dir: Path) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ ns = _ns(
+ tmp_path,
+ short_run_dir,
+ daemon=False,
+ backend=None,
+ egress="off",
+ egress_port=8899,
+ egress_host=None,
+ extra_bind_root=None,
+ idle_timeout=5.0,
+ backend_timeout=60.0,
+ log_level="INFO",
+ )
+ assert cli.cmd_serve(ns) == 0
+ assert not (short_run_dir / "podman.sock").exists()
+ assert not (short_run_dir / "docker.sock").exists()
+ finally:
+ os.close(fd)
+
+
+def test_cli_status_reports_running_when_lock_held(
+ tmp_path: Path, short_run_dir: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ rc = cli.cmd_status(_ns(tmp_path, short_run_dir))
+ out = json.loads(capsys.readouterr().out)
+ finally:
+ os.close(fd)
+ assert rc == 0
+ assert out["running"] is True
+ assert out["pid"] == os.getpid()
+ assert out["serving"] == [] # no sockets actually bound in this test
+
+
+def test_cli_status_removes_stale_pid_file_when_no_lock_held(
+ tmp_path: Path, short_run_dir: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ pid_file.write_text("424242\n") # a stale pid; nobody holds its lock
+ pid_file.chmod(0o600) # a trustworthy, well-formed pid file -- just stale
+ rc = cli.cmd_status(_ns(tmp_path, short_run_dir))
+ out = json.loads(capsys.readouterr().out)
+ assert rc == 3
+ assert out["running"] is False
+ assert out["pid"] is None
+ assert not pid_file.exists()
+
+
+def test_cli_stop_signals_the_pid_and_reports_stopped(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ our_pid = os.getpid()
+ calls: list[tuple[int, int]] = []
+ terminated = False
+
+ def fake_kill(pid: int, sig: int) -> None:
+ nonlocal terminated
+ calls.append((pid, sig))
+ if sig == signal.SIGTERM:
+ terminated = True
+ os.close(fd) # simulate the daemon exiting: release the flock
+ elif terminated:
+ raise ProcessLookupError
+
+ monkeypatch.setattr(os, "kill", fake_kill)
+ monkeypatch.setattr(
+ "container_gateway.backends.default_runner",
+ lambda argv: "python3 -m container_gateway serve --project /x",
+ )
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert rc == 0
+ assert (our_pid, signal.SIGTERM) in calls
+
+
+def test_cli_stop_when_lock_never_held_is_a_noop(tmp_path: Path, short_run_dir: Path) -> None:
+ assert cli.cmd_stop(_ns(tmp_path, short_run_dir)) == 0
+
+
+def test_cli_stop_prints_a_message_when_project_root_does_not_exist(
+ tmp_path: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ """A --project value that names nothing gets its own message, not the run-directory one."""
+ missing_root = tmp_path / "never-served"
+ run_dir = missing_root / ".apache-magpie-local" / "run"
+ rc = cli.cmd_stop(_ns(missing_root, run_dir))
+ out = capsys.readouterr().out
+ assert rc == 0
+ assert f"no project root at {missing_root}: nothing to stop" in out
+
+
+def test_cli_stop_prints_a_message_when_no_run_directory_ever_existed(
+ tmp_path: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ """A project that exists but was never served must not look identical to "stopped successfully"."""
+ project_root = tmp_path / "served-project"
+ project_root.mkdir()
+ run_dir = project_root / ".apache-magpie-local" / "run"
+ rc = cli.cmd_stop(_ns(project_root, run_dir))
+ out = capsys.readouterr().out
+ assert rc == 0
+ assert f"no run directory at {run_dir}: nothing to stop" in out
+
+
+# ------------------------- D3: unlink the pid file before closing its fd
+
+
+def test_run_unlinks_pid_file_before_closing_the_lock_fd(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ events: list[str] = []
+ real_unlink = Path.unlink
+ real_close = os.close
+ pid_file = short_run_dir / "pid"
+
+ def recording_unlink(self: Path, missing_ok: bool = False) -> None:
+ if self == pid_file:
+ events.append("unlink")
+ real_unlink(self, missing_ok=missing_ok)
+
+ def recording_close(fd: int) -> None:
+ events.append("close")
+ real_close(fd)
+
+ monkeypatch.setattr(Path, "unlink", recording_unlink)
+ monkeypatch.setattr(os, "close", recording_close)
+
+ cfg = daemon.Config(
+ tmp_path, short_run_dir, ("podman", "docker"), "off", 8899, None, (), 5.0, "INFO", pid_file
+ )
+
+ async def scenario() -> None:
+ rc = await daemon.run(cfg, discover_fn=lambda *a, **k: [], platform="Darwin")
+ assert rc == 0
+
+ run(scenario())
+ assert "unlink" in events
+ assert "close" in events
+ assert events.index("unlink") < events.index("close")
+
+
+# ---------------------------------------------------------------- I5
+
+
+def test_partial_bind_failure_cleans_up_first_socket_and_server(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ calls: list[Path] = []
+ closed: list[bool] = []
+
+ class _FakeServer:
+ def close(self) -> None:
+ closed.append(True)
+
+ async def wait_closed(self) -> None:
+ return None
+
+ async def fake_serve_unix(path: Path, handler: Any) -> _FakeServer:
+ calls.append(path)
+ if len(calls) == 2:
+ raise OSError("simulated bind failure")
+ path.write_text("") # stand in for "a socket file now exists here"
+ return _FakeServer()
+
+ monkeypatch.setattr(daemon, "serve_unix", fake_serve_unix)
+ cfg = daemon.Config(
+ tmp_path,
+ short_run_dir,
+ ("podman", "docker"),
+ "off",
+ 8899,
+ None,
+ (),
+ 5.0,
+ "INFO",
+ short_run_dir / "pid",
+ )
+ found = [Backend("podman", short_run_dir / "upstream.sock", "host.containers.internal")]
+
+ async def scenario() -> None:
+ with pytest.raises(OSError, match="simulated bind failure"):
+ await daemon.run(cfg, discover_fn=lambda *a, **k: found, platform="Darwin")
+
+ run(scenario())
+ assert closed == [True]
+ assert not (short_run_dir / "podman.sock").exists()
+ assert not cfg.pid_file.exists()
+
+
+# ------------------------------------------------------- M9: probe_egress
+
+
+def test_probe_egress_true_when_something_listens() -> None:
+ async def scenario() -> None:
+ try:
+ server = await asyncio.start_server(lambda r, w: None, host="127.0.0.1", port=0)
+ except PermissionError:
+ pytest.skip("sandbox denies TCP bind; runs in CI")
+ try:
+ port = server.sockets[0].getsockname()[1]
Review Comment:
## CodeQL / Potentially uninitialized local variable
Local variable 'server' may be used before it is initialized.
[Show more details](https://github.com/apache/magpie/security/code-scanning/77)
##########
tools/container-gateway/tests/test_daemon.py:
##########
@@ -0,0 +1,1013 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Daemon plumbing: paths, guards, idle exit, status and stop.
+
+Threat model exercised throughout this file: the daemon runs OUTSIDE the
+sandbox with the operator's own privileges, while the sandboxed agent
+can create, delete and symlink anything under the project tree,
+including ``.apache-magpie-local/run/``. Every guard test below plants
+exactly the kind of hostile filesystem state that threat model implies
+and checks the guard refuses it -- no bind needed for any of them.
+
+No ``pytest-asyncio`` in the ``magpie-dev`` dependency group, so each
+async scenario is a plain ``def`` test driving its coroutine through the
+``run()`` helper, exactly as ``test_http.py`` and ``test_relay.py`` do.
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import json
+import os
+import shutil
+import signal
+import subprocess
+import sys
+import tempfile
+from collections.abc import Coroutine, Iterator
+from pathlib import Path
+from typing import Any, TypeVar
+
+import pytest
+
+from container_gateway import __main__ as cli
+from container_gateway import daemon
+from container_gateway.backends import Backend
+
+from .fakebackend import FakeBackend
+
+SRC = Path(__file__).resolve().parents[1] / "src"
+
+_T = TypeVar("_T")
+
+
+def run(coro: Coroutine[Any, Any, _T]) -> _T:
+ """Drive a coroutine to completion without pytest-asyncio."""
+ return asyncio.run(coro)
+
+
+def _ns(project: Path, run_dir: Path, **extra: Any) -> argparse.Namespace:
+ """A minimal argparse.Namespace for calling cmd_serve/cmd_stop/cmd_status directly."""
+ base = {"project": project, "run_dir": run_dir, "pid_file": None}
+ base.update(extra)
+ return argparse.Namespace(**base)
+
+
+@pytest.fixture
+def short_run_dir() -> Iterator[Path]:
+ """A run directory short enough to hold a unix-socket path.
+
+ ``pytest``'s own ``tmp_path`` fixture nests under
+ ``pytest-of-<user>/pytest-<n>/<test-name>/`` inside ``$TMPDIR``, which
+ in this sandboxed dev environment is already long enough on its own
+ to blow the ~103-byte ``sun_path`` limit before ``run_dir`` even adds
+ ``podman.sock``. ``tempfile.mkdtemp()`` sits directly under
+ ``$TMPDIR`` with none of that nesting, so it stays short everywhere
+ ``tmp_path`` might not. It is also already 0700 and owned by us, so
+ it satisfies ``check_run_dir``'s "custom run-dir" branch as-is.
+ """
+ d = Path(tempfile.mkdtemp(prefix="cg-"))
+ try:
+ yield d
+ finally:
+ shutil.rmtree(d, ignore_errors=True)
+
+
+class _RealSocketBackend:
+ """A ``FakeBackend`` served over a real filesystem unix socket.
+
+ ``tests/fakebackend.FakeBackend`` only ever hands out in-process
+ ``socket.socketpair()`` connections (the sandbox refuses ``bind()``,
+ so it never listens on a path) -- but ``daemon.run()`` needs a real
+ socket path to hand to ``unix_connector`` for a ``Backend``. This
+ thin wrapper does the one real bind these daemon tests need, so it
+ can hit the same ``PermissionError`` the sandbox raises and skip
+ exactly like every other bind-touching test in this suite.
+ """
+
+ def __init__(self, socket_path: Path) -> None:
+ self.socket = socket_path
+ self._fake = FakeBackend()
+ self._server: asyncio.AbstractServer | None = None
+
+ async def start(self) -> None:
+ self._server = await asyncio.start_unix_server(self._fake._handle, path=str(self.socket))
+
+ async def stop(self) -> None:
+ if self._server is not None:
+ self._server.close()
+ await self._server.wait_closed()
+
+
+# --------------------------------------------------------------- paths
+
+
+def test_paths_and_socket_length(tmp_path: Path) -> None:
+ p = daemon.paths(tmp_path)
+ assert p["podman"].name == "podman.sock" and p["docker"].name == "docker.sock"
+ # A literal short path, not tmp_path: with TMPDIR unset, tmp_path's
+ # pytest-of-<user>/pytest-<n>/<test-name>/ nesting is already long
+ # enough to exceed the ~103-byte sun_path limit on its own, and
+ # check_socket_path only measures byte length.
+ daemon.check_socket_path(Path("/tmp/ok.sock"))
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_socket_path(Path("/" + "x" * 120 + "/podman.sock"))
+ assert exc.value.code == 2
+
+
+# ------------------------------------------------ C2: run dir / symlinks
+
+
+def test_check_run_dir_default_layout_creates_both_dirs_0700(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ run_dir = project_root / ".apache-magpie-local" / "run"
+ daemon.check_run_dir(run_dir, project_root)
+ assert (project_root / ".apache-magpie-local").stat().st_mode & 0o777 == 0o700
+ assert run_dir.stat().st_mode & 0o777 == 0o700
+
+
+def test_check_run_dir_refuses_world_writable_existing_dir(tmp_path: Path) -> None:
+ project_root = tmp_path
+ run_dir = tmp_path / "custom-run"
+ daemon.check_run_dir(run_dir, project_root)
+ assert run_dir.stat().st_mode & 0o777 == 0o700
+ run_dir.chmod(0o777)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(run_dir, project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_run(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ magpie_local = project_root / ".apache-magpie-local"
+ magpie_local.mkdir(parents=True, mode=0o700)
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (magpie_local / "run").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(magpie_local / "run", project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_apache_magpie_local(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (project_root / ".apache-magpie-local").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(project_root / ".apache-magpie-local" / "run", project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_custom_run_dir(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ custom = tmp_path / "custom-run"
+ custom.symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(custom, project_root)
+ assert exc.value.code == 2
+
+
+# ------------------------------------------- D5: missing ancestors refuse
+
+
+def test_check_run_dir_refuses_missing_project_root(tmp_path: Path) -> None:
+ missing_root = tmp_path / "does-not-exist"
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(missing_root / ".apache-magpie-local" / "run", missing_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_missing_custom_run_dir_parent(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ missing_parent_run_dir = tmp_path / "does-not-exist" / "run"
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(missing_parent_run_dir, project_root)
+ assert exc.value.code == 2
+
+
+def test_validate_run_dir_false_when_project_root_missing(tmp_path: Path) -> None:
+ missing_root = tmp_path / "does-not-exist"
+ assert daemon.validate_run_dir(missing_root / ".apache-magpie-local" / "run", missing_root) is False
+
+
+def test_validate_run_dir_false_when_custom_parent_missing(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ missing_parent_run_dir = tmp_path / "does-not-exist" / "run"
+ assert daemon.validate_run_dir(missing_parent_run_dir, project_root) is False
+
+
+# --------------------------------------- D6: lstat-then-mkdir race safety
+
+
+def test_ensure_owned_private_dir_handles_mkdir_race_with_planted_symlink(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ target = tmp_path / "custom-run"
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ real_mkdir = Path.mkdir
+
+ def racy_mkdir(self: Path, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None:
+ if self == target:
+ target.symlink_to(evil) # someone (or something) won the race and planted a symlink
+ raise FileExistsError(f"[Errno 17] File exists: '{target}'")
+ real_mkdir(self, mode, parents=parents, exist_ok=exist_ok)
+
+ monkeypatch.setattr(Path, "mkdir", racy_mkdir)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(target, tmp_path)
+ assert exc.value.code == 2
+
+
+# --------------------------------------------------- C2: socket guards
+
+
+def test_check_socket_type_refuses_non_socket(tmp_path: Path) -> None:
+ p = tmp_path / "podman.sock"
+ p.write_text("not a socket")
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_socket_type(p)
+ assert exc.value.code == 2
+
+
+def test_check_socket_type_allows_missing_path(tmp_path: Path) -> None:
+ daemon.check_socket_type(tmp_path / "missing.sock") # nothing there yet: fine
+
+
+# ------------------------------------------------------ C2: pid / log fd
+
+
+def test_acquire_pid_lock_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.pid"
+ target.write_text("")
+ link = tmp_path / "container-gateway.pid"
+ link.symlink_to(target)
+ with pytest.raises(SystemExit) as exc:
+ daemon.acquire_pid_lock(link)
+ assert exc.value.code == 2
+
+
+def test_probe_pid_lock_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.pid"
+ target.write_text("")
+ link = tmp_path / "container-gateway.pid"
+ link.symlink_to(target)
+ with pytest.raises(SystemExit) as exc:
+ daemon.probe_pid_lock(link)
+ assert exc.value.code == 2
+
+
+def test_probe_pid_lock_not_running_when_run_dir_absent(tmp_path: Path) -> None:
+ never_created = tmp_path / "never" / "container-gateway.pid"
+ assert daemon.probe_pid_lock(never_created) == (False, None)
+
+
+def test_open_log_fd_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.log"
+ target.write_text("")
+ link = tmp_path / "container-gateway.log"
+ link.symlink_to(target)
+ with pytest.raises(SystemExit) as exc:
+ cli._open_log_fd(link)
+ assert exc.value.code == 2
+
+
+# --------------------- D2: acquire_pid_lock never blanks a live pid file
+
+
+def test_acquire_pid_lock_does_not_blank_a_live_daemons_pid_file(tmp_path: Path) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ os.ftruncate(fd, 0)
+ os.lseek(fd, 0, 0)
+ os.write(fd, b"4242\n")
+ os.fsync(fd)
+ second = daemon.acquire_pid_lock(pid_file)
+ assert second is None
+ assert pid_file.read_text() == "4242\n"
+ finally:
+ os.close(fd)
+
+
+# ------------------------------------- D1: status/stop bypassed check_run_dir
+
+
+def test_pid_file_is_trustworthy_none_when_missing(tmp_path: Path) -> None:
+ assert daemon.pid_file_is_trustworthy(tmp_path / "container-gateway.pid") is None
+
+
+def test_pid_file_is_trustworthy_true_for_a_lock_created_file(tmp_path: Path) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ assert daemon.pid_file_is_trustworthy(pid_file) is True
+ finally:
+ os.close(fd)
+
+
+def test_pid_file_is_trustworthy_false_for_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.pid"
+ target.write_text("4242\n")
+ target.chmod(0o600)
+ link = tmp_path / "container-gateway.pid"
+ link.symlink_to(target)
+ assert daemon.pid_file_is_trustworthy(link) is False
+
+
+def test_pid_file_is_trustworthy_false_for_wrong_mode(tmp_path: Path) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ pid_file.write_text("4242\n")
+ pid_file.chmod(0o644)
+ assert daemon.pid_file_is_trustworthy(pid_file) is False
+
+
+def test_cli_status_refuses_symlinked_run_dir(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ magpie_local = project_root / ".apache-magpie-local"
+ magpie_local.mkdir(parents=True, mode=0o700)
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (magpie_local / "run").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ cli.cmd_status(_ns(project_root, magpie_local / "run"))
+ assert exc.value.code == 2
+
+
+def test_cli_stop_refuses_symlinked_run_dir_without_signalling(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ project_root = tmp_path / "proj"
+ magpie_local = project_root / ".apache-magpie-local"
+ magpie_local.mkdir(parents=True, mode=0o700)
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (magpie_local / "run").symlink_to(evil)
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ with pytest.raises(SystemExit) as exc:
+ cli.cmd_stop(_ns(project_root, magpie_local / "run"))
+ assert exc.value.code == 2
+ assert calls == []
+
+
+def test_cli_stop_refuses_pid_file_with_wrong_mode(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ pid_file.write_text("4242\n")
+ pid_file.chmod(0o644)
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ with pytest.raises(SystemExit) as exc:
+ cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert exc.value.code == 2
+ assert calls == []
+
+
+def test_cli_status_treats_wrong_mode_pid_file_as_not_running(
+ tmp_path: Path, short_run_dir: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ pid_file.write_text("4242\n")
+ pid_file.chmod(0o644)
+ rc = cli.cmd_status(_ns(tmp_path, short_run_dir))
+ out = json.loads(capsys.readouterr().out)
+ assert rc == 3
+ assert out["running"] is False
+ # Untrustworthy content is left alone, not deleted, by `status`.
+ assert pid_file.exists()
+
+
+# -------------------------------- D4: stop verifies the signalled process
+
+
+def test_cli_stop_refuses_when_process_does_not_look_like_gateway(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ monkeypatch.setattr("container_gateway.backends.default_runner", lambda argv: "bash -c sleep 100")
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+def test_cli_stop_refuses_a_process_that_merely_mentions_the_module_name(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """An editor opened on a file named ``container_gateway.py`` is not the gateway.
+
+ A substring check on the ``ps`` line would wrongly treat this as a
+ match; the argv-shape check must not.
+ """
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ monkeypatch.setattr(
+ "container_gateway.backends.default_runner", lambda argv: "vim container_gateway.py"
+ )
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+def test_cli_stop_checks_only_the_first_line_of_ps_output(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A gateway-shaped second line must not rescue a non-gateway first line."""
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ monkeypatch.setattr(
+ "container_gateway.backends.default_runner",
+ lambda argv: "bash -c sleep 100\npython3 -m container_gateway serve --project /x",
+ )
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+def test_cli_stop_signals_when_process_is_the_console_script(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The installed ``container-gateway`` console script is also recognised, not just ``python -m``."""
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
Review Comment:
## CodeQL / File is not always closed
File is opened but is not closed.
[Show more details](https://github.com/apache/magpie/security/code-scanning/73)
##########
tools/container-gateway/tests/test_daemon.py:
##########
@@ -0,0 +1,1013 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Daemon plumbing: paths, guards, idle exit, status and stop.
+
+Threat model exercised throughout this file: the daemon runs OUTSIDE the
+sandbox with the operator's own privileges, while the sandboxed agent
+can create, delete and symlink anything under the project tree,
+including ``.apache-magpie-local/run/``. Every guard test below plants
+exactly the kind of hostile filesystem state that threat model implies
+and checks the guard refuses it -- no bind needed for any of them.
+
+No ``pytest-asyncio`` in the ``magpie-dev`` dependency group, so each
+async scenario is a plain ``def`` test driving its coroutine through the
+``run()`` helper, exactly as ``test_http.py`` and ``test_relay.py`` do.
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import json
+import os
+import shutil
+import signal
+import subprocess
+import sys
+import tempfile
+from collections.abc import Coroutine, Iterator
+from pathlib import Path
+from typing import Any, TypeVar
+
+import pytest
+
+from container_gateway import __main__ as cli
+from container_gateway import daemon
+from container_gateway.backends import Backend
+
+from .fakebackend import FakeBackend
+
+SRC = Path(__file__).resolve().parents[1] / "src"
+
+_T = TypeVar("_T")
+
+
+def run(coro: Coroutine[Any, Any, _T]) -> _T:
+ """Drive a coroutine to completion without pytest-asyncio."""
+ return asyncio.run(coro)
+
+
+def _ns(project: Path, run_dir: Path, **extra: Any) -> argparse.Namespace:
+ """A minimal argparse.Namespace for calling cmd_serve/cmd_stop/cmd_status directly."""
+ base = {"project": project, "run_dir": run_dir, "pid_file": None}
+ base.update(extra)
+ return argparse.Namespace(**base)
+
+
+@pytest.fixture
+def short_run_dir() -> Iterator[Path]:
+ """A run directory short enough to hold a unix-socket path.
+
+ ``pytest``'s own ``tmp_path`` fixture nests under
+ ``pytest-of-<user>/pytest-<n>/<test-name>/`` inside ``$TMPDIR``, which
+ in this sandboxed dev environment is already long enough on its own
+ to blow the ~103-byte ``sun_path`` limit before ``run_dir`` even adds
+ ``podman.sock``. ``tempfile.mkdtemp()`` sits directly under
+ ``$TMPDIR`` with none of that nesting, so it stays short everywhere
+ ``tmp_path`` might not. It is also already 0700 and owned by us, so
+ it satisfies ``check_run_dir``'s "custom run-dir" branch as-is.
+ """
+ d = Path(tempfile.mkdtemp(prefix="cg-"))
+ try:
+ yield d
+ finally:
+ shutil.rmtree(d, ignore_errors=True)
+
+
+class _RealSocketBackend:
+ """A ``FakeBackend`` served over a real filesystem unix socket.
+
+ ``tests/fakebackend.FakeBackend`` only ever hands out in-process
+ ``socket.socketpair()`` connections (the sandbox refuses ``bind()``,
+ so it never listens on a path) -- but ``daemon.run()`` needs a real
+ socket path to hand to ``unix_connector`` for a ``Backend``. This
+ thin wrapper does the one real bind these daemon tests need, so it
+ can hit the same ``PermissionError`` the sandbox raises and skip
+ exactly like every other bind-touching test in this suite.
+ """
+
+ def __init__(self, socket_path: Path) -> None:
+ self.socket = socket_path
+ self._fake = FakeBackend()
+ self._server: asyncio.AbstractServer | None = None
+
+ async def start(self) -> None:
+ self._server = await asyncio.start_unix_server(self._fake._handle, path=str(self.socket))
+
+ async def stop(self) -> None:
+ if self._server is not None:
+ self._server.close()
+ await self._server.wait_closed()
+
+
+# --------------------------------------------------------------- paths
+
+
+def test_paths_and_socket_length(tmp_path: Path) -> None:
+ p = daemon.paths(tmp_path)
+ assert p["podman"].name == "podman.sock" and p["docker"].name == "docker.sock"
+ # A literal short path, not tmp_path: with TMPDIR unset, tmp_path's
+ # pytest-of-<user>/pytest-<n>/<test-name>/ nesting is already long
+ # enough to exceed the ~103-byte sun_path limit on its own, and
+ # check_socket_path only measures byte length.
+ daemon.check_socket_path(Path("/tmp/ok.sock"))
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_socket_path(Path("/" + "x" * 120 + "/podman.sock"))
+ assert exc.value.code == 2
+
+
+# ------------------------------------------------ C2: run dir / symlinks
+
+
+def test_check_run_dir_default_layout_creates_both_dirs_0700(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ run_dir = project_root / ".apache-magpie-local" / "run"
+ daemon.check_run_dir(run_dir, project_root)
+ assert (project_root / ".apache-magpie-local").stat().st_mode & 0o777 == 0o700
+ assert run_dir.stat().st_mode & 0o777 == 0o700
+
+
+def test_check_run_dir_refuses_world_writable_existing_dir(tmp_path: Path) -> None:
+ project_root = tmp_path
+ run_dir = tmp_path / "custom-run"
+ daemon.check_run_dir(run_dir, project_root)
+ assert run_dir.stat().st_mode & 0o777 == 0o700
+ run_dir.chmod(0o777)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(run_dir, project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_run(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ magpie_local = project_root / ".apache-magpie-local"
+ magpie_local.mkdir(parents=True, mode=0o700)
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (magpie_local / "run").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(magpie_local / "run", project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_apache_magpie_local(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (project_root / ".apache-magpie-local").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(project_root / ".apache-magpie-local" / "run", project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_custom_run_dir(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ custom = tmp_path / "custom-run"
+ custom.symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(custom, project_root)
+ assert exc.value.code == 2
+
+
+# ------------------------------------------- D5: missing ancestors refuse
+
+
+def test_check_run_dir_refuses_missing_project_root(tmp_path: Path) -> None:
+ missing_root = tmp_path / "does-not-exist"
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(missing_root / ".apache-magpie-local" / "run", missing_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_missing_custom_run_dir_parent(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ missing_parent_run_dir = tmp_path / "does-not-exist" / "run"
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(missing_parent_run_dir, project_root)
+ assert exc.value.code == 2
+
+
+def test_validate_run_dir_false_when_project_root_missing(tmp_path: Path) -> None:
+ missing_root = tmp_path / "does-not-exist"
+ assert daemon.validate_run_dir(missing_root / ".apache-magpie-local" / "run", missing_root) is False
+
+
+def test_validate_run_dir_false_when_custom_parent_missing(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ missing_parent_run_dir = tmp_path / "does-not-exist" / "run"
+ assert daemon.validate_run_dir(missing_parent_run_dir, project_root) is False
+
+
+# --------------------------------------- D6: lstat-then-mkdir race safety
+
+
+def test_ensure_owned_private_dir_handles_mkdir_race_with_planted_symlink(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ target = tmp_path / "custom-run"
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ real_mkdir = Path.mkdir
+
+ def racy_mkdir(self: Path, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None:
+ if self == target:
+ target.symlink_to(evil) # someone (or something) won the race and planted a symlink
+ raise FileExistsError(f"[Errno 17] File exists: '{target}'")
+ real_mkdir(self, mode, parents=parents, exist_ok=exist_ok)
+
+ monkeypatch.setattr(Path, "mkdir", racy_mkdir)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(target, tmp_path)
+ assert exc.value.code == 2
+
+
+# --------------------------------------------------- C2: socket guards
+
+
+def test_check_socket_type_refuses_non_socket(tmp_path: Path) -> None:
+ p = tmp_path / "podman.sock"
+ p.write_text("not a socket")
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_socket_type(p)
+ assert exc.value.code == 2
+
+
+def test_check_socket_type_allows_missing_path(tmp_path: Path) -> None:
+ daemon.check_socket_type(tmp_path / "missing.sock") # nothing there yet: fine
+
+
+# ------------------------------------------------------ C2: pid / log fd
+
+
+def test_acquire_pid_lock_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.pid"
+ target.write_text("")
+ link = tmp_path / "container-gateway.pid"
+ link.symlink_to(target)
+ with pytest.raises(SystemExit) as exc:
+ daemon.acquire_pid_lock(link)
+ assert exc.value.code == 2
+
+
+def test_probe_pid_lock_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.pid"
+ target.write_text("")
+ link = tmp_path / "container-gateway.pid"
+ link.symlink_to(target)
+ with pytest.raises(SystemExit) as exc:
+ daemon.probe_pid_lock(link)
+ assert exc.value.code == 2
+
+
+def test_probe_pid_lock_not_running_when_run_dir_absent(tmp_path: Path) -> None:
+ never_created = tmp_path / "never" / "container-gateway.pid"
+ assert daemon.probe_pid_lock(never_created) == (False, None)
+
+
+def test_open_log_fd_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.log"
+ target.write_text("")
+ link = tmp_path / "container-gateway.log"
+ link.symlink_to(target)
+ with pytest.raises(SystemExit) as exc:
+ cli._open_log_fd(link)
+ assert exc.value.code == 2
+
+
+# --------------------- D2: acquire_pid_lock never blanks a live pid file
+
+
+def test_acquire_pid_lock_does_not_blank_a_live_daemons_pid_file(tmp_path: Path) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ os.ftruncate(fd, 0)
+ os.lseek(fd, 0, 0)
+ os.write(fd, b"4242\n")
+ os.fsync(fd)
+ second = daemon.acquire_pid_lock(pid_file)
+ assert second is None
+ assert pid_file.read_text() == "4242\n"
+ finally:
+ os.close(fd)
+
+
+# ------------------------------------- D1: status/stop bypassed check_run_dir
+
+
+def test_pid_file_is_trustworthy_none_when_missing(tmp_path: Path) -> None:
+ assert daemon.pid_file_is_trustworthy(tmp_path / "container-gateway.pid") is None
+
+
+def test_pid_file_is_trustworthy_true_for_a_lock_created_file(tmp_path: Path) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ assert daemon.pid_file_is_trustworthy(pid_file) is True
+ finally:
+ os.close(fd)
+
+
+def test_pid_file_is_trustworthy_false_for_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.pid"
+ target.write_text("4242\n")
+ target.chmod(0o600)
+ link = tmp_path / "container-gateway.pid"
+ link.symlink_to(target)
+ assert daemon.pid_file_is_trustworthy(link) is False
+
+
+def test_pid_file_is_trustworthy_false_for_wrong_mode(tmp_path: Path) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ pid_file.write_text("4242\n")
+ pid_file.chmod(0o644)
+ assert daemon.pid_file_is_trustworthy(pid_file) is False
+
+
+def test_cli_status_refuses_symlinked_run_dir(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ magpie_local = project_root / ".apache-magpie-local"
+ magpie_local.mkdir(parents=True, mode=0o700)
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (magpie_local / "run").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ cli.cmd_status(_ns(project_root, magpie_local / "run"))
+ assert exc.value.code == 2
+
+
+def test_cli_stop_refuses_symlinked_run_dir_without_signalling(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ project_root = tmp_path / "proj"
+ magpie_local = project_root / ".apache-magpie-local"
+ magpie_local.mkdir(parents=True, mode=0o700)
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (magpie_local / "run").symlink_to(evil)
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ with pytest.raises(SystemExit) as exc:
+ cli.cmd_stop(_ns(project_root, magpie_local / "run"))
+ assert exc.value.code == 2
+ assert calls == []
+
+
+def test_cli_stop_refuses_pid_file_with_wrong_mode(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ pid_file.write_text("4242\n")
+ pid_file.chmod(0o644)
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ with pytest.raises(SystemExit) as exc:
+ cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert exc.value.code == 2
+ assert calls == []
+
+
+def test_cli_status_treats_wrong_mode_pid_file_as_not_running(
+ tmp_path: Path, short_run_dir: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ pid_file.write_text("4242\n")
+ pid_file.chmod(0o644)
+ rc = cli.cmd_status(_ns(tmp_path, short_run_dir))
+ out = json.loads(capsys.readouterr().out)
+ assert rc == 3
+ assert out["running"] is False
+ # Untrustworthy content is left alone, not deleted, by `status`.
+ assert pid_file.exists()
+
+
+# -------------------------------- D4: stop verifies the signalled process
+
+
+def test_cli_stop_refuses_when_process_does_not_look_like_gateway(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ monkeypatch.setattr("container_gateway.backends.default_runner", lambda argv: "bash -c sleep 100")
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+def test_cli_stop_refuses_a_process_that_merely_mentions_the_module_name(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """An editor opened on a file named ``container_gateway.py`` is not the gateway.
+
+ A substring check on the ``ps`` line would wrongly treat this as a
+ match; the argv-shape check must not.
+ """
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ monkeypatch.setattr(
+ "container_gateway.backends.default_runner", lambda argv: "vim container_gateway.py"
+ )
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+def test_cli_stop_checks_only_the_first_line_of_ps_output(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A gateway-shaped second line must not rescue a non-gateway first line."""
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ monkeypatch.setattr(
+ "container_gateway.backends.default_runner",
+ lambda argv: "bash -c sleep 100\npython3 -m container_gateway serve --project /x",
+ )
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+def test_cli_stop_signals_when_process_is_the_console_script(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The installed ``container-gateway`` console script is also recognised, not just ``python -m``."""
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ our_pid = os.getpid()
+ calls: list[tuple[int, int]] = []
+ terminated = False
+
+ def fake_kill(pid: int, sig: int) -> None:
+ nonlocal terminated
+ calls.append((pid, sig))
+ if sig == signal.SIGTERM:
+ terminated = True
+ os.close(fd) # simulate the daemon exiting: release the flock
+ elif terminated:
+ raise ProcessLookupError
+
+ monkeypatch.setattr(os, "kill", fake_kill)
+ monkeypatch.setattr(
+ "container_gateway.backends.default_runner",
+ lambda argv: "/usr/local/bin/container-gateway serve --project /x",
+ )
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert rc == 0
+ assert (our_pid, signal.SIGTERM) in calls
+
+
+@pytest.mark.parametrize(
+ "command_line",
+ [
+ "python3 -u -m container_gateway serve --project /x",
+ "uv run python -m container_gateway serve --project /x",
+ ],
+)
+def test_cli_stop_signals_a_python_dash_m_invocation_with_extra_argv(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch, command_line: str
+) -> None:
+ """Interpreter flags (``-u``) and a runner prefix (``uv run``) do not defeat the argv-shape match."""
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
Review Comment:
## CodeQL / File is not always closed
File is opened but is not closed.
[Show more details](https://github.com/apache/magpie/security/code-scanning/74)
##########
tools/container-gateway/tests/test_daemon.py:
##########
@@ -0,0 +1,1013 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Daemon plumbing: paths, guards, idle exit, status and stop.
+
+Threat model exercised throughout this file: the daemon runs OUTSIDE the
+sandbox with the operator's own privileges, while the sandboxed agent
+can create, delete and symlink anything under the project tree,
+including ``.apache-magpie-local/run/``. Every guard test below plants
+exactly the kind of hostile filesystem state that threat model implies
+and checks the guard refuses it -- no bind needed for any of them.
+
+No ``pytest-asyncio`` in the ``magpie-dev`` dependency group, so each
+async scenario is a plain ``def`` test driving its coroutine through the
+``run()`` helper, exactly as ``test_http.py`` and ``test_relay.py`` do.
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import json
+import os
+import shutil
+import signal
+import subprocess
+import sys
+import tempfile
+from collections.abc import Coroutine, Iterator
+from pathlib import Path
+from typing import Any, TypeVar
+
+import pytest
+
+from container_gateway import __main__ as cli
+from container_gateway import daemon
+from container_gateway.backends import Backend
+
+from .fakebackend import FakeBackend
+
+SRC = Path(__file__).resolve().parents[1] / "src"
+
+_T = TypeVar("_T")
+
+
+def run(coro: Coroutine[Any, Any, _T]) -> _T:
+ """Drive a coroutine to completion without pytest-asyncio."""
+ return asyncio.run(coro)
+
+
+def _ns(project: Path, run_dir: Path, **extra: Any) -> argparse.Namespace:
+ """A minimal argparse.Namespace for calling cmd_serve/cmd_stop/cmd_status directly."""
+ base = {"project": project, "run_dir": run_dir, "pid_file": None}
+ base.update(extra)
+ return argparse.Namespace(**base)
+
+
+@pytest.fixture
+def short_run_dir() -> Iterator[Path]:
+ """A run directory short enough to hold a unix-socket path.
+
+ ``pytest``'s own ``tmp_path`` fixture nests under
+ ``pytest-of-<user>/pytest-<n>/<test-name>/`` inside ``$TMPDIR``, which
+ in this sandboxed dev environment is already long enough on its own
+ to blow the ~103-byte ``sun_path`` limit before ``run_dir`` even adds
+ ``podman.sock``. ``tempfile.mkdtemp()`` sits directly under
+ ``$TMPDIR`` with none of that nesting, so it stays short everywhere
+ ``tmp_path`` might not. It is also already 0700 and owned by us, so
+ it satisfies ``check_run_dir``'s "custom run-dir" branch as-is.
+ """
+ d = Path(tempfile.mkdtemp(prefix="cg-"))
+ try:
+ yield d
+ finally:
+ shutil.rmtree(d, ignore_errors=True)
+
+
+class _RealSocketBackend:
+ """A ``FakeBackend`` served over a real filesystem unix socket.
+
+ ``tests/fakebackend.FakeBackend`` only ever hands out in-process
+ ``socket.socketpair()`` connections (the sandbox refuses ``bind()``,
+ so it never listens on a path) -- but ``daemon.run()`` needs a real
+ socket path to hand to ``unix_connector`` for a ``Backend``. This
+ thin wrapper does the one real bind these daemon tests need, so it
+ can hit the same ``PermissionError`` the sandbox raises and skip
+ exactly like every other bind-touching test in this suite.
+ """
+
+ def __init__(self, socket_path: Path) -> None:
+ self.socket = socket_path
+ self._fake = FakeBackend()
+ self._server: asyncio.AbstractServer | None = None
+
+ async def start(self) -> None:
+ self._server = await asyncio.start_unix_server(self._fake._handle, path=str(self.socket))
+
+ async def stop(self) -> None:
+ if self._server is not None:
+ self._server.close()
+ await self._server.wait_closed()
+
+
+# --------------------------------------------------------------- paths
+
+
+def test_paths_and_socket_length(tmp_path: Path) -> None:
+ p = daemon.paths(tmp_path)
+ assert p["podman"].name == "podman.sock" and p["docker"].name == "docker.sock"
+ # A literal short path, not tmp_path: with TMPDIR unset, tmp_path's
+ # pytest-of-<user>/pytest-<n>/<test-name>/ nesting is already long
+ # enough to exceed the ~103-byte sun_path limit on its own, and
+ # check_socket_path only measures byte length.
+ daemon.check_socket_path(Path("/tmp/ok.sock"))
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_socket_path(Path("/" + "x" * 120 + "/podman.sock"))
+ assert exc.value.code == 2
+
+
+# ------------------------------------------------ C2: run dir / symlinks
+
+
+def test_check_run_dir_default_layout_creates_both_dirs_0700(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ run_dir = project_root / ".apache-magpie-local" / "run"
+ daemon.check_run_dir(run_dir, project_root)
+ assert (project_root / ".apache-magpie-local").stat().st_mode & 0o777 == 0o700
+ assert run_dir.stat().st_mode & 0o777 == 0o700
+
+
+def test_check_run_dir_refuses_world_writable_existing_dir(tmp_path: Path) -> None:
+ project_root = tmp_path
+ run_dir = tmp_path / "custom-run"
+ daemon.check_run_dir(run_dir, project_root)
+ assert run_dir.stat().st_mode & 0o777 == 0o700
+ run_dir.chmod(0o777)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(run_dir, project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_run(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ magpie_local = project_root / ".apache-magpie-local"
+ magpie_local.mkdir(parents=True, mode=0o700)
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (magpie_local / "run").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(magpie_local / "run", project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_apache_magpie_local(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (project_root / ".apache-magpie-local").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(project_root / ".apache-magpie-local" / "run", project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_custom_run_dir(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ custom = tmp_path / "custom-run"
+ custom.symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(custom, project_root)
+ assert exc.value.code == 2
+
+
+# ------------------------------------------- D5: missing ancestors refuse
+
+
+def test_check_run_dir_refuses_missing_project_root(tmp_path: Path) -> None:
+ missing_root = tmp_path / "does-not-exist"
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(missing_root / ".apache-magpie-local" / "run", missing_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_missing_custom_run_dir_parent(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ missing_parent_run_dir = tmp_path / "does-not-exist" / "run"
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(missing_parent_run_dir, project_root)
+ assert exc.value.code == 2
+
+
+def test_validate_run_dir_false_when_project_root_missing(tmp_path: Path) -> None:
+ missing_root = tmp_path / "does-not-exist"
+ assert daemon.validate_run_dir(missing_root / ".apache-magpie-local" / "run", missing_root) is False
+
+
+def test_validate_run_dir_false_when_custom_parent_missing(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ missing_parent_run_dir = tmp_path / "does-not-exist" / "run"
+ assert daemon.validate_run_dir(missing_parent_run_dir, project_root) is False
+
+
+# --------------------------------------- D6: lstat-then-mkdir race safety
+
+
+def test_ensure_owned_private_dir_handles_mkdir_race_with_planted_symlink(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ target = tmp_path / "custom-run"
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ real_mkdir = Path.mkdir
+
+ def racy_mkdir(self: Path, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None:
+ if self == target:
+ target.symlink_to(evil) # someone (or something) won the race and planted a symlink
+ raise FileExistsError(f"[Errno 17] File exists: '{target}'")
+ real_mkdir(self, mode, parents=parents, exist_ok=exist_ok)
+
+ monkeypatch.setattr(Path, "mkdir", racy_mkdir)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(target, tmp_path)
+ assert exc.value.code == 2
+
+
+# --------------------------------------------------- C2: socket guards
+
+
+def test_check_socket_type_refuses_non_socket(tmp_path: Path) -> None:
+ p = tmp_path / "podman.sock"
+ p.write_text("not a socket")
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_socket_type(p)
+ assert exc.value.code == 2
+
+
+def test_check_socket_type_allows_missing_path(tmp_path: Path) -> None:
+ daemon.check_socket_type(tmp_path / "missing.sock") # nothing there yet: fine
+
+
+# ------------------------------------------------------ C2: pid / log fd
+
+
+def test_acquire_pid_lock_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.pid"
+ target.write_text("")
+ link = tmp_path / "container-gateway.pid"
+ link.symlink_to(target)
+ with pytest.raises(SystemExit) as exc:
+ daemon.acquire_pid_lock(link)
+ assert exc.value.code == 2
+
+
+def test_probe_pid_lock_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.pid"
+ target.write_text("")
+ link = tmp_path / "container-gateway.pid"
+ link.symlink_to(target)
+ with pytest.raises(SystemExit) as exc:
+ daemon.probe_pid_lock(link)
+ assert exc.value.code == 2
+
+
+def test_probe_pid_lock_not_running_when_run_dir_absent(tmp_path: Path) -> None:
+ never_created = tmp_path / "never" / "container-gateway.pid"
+ assert daemon.probe_pid_lock(never_created) == (False, None)
+
+
+def test_open_log_fd_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.log"
+ target.write_text("")
+ link = tmp_path / "container-gateway.log"
+ link.symlink_to(target)
+ with pytest.raises(SystemExit) as exc:
+ cli._open_log_fd(link)
+ assert exc.value.code == 2
+
+
+# --------------------- D2: acquire_pid_lock never blanks a live pid file
+
+
+def test_acquire_pid_lock_does_not_blank_a_live_daemons_pid_file(tmp_path: Path) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ os.ftruncate(fd, 0)
+ os.lseek(fd, 0, 0)
+ os.write(fd, b"4242\n")
+ os.fsync(fd)
+ second = daemon.acquire_pid_lock(pid_file)
Review Comment:
## CodeQL / File is not always closed
File is opened but is not closed.
[Show more details](https://github.com/apache/magpie/security/code-scanning/72)
##########
tools/container-gateway/tests/test_daemon.py:
##########
@@ -0,0 +1,1013 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Daemon plumbing: paths, guards, idle exit, status and stop.
+
+Threat model exercised throughout this file: the daemon runs OUTSIDE the
+sandbox with the operator's own privileges, while the sandboxed agent
+can create, delete and symlink anything under the project tree,
+including ``.apache-magpie-local/run/``. Every guard test below plants
+exactly the kind of hostile filesystem state that threat model implies
+and checks the guard refuses it -- no bind needed for any of them.
+
+No ``pytest-asyncio`` in the ``magpie-dev`` dependency group, so each
+async scenario is a plain ``def`` test driving its coroutine through the
+``run()`` helper, exactly as ``test_http.py`` and ``test_relay.py`` do.
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import json
+import os
+import shutil
+import signal
+import subprocess
+import sys
+import tempfile
+from collections.abc import Coroutine, Iterator
+from pathlib import Path
+from typing import Any, TypeVar
+
+import pytest
+
+from container_gateway import __main__ as cli
+from container_gateway import daemon
+from container_gateway.backends import Backend
+
+from .fakebackend import FakeBackend
+
+SRC = Path(__file__).resolve().parents[1] / "src"
+
+_T = TypeVar("_T")
+
+
+def run(coro: Coroutine[Any, Any, _T]) -> _T:
+ """Drive a coroutine to completion without pytest-asyncio."""
+ return asyncio.run(coro)
+
+
+def _ns(project: Path, run_dir: Path, **extra: Any) -> argparse.Namespace:
+ """A minimal argparse.Namespace for calling cmd_serve/cmd_stop/cmd_status directly."""
+ base = {"project": project, "run_dir": run_dir, "pid_file": None}
+ base.update(extra)
+ return argparse.Namespace(**base)
+
+
+@pytest.fixture
+def short_run_dir() -> Iterator[Path]:
+ """A run directory short enough to hold a unix-socket path.
+
+ ``pytest``'s own ``tmp_path`` fixture nests under
+ ``pytest-of-<user>/pytest-<n>/<test-name>/`` inside ``$TMPDIR``, which
+ in this sandboxed dev environment is already long enough on its own
+ to blow the ~103-byte ``sun_path`` limit before ``run_dir`` even adds
+ ``podman.sock``. ``tempfile.mkdtemp()`` sits directly under
+ ``$TMPDIR`` with none of that nesting, so it stays short everywhere
+ ``tmp_path`` might not. It is also already 0700 and owned by us, so
+ it satisfies ``check_run_dir``'s "custom run-dir" branch as-is.
+ """
+ d = Path(tempfile.mkdtemp(prefix="cg-"))
+ try:
+ yield d
+ finally:
+ shutil.rmtree(d, ignore_errors=True)
+
+
+class _RealSocketBackend:
+ """A ``FakeBackend`` served over a real filesystem unix socket.
+
+ ``tests/fakebackend.FakeBackend`` only ever hands out in-process
+ ``socket.socketpair()`` connections (the sandbox refuses ``bind()``,
+ so it never listens on a path) -- but ``daemon.run()`` needs a real
+ socket path to hand to ``unix_connector`` for a ``Backend``. This
+ thin wrapper does the one real bind these daemon tests need, so it
+ can hit the same ``PermissionError`` the sandbox raises and skip
+ exactly like every other bind-touching test in this suite.
+ """
+
+ def __init__(self, socket_path: Path) -> None:
+ self.socket = socket_path
+ self._fake = FakeBackend()
+ self._server: asyncio.AbstractServer | None = None
+
+ async def start(self) -> None:
+ self._server = await asyncio.start_unix_server(self._fake._handle, path=str(self.socket))
+
+ async def stop(self) -> None:
+ if self._server is not None:
+ self._server.close()
+ await self._server.wait_closed()
+
+
+# --------------------------------------------------------------- paths
+
+
+def test_paths_and_socket_length(tmp_path: Path) -> None:
+ p = daemon.paths(tmp_path)
+ assert p["podman"].name == "podman.sock" and p["docker"].name == "docker.sock"
+ # A literal short path, not tmp_path: with TMPDIR unset, tmp_path's
+ # pytest-of-<user>/pytest-<n>/<test-name>/ nesting is already long
+ # enough to exceed the ~103-byte sun_path limit on its own, and
+ # check_socket_path only measures byte length.
+ daemon.check_socket_path(Path("/tmp/ok.sock"))
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_socket_path(Path("/" + "x" * 120 + "/podman.sock"))
+ assert exc.value.code == 2
+
+
+# ------------------------------------------------ C2: run dir / symlinks
+
+
+def test_check_run_dir_default_layout_creates_both_dirs_0700(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ run_dir = project_root / ".apache-magpie-local" / "run"
+ daemon.check_run_dir(run_dir, project_root)
+ assert (project_root / ".apache-magpie-local").stat().st_mode & 0o777 == 0o700
+ assert run_dir.stat().st_mode & 0o777 == 0o700
+
+
+def test_check_run_dir_refuses_world_writable_existing_dir(tmp_path: Path) -> None:
+ project_root = tmp_path
+ run_dir = tmp_path / "custom-run"
+ daemon.check_run_dir(run_dir, project_root)
+ assert run_dir.stat().st_mode & 0o777 == 0o700
+ run_dir.chmod(0o777)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(run_dir, project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_run(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ magpie_local = project_root / ".apache-magpie-local"
+ magpie_local.mkdir(parents=True, mode=0o700)
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (magpie_local / "run").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(magpie_local / "run", project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_apache_magpie_local(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (project_root / ".apache-magpie-local").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(project_root / ".apache-magpie-local" / "run", project_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_symlinked_custom_run_dir(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ custom = tmp_path / "custom-run"
+ custom.symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(custom, project_root)
+ assert exc.value.code == 2
+
+
+# ------------------------------------------- D5: missing ancestors refuse
+
+
+def test_check_run_dir_refuses_missing_project_root(tmp_path: Path) -> None:
+ missing_root = tmp_path / "does-not-exist"
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(missing_root / ".apache-magpie-local" / "run", missing_root)
+ assert exc.value.code == 2
+
+
+def test_check_run_dir_refuses_missing_custom_run_dir_parent(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ missing_parent_run_dir = tmp_path / "does-not-exist" / "run"
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(missing_parent_run_dir, project_root)
+ assert exc.value.code == 2
+
+
+def test_validate_run_dir_false_when_project_root_missing(tmp_path: Path) -> None:
+ missing_root = tmp_path / "does-not-exist"
+ assert daemon.validate_run_dir(missing_root / ".apache-magpie-local" / "run", missing_root) is False
+
+
+def test_validate_run_dir_false_when_custom_parent_missing(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ project_root.mkdir()
+ missing_parent_run_dir = tmp_path / "does-not-exist" / "run"
+ assert daemon.validate_run_dir(missing_parent_run_dir, project_root) is False
+
+
+# --------------------------------------- D6: lstat-then-mkdir race safety
+
+
+def test_ensure_owned_private_dir_handles_mkdir_race_with_planted_symlink(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ target = tmp_path / "custom-run"
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ real_mkdir = Path.mkdir
+
+ def racy_mkdir(self: Path, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None:
+ if self == target:
+ target.symlink_to(evil) # someone (or something) won the race and planted a symlink
+ raise FileExistsError(f"[Errno 17] File exists: '{target}'")
+ real_mkdir(self, mode, parents=parents, exist_ok=exist_ok)
+
+ monkeypatch.setattr(Path, "mkdir", racy_mkdir)
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_run_dir(target, tmp_path)
+ assert exc.value.code == 2
+
+
+# --------------------------------------------------- C2: socket guards
+
+
+def test_check_socket_type_refuses_non_socket(tmp_path: Path) -> None:
+ p = tmp_path / "podman.sock"
+ p.write_text("not a socket")
+ with pytest.raises(SystemExit) as exc:
+ daemon.check_socket_type(p)
+ assert exc.value.code == 2
+
+
+def test_check_socket_type_allows_missing_path(tmp_path: Path) -> None:
+ daemon.check_socket_type(tmp_path / "missing.sock") # nothing there yet: fine
+
+
+# ------------------------------------------------------ C2: pid / log fd
+
+
+def test_acquire_pid_lock_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.pid"
+ target.write_text("")
+ link = tmp_path / "container-gateway.pid"
+ link.symlink_to(target)
+ with pytest.raises(SystemExit) as exc:
+ daemon.acquire_pid_lock(link)
+ assert exc.value.code == 2
+
+
+def test_probe_pid_lock_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.pid"
+ target.write_text("")
+ link = tmp_path / "container-gateway.pid"
+ link.symlink_to(target)
+ with pytest.raises(SystemExit) as exc:
+ daemon.probe_pid_lock(link)
+ assert exc.value.code == 2
+
+
+def test_probe_pid_lock_not_running_when_run_dir_absent(tmp_path: Path) -> None:
+ never_created = tmp_path / "never" / "container-gateway.pid"
+ assert daemon.probe_pid_lock(never_created) == (False, None)
+
+
+def test_open_log_fd_refuses_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.log"
+ target.write_text("")
+ link = tmp_path / "container-gateway.log"
+ link.symlink_to(target)
+ with pytest.raises(SystemExit) as exc:
+ cli._open_log_fd(link)
+ assert exc.value.code == 2
+
+
+# --------------------- D2: acquire_pid_lock never blanks a live pid file
+
+
+def test_acquire_pid_lock_does_not_blank_a_live_daemons_pid_file(tmp_path: Path) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ os.ftruncate(fd, 0)
+ os.lseek(fd, 0, 0)
+ os.write(fd, b"4242\n")
+ os.fsync(fd)
+ second = daemon.acquire_pid_lock(pid_file)
+ assert second is None
+ assert pid_file.read_text() == "4242\n"
+ finally:
+ os.close(fd)
+
+
+# ------------------------------------- D1: status/stop bypassed check_run_dir
+
+
+def test_pid_file_is_trustworthy_none_when_missing(tmp_path: Path) -> None:
+ assert daemon.pid_file_is_trustworthy(tmp_path / "container-gateway.pid") is None
+
+
+def test_pid_file_is_trustworthy_true_for_a_lock_created_file(tmp_path: Path) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ assert daemon.pid_file_is_trustworthy(pid_file) is True
+ finally:
+ os.close(fd)
+
+
+def test_pid_file_is_trustworthy_false_for_symlink(tmp_path: Path) -> None:
+ target = tmp_path / "elsewhere.pid"
+ target.write_text("4242\n")
+ target.chmod(0o600)
+ link = tmp_path / "container-gateway.pid"
+ link.symlink_to(target)
+ assert daemon.pid_file_is_trustworthy(link) is False
+
+
+def test_pid_file_is_trustworthy_false_for_wrong_mode(tmp_path: Path) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ pid_file.write_text("4242\n")
+ pid_file.chmod(0o644)
+ assert daemon.pid_file_is_trustworthy(pid_file) is False
+
+
+def test_cli_status_refuses_symlinked_run_dir(tmp_path: Path) -> None:
+ project_root = tmp_path / "proj"
+ magpie_local = project_root / ".apache-magpie-local"
+ magpie_local.mkdir(parents=True, mode=0o700)
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (magpie_local / "run").symlink_to(evil)
+ with pytest.raises(SystemExit) as exc:
+ cli.cmd_status(_ns(project_root, magpie_local / "run"))
+ assert exc.value.code == 2
+
+
+def test_cli_stop_refuses_symlinked_run_dir_without_signalling(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ project_root = tmp_path / "proj"
+ magpie_local = project_root / ".apache-magpie-local"
+ magpie_local.mkdir(parents=True, mode=0o700)
+ evil = tmp_path / "evil"
+ evil.mkdir()
+ (magpie_local / "run").symlink_to(evil)
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ with pytest.raises(SystemExit) as exc:
+ cli.cmd_stop(_ns(project_root, magpie_local / "run"))
+ assert exc.value.code == 2
+ assert calls == []
+
+
+def test_cli_stop_refuses_pid_file_with_wrong_mode(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ pid_file.write_text("4242\n")
+ pid_file.chmod(0o644)
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ with pytest.raises(SystemExit) as exc:
+ cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert exc.value.code == 2
+ assert calls == []
+
+
+def test_cli_status_treats_wrong_mode_pid_file_as_not_running(
+ tmp_path: Path, short_run_dir: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ pid_file.write_text("4242\n")
+ pid_file.chmod(0o644)
+ rc = cli.cmd_status(_ns(tmp_path, short_run_dir))
+ out = json.loads(capsys.readouterr().out)
+ assert rc == 3
+ assert out["running"] is False
+ # Untrustworthy content is left alone, not deleted, by `status`.
+ assert pid_file.exists()
+
+
+# -------------------------------- D4: stop verifies the signalled process
+
+
+def test_cli_stop_refuses_when_process_does_not_look_like_gateway(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ monkeypatch.setattr("container_gateway.backends.default_runner", lambda argv: "bash -c sleep 100")
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+def test_cli_stop_refuses_a_process_that_merely_mentions_the_module_name(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """An editor opened on a file named ``container_gateway.py`` is not the gateway.
+
+ A substring check on the ``ps`` line would wrongly treat this as a
+ match; the argv-shape check must not.
+ """
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ monkeypatch.setattr(
+ "container_gateway.backends.default_runner", lambda argv: "vim container_gateway.py"
+ )
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+def test_cli_stop_checks_only_the_first_line_of_ps_output(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A gateway-shaped second line must not rescue a non-gateway first line."""
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ monkeypatch.setattr(
+ "container_gateway.backends.default_runner",
+ lambda argv: "bash -c sleep 100\npython3 -m container_gateway serve --project /x",
+ )
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+def test_cli_stop_signals_when_process_is_the_console_script(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The installed ``container-gateway`` console script is also recognised, not just ``python -m``."""
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ our_pid = os.getpid()
+ calls: list[tuple[int, int]] = []
+ terminated = False
+
+ def fake_kill(pid: int, sig: int) -> None:
+ nonlocal terminated
+ calls.append((pid, sig))
+ if sig == signal.SIGTERM:
+ terminated = True
+ os.close(fd) # simulate the daemon exiting: release the flock
+ elif terminated:
+ raise ProcessLookupError
+
+ monkeypatch.setattr(os, "kill", fake_kill)
+ monkeypatch.setattr(
+ "container_gateway.backends.default_runner",
+ lambda argv: "/usr/local/bin/container-gateway serve --project /x",
+ )
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert rc == 0
+ assert (our_pid, signal.SIGTERM) in calls
+
+
+@pytest.mark.parametrize(
+ "command_line",
+ [
+ "python3 -u -m container_gateway serve --project /x",
+ "uv run python -m container_gateway serve --project /x",
+ ],
+)
+def test_cli_stop_signals_a_python_dash_m_invocation_with_extra_argv(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch, command_line: str
+) -> None:
+ """Interpreter flags (``-u``) and a runner prefix (``uv run``) do not defeat the argv-shape match."""
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ our_pid = os.getpid()
+ calls: list[tuple[int, int]] = []
+ terminated = False
+
+ def fake_kill(pid: int, sig: int) -> None:
+ nonlocal terminated
+ calls.append((pid, sig))
+ if sig == signal.SIGTERM:
+ terminated = True
+ os.close(fd) # simulate the daemon exiting: release the flock
+ elif terminated:
+ raise ProcessLookupError
+
+ monkeypatch.setattr(os, "kill", fake_kill)
+ monkeypatch.setattr("container_gateway.backends.default_runner", lambda argv: command_line)
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert rc == 0
+ assert (our_pid, signal.SIGTERM) in calls
+
+
+def test_cli_stop_refuses_when_ps_is_unavailable(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ monkeypatch.setattr("container_gateway.backends.default_runner", lambda argv: None)
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+# --------------------------------------------------------------- C1: pid
+
+
+@pytest.mark.parametrize("content", ["-1", "0", "1", "abc", "12 34", "99999999999", ""])
+def test_read_pid_rejects_unsafe_content(tmp_path: Path, content: str) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ pid_file.write_text(content)
+ assert daemon.read_pid(pid_file) is None
+
+
+def test_read_pid_accepts_a_real_pid(tmp_path: Path) -> None:
+ pid_file = tmp_path / "container-gateway.pid"
+ pid_file.write_text("42\n")
+ assert daemon.read_pid(pid_file) == 42
+
+
+def test_pid_alive_false_for_pid_le_1() -> None:
+ assert daemon.pid_alive(0) is False
+ assert daemon.pid_alive(1) is False
+ assert daemon.pid_alive(-1) is False
+
+
+@pytest.mark.parametrize("content", ["-1", "0", "1", "abc", "12 34"])
+def test_cli_stop_with_unsafe_pid_file_does_not_signal(
+ tmp_path: Path, short_run_dir: Path, content: str, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ pid_file.write_text(content)
+ pid_file.chmod(0o600) # a trustworthy *file*; the *content* is what's unsafe here
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 0
+
+
+def test_cli_stop_does_not_signal_when_lock_held_but_pid_content_poisoned(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A live, lock-holding instance whose pid-file *content* was overwritten afterwards.
+
+ ``stop`` must refuse to guess: something is clearly running (the
+ lock says so), but nothing safe to signal can be read back out of
+ the file.
+ """
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ os.ftruncate(fd, 0)
+ os.lseek(fd, 0, 0)
+ os.write(fd, b"-1\n")
+ calls: list[tuple[int, int]] = []
+ monkeypatch.setattr(os, "kill", lambda pid, sig: calls.append((pid, sig)))
+ rc = cli.cmd_stop(_ns(tmp_path, short_run_dir))
+ assert calls == []
+ assert rc == 1
+ finally:
+ os.close(fd)
+
+
+# --------------------------------------------- I3+I4: flock single instance
+
+
+def test_cli_serve_short_circuits_when_lock_already_held(tmp_path: Path, short_run_dir: Path) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ ns = _ns(
+ tmp_path,
+ short_run_dir,
+ daemon=False,
+ backend=None,
+ egress="off",
+ egress_port=8899,
+ egress_host=None,
+ extra_bind_root=None,
+ idle_timeout=5.0,
+ backend_timeout=60.0,
+ log_level="INFO",
+ )
+ assert cli.cmd_serve(ns) == 0
+ assert not (short_run_dir / "podman.sock").exists()
+ assert not (short_run_dir / "docker.sock").exists()
+ finally:
+ os.close(fd)
+
+
+def test_cli_status_reports_running_when_lock_held(
+ tmp_path: Path, short_run_dir: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
+ assert fd is not None
+ try:
+ rc = cli.cmd_status(_ns(tmp_path, short_run_dir))
+ out = json.loads(capsys.readouterr().out)
+ finally:
+ os.close(fd)
+ assert rc == 0
+ assert out["running"] is True
+ assert out["pid"] == os.getpid()
+ assert out["serving"] == [] # no sockets actually bound in this test
+
+
+def test_cli_status_removes_stale_pid_file_when_no_lock_held(
+ tmp_path: Path, short_run_dir: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ pid_file.write_text("424242\n") # a stale pid; nobody holds its lock
+ pid_file.chmod(0o600) # a trustworthy, well-formed pid file -- just stale
+ rc = cli.cmd_status(_ns(tmp_path, short_run_dir))
+ out = json.loads(capsys.readouterr().out)
+ assert rc == 3
+ assert out["running"] is False
+ assert out["pid"] is None
+ assert not pid_file.exists()
+
+
+def test_cli_stop_signals_the_pid_and_reports_stopped(
+ tmp_path: Path, short_run_dir: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pid_file = short_run_dir / "container-gateway.pid"
+ fd = daemon.acquire_pid_lock(pid_file)
Review Comment:
## CodeQL / File is not always closed
File is opened but is not closed.
[Show more details](https://github.com/apache/magpie/security/code-scanning/75)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@magpie.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org