Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

7.4 KB
Raw Blame
"""Secret templates cross the public Python API and the HTTP boundary."""

import importlib.util
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

import pytest

import boxlite

pytestmark = pytest.mark.skipif(
    importlib.util.find_spec("boxlite.boxlite") is None,
    reason="native extension not built",
)


_UNSET = object()


def secret_with_headers(headers=_UNSET):
    kwargs = {"name": "bot", "value": "token", "hosts": ["api.example.com"]}
    if headers is not _UNSET:
        return boxlite.Secret(**kwargs, headers=headers)
    return boxlite.Secret(**kwargs)


@pytest.fixture
def secret_rest_server():
    requests = []
    boxes = {}

    class Handler(BaseHTTPRequestHandler):
        def reply(self, status, body):
            payload = json.dumps(body).encode()
            self.send_response(status)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(payload)))
            self.end_headers()
            self.wfile.write(payload)

        def do_GET(self):
            requests.append((self.command, self.path, None))
            if self.path in boxes:
                self.reply(200, boxes[self.path])
            else:
                self.reply(404, {"message": "box not found"})

        def do_POST(self):
            body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
            requests.append((self.command, self.path, body))
            if self.headers.get("Content-Type") != "application/json":
                self.reply(415, {"message": "expected JSON"})
                return
            info = {
                "box_id": "secret-test",
                "name": body.get("name"),
                "status": "configured",
                "created_at": "2026-01-01T00:00:00Z",
                "updated_at": "2026-01-01T00:00:00Z",
                "pid": None,
                "image": "alpine:latest",
                "cpus": 1,
                "memory_mib": 512,
                "privileged": False,
            }
            if info["name"]:
                boxes[f"/v1/boxes/{info['name']}"] = info
            self.reply(201, info)

        def log_message(self, *args):
            pass

    server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()
    runtime = boxlite.Boxlite.rest(
        boxlite.BoxliteRestOptions(url=f"http://127.0.0.1:{server.server_port}")
    )
    try:
        yield runtime, requests
    finally:
        runtime.close()
        server.shutdown()
        server.server_close()
        thread.join()


@pytest.mark.asyncio
async def test_secret_headers_rest_request(secret_rest_server):
    runtime, requests = secret_rest_server
    templates = {"Authorization": "Bot {value}", "X-Key": "{value}"}
    for headers in [{"Authorization": "Bearer {value}"}, templates]:
        await runtime.create(
            boxlite.BoxOptions(
                image="alpine:latest", secrets=[secret_with_headers(headers)]
            )
        )
    assert [(method, path) for method, path, _ in requests] == [
        ("POST", "/v1/boxes")
    ] * 2
    before, after = [body for _, _, body in requests]
    assert before["secrets"][0].pop("headers") == {"Authorization": "Bearer {value}"}
    assert after["secrets"][0].pop("headers", None) == templates
    assert before == after

    await runtime.create(boxlite.BoxOptions(image="alpine:latest"))
    assert "secrets" not in requests[-1][2]

    ref = {"secret": "openai"}
    mixed = boxlite.BoxOptions(
        image="alpine:latest", secrets=[ref, secret_with_headers(templates)]
    )
    assert mixed.secrets[0] == ref
    await runtime.create(mixed)
    assert requests[-1][2]["secrets"] == [
        ref,
        {**after["secrets"][0], "headers": templates},
    ]

    await runtime.create(boxlite.BoxOptions(image="alpine:latest", secrets=[ref]))
    assert requests[-1][2]["secrets"] == [ref]
    with pytest.raises(ValueError, match="only"):
        boxlite.BoxOptions(secrets=[{"secret": "openai", "value": "override"}])


@pytest.mark.asyncio
async def test_get_or_create_named_secret_checks_existing_box(secret_rest_server):
    runtime, requests = secret_rest_server
    options = boxlite.BoxOptions(image="alpine:latest")
    options.secrets = [{"secret": "shared"}]
    box, created = await runtime.get_or_create(options, name="worker")
    assert created and box.id == "secret-test"
    assert len(requests) == 2
    assert requests[0] == ("GET", "/v1/boxes/worker", None)
    method, path, body = requests[1]
    assert (method, path, body["name"], body["secrets"]) == (
        "POST",
        "/v1/boxes",
        "worker",
        [{"secret": "shared"}],
    )
    requests.clear()

    with pytest.raises(
        boxlite.errors.UnsupportedError, match="cannot verify named secret bindings"
    ):
        await runtime.get_or_create(options, name="worker")
    assert requests == [("GET", "/v1/boxes/worker", None)]

    options.secrets = []
    box, created = await runtime.get_or_create(options, name="worker")
    assert not created and box.id == "secret-test"
    assert requests == [("GET", "/v1/boxes/worker", None)] * 2


@pytest.mark.asyncio
async def test_mixed_secrets_share_the_64_entry_limit(secret_rest_server):
    runtime, requests = secret_rest_server
    refs = [{"secret": f"shared_{i}"} for i in range(63)]
    inline = secret_with_headers({"Authorization": "Bearer {value}"})
    options = boxlite.BoxOptions(image="alpine:latest", secrets=[inline, *refs])
    await runtime.create(options)
    assert len(requests) == 1
    sent = requests[0][2]["secrets"]
    assert sent[0]["name"] == "bot" and sent[1:] == refs

    options.secrets = [inline, *refs, {"secret": "one_too_many"}]
    with pytest.raises(boxlite.errors.InvalidArgumentError, match="at most 64"):
        await runtime.create(options)
    assert len(requests) == 1


@pytest.mark.parametrize(
    "bad, error",
    [({"secret": 42}, TypeError), ({"wrong": "key"}, ValueError), (None, TypeError)],
)
def test_secret_assignment_rejects_invalid_entries_atomically(bad, error):
    options = boxlite.BoxOptions(secrets=[{"secret": "original"}])
    with pytest.raises(error):
        options.secrets = [{"secret": "replacement"}, bad]
    assert options.secrets == [{"secret": "original"}]


@pytest.mark.asyncio
@pytest.mark.parametrize("headers", [_UNSET, None, {}, "", {"Bad Header": "{value}"}])
async def test_secret_headers_reject_invalid_input(tmp_path, headers):
    rootfs = tmp_path / "rootfs"
    rootfs.mkdir()
    runtime = boxlite.Boxlite(boxlite.Options(home_dir=str(tmp_path / "runtime")))
    try:
        with pytest.raises(Exception, match="header"):
            await runtime.create(
                boxlite.BoxOptions(
                    rootfs_path=str(rootfs), secrets=[secret_with_headers(headers)]
                )
            )
    finally:
        runtime.close()


@pytest.mark.asyncio
@pytest.mark.parametrize("method", ["create", "get_or_create"])
async def test_named_secret_requires_hosted_runtime(tmp_path, method):
    runtime = boxlite.Boxlite(boxlite.Options(home_dir=str(tmp_path / "runtime")))
    try:
        with pytest.raises(
            boxlite.errors.UnsupportedError,
            match="Named secrets require a hosted runtime",
        ):
            await getattr(runtime, method)(
                boxlite.BoxOptions(image="alpine", secrets=[{"secret": "shared"}])
            )
    finally:
        runtime.close()