Files
headquarter/apps/api/tests/unit/test_terminal_session.py
T
Developer 9f720930ea fix: run tool terminal sessions as container user instead of root
- Remove compose-level user: 0:0 override from manifest_compiler.py so the
  entrypoint can start as root, fix mount ownership, and drop privileges to
  the container user internally.
- Add get_manifest_container_user() helper to resolve the manifest-declared
  container user (with uid:gid fallback).
- Pass container user through TerminalSession, TerminalManager, and the
  terminal WebSocket handler so docker exec is invoked with --user <user>.
- Update and add unit tests for the manifest compiler and terminal session.
- Record the additional root-user fix in the fix-pi-container-mount-permissions
  OpenSpec change/tasks.

Quality gates: pytest tests/unit/ (226 passed), pytest tests/services/test_terminal_manager_multi.py (7 passed), ruff check on changed files (clean), mypy on changed files (clean)
2026-06-17 20:51:46 +00:00

65 lines
1.9 KiB
Python

"""Unit tests for TerminalSession docker exec invocation."""
import uuid
from unittest.mock import AsyncMock, patch
import pytest
from src.services.terminal.terminal_session import TerminalSession
@pytest.mark.unit
@pytest.mark.asyncio
async def test_start_passes_container_user_to_docker_exec() -> None:
"""When container_user is set, docker exec receives --user <user>."""
session = TerminalSession(
session_id=str(uuid.uuid4()),
instance_id=uuid.uuid4(),
container_id="container-123",
container_user="dev",
)
with patch(
"src.services.terminal.terminal_session.pty.openpty",
return_value=(1, 2),
):
with patch(
"src.services.terminal.terminal_session.asyncio.create_subprocess_exec",
new=AsyncMock(),
) as mock_exec:
with patch("src.services.terminal.terminal_session.os.close"):
await session.start()
args, _kwargs = mock_exec.call_args
assert "docker" in args
assert "exec" in args
assert "--user" in args
user_index = args.index("--user")
assert args[user_index + 1] == "dev"
assert "container-123" in args
@pytest.mark.unit
@pytest.mark.asyncio
async def test_start_omits_user_when_not_configured() -> None:
"""Without container_user, docker exec does not receive --user."""
session = TerminalSession(
session_id=str(uuid.uuid4()),
instance_id=uuid.uuid4(),
container_id="container-123",
)
with patch(
"src.services.terminal.terminal_session.pty.openpty",
return_value=(1, 2),
):
with patch(
"src.services.terminal.terminal_session.asyncio.create_subprocess_exec",
new=AsyncMock(),
) as mock_exec:
with patch("src.services.terminal.terminal_session.os.close"):
await session.start()
args, _kwargs = mock_exec.call_args
assert "--user" not in args