The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
"""Mixed Box secrets through a real Runner, a verdict-only HTTPS upstream and PostgreSQL."""
import asyncio
import hashlib
import os
import secrets
import subprocess
from contextlib import AsyncExitStack
from pathlib import Path
from urllib.parse import urlencode, urlsplit
import pytest
from conftest import drain
from e2e_auth import discover_path_prefix, load_profile, request_json
from network_fixtures import prepare, service_box, state
from preview import access, require
import boxlite
async def verify(box, uri, policies, original_values):
execution = await box.exec("env", [], None)
stdout, stderr = await drain(execution)
require((await execution.wait()).exit_code == 0, "guest environment unavailable")
require(
all(value not in stdout + stderr for value in original_values),
"guest environment contains an original value",
)
for path, name in policies:
placeholder = f"<BOXLITE_SECRET:{name}>"
require(
f"BOXLITE_SECRET_{name.upper()}={placeholder}" in stdout.splitlines(),
"secret placeholder missing in guest",
)
probe = await box.exec(
"curl",
[
"--silent",
"--show-error",
"--max-time",
"20",
"--output",
"/dev/null",
"--write-out",
"%{http_code}",
"--header",
"X-BoxLite-Skip-Preview-Warning: true",
"--header",
f"X-Test-{path}: dummy",
f"{uri.rstrip('/')}/{path}",
],
None,
)
output, _ = await drain(probe)
require(
(await probe.wait()).exit_code == 0 and output == "204",
f"upstream rejected the {path} policy",
)
def private_count(box_id, service):
proc = subprocess.run(
["psql", "-XqAt", "-v", "ON_ERROR_STOP=1", "-v", f"box={box_id}"],
input="SELECT count(*) FROM secret WHERE scope='box' AND box_id=:'box';",
env={**os.environ, "PGSERVICE": service},
check=False,
capture_output=True,
text=True,
timeout=10,
)
require(proc.returncode == 0, "Secret Server database check failed")
return int(proc.stdout.strip())
def listed_secret(secret_id):
query = {"pageSize": 100}
while True:
status, page = request_json("GET", "/v1/secrets?" + urlencode(query))
require(status == 200, "organization secret listing failed")
for item in page["secrets"]:
require(
set(item) == {"id", "name", "hosts", "headers", "placeholder"},
"unexpected organization secret list fields",
)
if item["id"] == secret_id:
return item
if "next_page_token" not in page:
return None
query["pageToken"] = page["next_page_token"]
async def delete_after_destruction(path):
async with asyncio.timeout(180):
while True:
status, _ = request_json("DELETE", path)
if status == 204:
return
require(status == 409, "organization secret deletion failed")
await asyncio.sleep(1)
@pytest.mark.e2e
async def test_named_secret_lifecycle(rt, image, e2e_auth):
service = os.getenv("BOXLITE_E2E_SECRET_PGSERVICE")
if not service:
pytest.skip(
"requires a libpq service for the disposable Secret Server database"
)
foreign = load_profile(os.environ["BOXLITE_E2E_FOREIGN_PROFILE"])
require(
foreign["url"].rstrip("/") == e2e_auth.url.rstrip("/"),
"profiles must use the same API",
)
foreign_prefix = discover_path_prefix(e2e_auth.url, foreign["api_key"])
require(
foreign_prefix
and e2e_auth.path_prefix
and foreign_prefix != e2e_auth.path_prefix,
"profiles must belong to different organizations",
)
shared_name = "shared_" + secrets.token_hex(6)
shared, private = secrets.token_hex(32), secrets.token_hex(32)
upstream = (Path(__file__).parents[1] / "fixtures/secret_verdict.py").read_text()
digests = [hashlib.sha256(v.encode()).hexdigest() for v in (shared, private)]
async with service_box(
rt, image, entrypoint=["python3", "-u", "-c", upstream, *digests]
) as (server, _):
tunnel = await prepare(server)
uri = tunnel.uri()
host = urlsplit(uri).hostname
require(
urlsplit(uri).scheme == "https" and host, "verdict upstream requires HTTPS"
)
async with asyncio.timeout(45):
while True:
control = await access(
uri.rstrip("/") + "/shared",
headers={"X-BoxLite-Skip-Preview-Warning": "true"},
)
if control.status not in (502, 503):
break
await asyncio.sleep(0.2)
require(
control.status == 403 and not control.body,
"verdict upstream must reject a request with no credential",
)
status, identity = request_json(
"POST",
"/v1/secrets",
{
"name": shared_name,
"value": shared,
"hosts": [host],
"headers": {"X-Test-Shared": "{value}"},
},
)
require(
status == 201
and set(identity) == {"id", "name"}
and identity["name"] == shared_name,
"organization secret creation failed",
)
ref = {"secret": shared_name}
inline = boxlite.Secret(
"private", private, [host], headers={"X-Test-Private": "{value}"}
)
other = boxlite.Boxlite.rest(
boxlite.BoxliteRestOptions(
url=foreign["url"],
credential=boxlite.ApiKeyCredential(foreign["api_key"]),
path_prefix=foreign_prefix,
)
)
path = "/v1/secrets/" + identity["id"]
async with AsyncExitStack() as boxes:
boxes.push_async_callback(delete_after_destruction, path)
require(
listed_secret(identity["id"])
== {
**identity,
"hosts": [host],
"headers": {"X-Test-Shared": "{value}"},
"placeholder": f"<BOXLITE_SECRET:{shared_name}>",
},
"listed organization secret policy differs from the saved policy",
)
try:
try:
unexpected = await other.create(
boxlite.BoxOptions(image=image, secrets=[ref])
)
except boxlite.NotFoundError as err:
require(
"secret not found" in str(err).lower(),
"expected a missing organization secret",
)
else:
await other.remove(unexpected.id, force=True)
pytest.fail("another organization resolved the private name")
finally:
other.close()
a = await rt.create(
boxlite.BoxOptions(
image=image, auto_remove=False, secrets=[inline, ref]
)
)
async with AsyncExitStack() as owner:
owner.push_async_callback(rt.remove, a.id, force=True)
original_values = (shared, private)
shared_policy = ("shared", shared_name)
mixed = [("private", "private"), shared_policy]
await verify(a, uri, mixed, original_values)
assert private_count(a.id, service) == 1
await a.stop()
await state(rt, a.id, "stopped")
assert private_count(a.id, service) == 1
require(
request_json("DELETE", path)[0] == 409,
"stopped Box lost its reference",
)
b = await rt.create(boxlite.BoxOptions(image=image, secrets=[ref]))
boxes.push_async_callback(rt.remove, b.id, force=True)
await verify(b, uri, [shared_policy], original_values)
await a.start()
await state(rt, a.id, "running")
await verify(a, uri, mixed, original_values)
async with asyncio.timeout(180):
while private_count(a.id, service):
await asyncio.sleep(1)
await verify(b, uri, [shared_policy], original_values)
require(
request_json("DELETE", path)[0] == 409,
"Box B lost its shared reference",
)
require(request_json("DELETE", path)[0] == 204, "owner deletion retry failed")
assert listed_secret(identity["id"]) is None