diff --git a/docs/source/getting-started.md b/docs/source/getting-started.md index e799629962..805b742765 100644 --- a/docs/source/getting-started.md +++ b/docs/source/getting-started.md @@ -22,7 +22,7 @@ A few integrations ship as optional extras. Install them with |-------|----------| | `inspect` | The Inspect AI evaluation harness | | `harbor` | The [Harbor integration](environments/harbor) and its sandbox backends (Python 3.12+) | -| `daytona`, `aca`, `modal`, `novita` | Cloud sandbox providers (see [Runtime Providers](guides/runtime-providers)) | +| `daytona`, `aca`, `modal`, `novita`, `groundbox` | Cloud sandbox providers (see [Runtime Providers](guides/runtime-providers)) | ## Try an Environment @@ -155,7 +155,7 @@ with EchoEnv(base_url="http://localhost:8000").sync() as client: result = client.reset() ``` -The same client also runs environments on cloud sandboxes (Daytona, Modal, Novita, Azure Container Apps, Hugging Face) and on a Kubernetes cluster through runtime providers. `HFSandboxProvider` ships with core OpenEnv and needs a Hugging Face token for an account that can run Jobs (the sandboxes are billed as Jobs): it runs an environment's Space image in a Hugging Face sandbox ([example](guides/runtime-providers#hfsandboxprovider)). `KubernetesProvider` is an optional extra (`pip install openenv[kubernetes]`, [example](guides/runtime-providers#kubernetesprovider)). See the [Runtime Providers guide](guides/runtime-providers) to pick one. +The same client also runs environments on cloud sandboxes (Daytona, Modal, Novita, Azure Container Apps, Groundbox, Hugging Face) and on a Kubernetes cluster through runtime providers. `HFSandboxProvider` ships with core OpenEnv and needs a Hugging Face token for an account that can run Jobs (the sandboxes are billed as Jobs): it runs an environment's Space image in a Hugging Face sandbox ([example](guides/runtime-providers#hfsandboxprovider)). `KubernetesProvider` is an optional extra (`pip install openenv[kubernetes]`, [example](guides/runtime-providers#kubernetesprovider)). See the [Runtime Providers guide](guides/runtime-providers) to pick one. ## Next Steps diff --git a/docs/source/guides/runtime-providers.md b/docs/source/guides/runtime-providers.md index 5258d51730..64a46810d1 100644 --- a/docs/source/guides/runtime-providers.md +++ b/docs/source/guides/runtime-providers.md @@ -60,6 +60,7 @@ is a one-line change. | `ACASandboxProvider` | Azure Container Apps Sandboxes | `pip install openenv[aca]` | ✅ | | `ModalProvider` | Modal sandboxes | `pip install openenv[modal]` | ✅ | | `NovitaSandboxProvider` | Novita AI sandboxes | `pip install openenv[novita]` | ✅ | +| `GroundboxProvider` | Groundbox sandboxes (microVMs) | `pip install openenv[groundbox]` | ✅ | | `HFSandboxProvider` | Hugging Face sandboxes (billed as HF Jobs) | core | ✅ | | `KubernetesProvider` | Kubernetes cluster | `pip install openenv[kubernetes]` | ✅ | @@ -91,8 +92,8 @@ async with MyEnv(provider=provider) as env: ... ``` -`ModalProvider`, `DaytonaProvider`, `ACASandboxProvider`, and `HFSandboxProvider` -support this provider-owned flow. Providers that require an explicit image at +`ModalProvider`, `DaytonaProvider`, `ACASandboxProvider`, `GroundboxProvider`, and +`HFSandboxProvider` support this provider-owned flow. Providers that require an explicit image at `start_container()` time, such as `LocalDockerProvider` and `DockerSwarmProvider`, should still be started manually and passed in with the returned `base_url`: @@ -205,6 +206,47 @@ from openenv.core.containers.runtime import DockerSwarmProvider provider = DockerSwarmProvider() ``` +### GroundboxProvider + +Runs the server in a [Groundbox](https://groundbox.dev) sandbox, a Linux microVM +of its own. Install with `pip install openenv[groundbox]`. Sign in once in the +browser, which saves an API key (a new account gets free credit): + +```bash +openenv groundbox login +``` + +The key is kept where the Groundbox CLI keeps it +(`~/.config/groundbox/credentials.json`). `GROUNDBOX_API_KEY` or `api_key=` take +precedence, for CI and other machines without a browser. + +The sandbox starts from a Docker image, such as an environment's Space image, or +from a Groundbox template. The first sandbox from an image waits while the image +is turned into a disk; later ones start in about a second. + +```python +from echo_env import EchoEnv +from openenv.core.containers.runtime.groundbox_provider import GroundboxProvider + +provider = GroundboxProvider(image="registry.hf.space/openenv-echo-env:latest") +base_url = provider.start_container() +try: + provider.wait_for_ready(base_url) + with EchoEnv(base_url=base_url).sync() as env: + env.reset() +finally: + provider.stop_container() +``` + +Images must be `linux/amd64` and public, or pushed to your Groundbox registry. +Groundbox does not run the image's `CMD`: the server command comes from the +image's `openenv.yaml` (as for Daytona), or from `cmd=`. `cpus` and `memory_gb` +size the sandbox, and `timeout_minutes` (default 60) deletes it even if +`stop_container()` is never called. The server's port gets a public HTTPS URL +with an unguessable host name, which ends with the sandbox. + +Full example: [`examples/groundbox_echo_env.py`](https://github.com/openenv/OpenEnv/blob/main/examples/groundbox_echo_env.py). + ### HFSandboxProvider Runs the server in a Hugging Face sandbox, when your Hugging Face account is diff --git a/docs/source/reference/cli.md b/docs/source/reference/cli.md index 3c1e743e37..d2e0529e70 100644 --- a/docs/source/reference/cli.md +++ b/docs/source/reference/cli.md @@ -457,6 +457,17 @@ pass the key through `OPENAI_API_KEY` instead. [[autodoc]] openenv.cli.commands.collect.collect +## `openenv groundbox login` + +Signs in to Groundbox in the browser for +[`GroundboxProvider`](../guides/runtime-providers#groundboxprovider) and saves +an API key where the Groundbox CLI keeps it. A new account is made on the way, +with free credit. It uses OAuth with PKCE and a redirect to `127.0.0.1`, so no +key is copied by hand. `GROUNDBOX_OAUTH_CLIENT_ID` overrides OpenEnv's OAuth +client; set it empty to register a new client for each sign-in. `--no-browser` prints the link instead of opening it. + +[[autodoc]] openenv.cli.commands.groundbox.login + ## `openenv harbor` Runs [Harbor](../environments/harbor) tasks with real coding agents and diff --git a/docs/source/reference/core.md b/docs/source/reference/core.md index fc0b672691..05c6374da2 100644 --- a/docs/source/reference/core.md +++ b/docs/source/reference/core.md @@ -290,6 +290,8 @@ See [Evaluating with Environments](../tutorials/evaluation-inspect) for a worked [[autodoc]] openenv.core.containers.runtime.novita_provider.NovitaSandboxProvider +[[autodoc]] openenv.core.containers.runtime.groundbox_provider.GroundboxProvider + [[autodoc]] openenv.core.containers.runtime.hf_sandbox_provider.HFSandboxProvider [[autodoc]] openenv.core.containers.runtime.kubernetes_provider.KubernetesProvider diff --git a/examples/groundbox_echo_env.py b/examples/groundbox_echo_env.py new file mode 100644 index 0000000000..fc8c596912 --- /dev/null +++ b/examples/groundbox_echo_env.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +"""Hello-world example running the Echo environment on Groundbox. + +Starts the echo-env server in a Groundbox sandbox from its Hugging Face Space +image via ``GroundboxProvider``, then talks to it through ``EchoEnv`` over the +sandbox's HTTPS preview URL (https/wss). The sandbox is deleted at the +end. + +Usage: + pip install "openenv[groundbox]" + openenv groundbox login (one-time; or set GROUNDBOX_API_KEY) + PYTHONPATH=src:envs uv run python examples/groundbox_echo_env.py +""" + +import logging + +from echo_env import EchoEnv +from openenv.core.containers.runtime.groundbox_provider import GroundboxProvider +from openenv.core.env_server.mcp_types import CallToolAction + +logger = logging.getLogger(__name__) + + +def main() -> int: + logging.basicConfig(level=logging.INFO, format="%(message)s") + + provider = GroundboxProvider(image="registry.hf.space/openenv-echo-env:latest") + logger.info( + "Starting Groundbox sandbox (the first start from an image is slower)..." + ) + base_url = provider.start_container() + try: + provider.wait_for_ready(base_url) + logger.info("Server ready in sandbox %s.", provider.sandbox_id) + with EchoEnv(base_url=base_url).sync() as env: + env.reset() + result = env.step( + CallToolAction( + tool_name="echo_message", arguments={"message": "Hello, World!"} + ) + ) + logger.info("echo_message -> %s", result.observation) + finally: + provider.stop_container() + logger.info("Sandbox deleted.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/pyproject.toml b/pyproject.toml index bb11abf606..2ede6ef8c5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -54,6 +54,9 @@ modal = [ "modal>=1.6.3", "pyyaml>=6.0", ] +groundbox = [ + "groundbox>=0.6.0", +] kubernetes = [ "kubernetes>=29.0.0", ] diff --git a/src/openenv/cli/__main__.py b/src/openenv/cli/__main__.py index b4f32159ec..388f883c7c 100644 --- a/src/openenv/cli/__main__.py +++ b/src/openenv/cli/__main__.py @@ -15,6 +15,7 @@ catalog, collect, fork, + groundbox, harbor, import_env, init, @@ -44,6 +45,11 @@ name="harbor", help="Run Harbor tasks with token-level capture (requires: pip install openenv\\[harbor])", ) +app.add_typer( + groundbox.app, + name="groundbox", + help="Sign in to Groundbox for GroundboxProvider", +) app.command(name="validate", help="Validate a package against the OpenEnv quality bar")( validate.validate ) diff --git a/src/openenv/cli/commands/groundbox.py b/src/openenv/cli/commands/groundbox.py new file mode 100644 index 0000000000..c877c4c2e8 --- /dev/null +++ b/src/openenv/cli/commands/groundbox.py @@ -0,0 +1,166 @@ +# SPDX-License-Identifier: BSD-3-Clause + +"""Sign in to Groundbox, for `GroundboxProvider`.""" + +from __future__ import annotations + +import base64 +import hashlib +import json +import os +import secrets +import time +import webbrowser +from http.server import BaseHTTPRequestHandler, HTTPServer +from typing import Annotated +from urllib.parse import parse_qs, urlencode, urlsplit + +import requests +import typer +from openenv.core.containers.runtime.groundbox_provider import ( + groundbox_credentials_path, +) + +from .._cli_utils import console + +app = typer.Typer(no_args_is_help=True) + +_SCOPES = "sandboxes:read sandboxes:write" +# OpenEnv's public OAuth client on Groundbox (PKCE, no secret). Override with +# GROUNDBOX_OAUTH_CLIENT_ID; set it empty to register a client for each login. +_CLIENT_ID = "gbc_N9uJ9s2zobxBqPp8mDOsfsMW" +_PAGE = "OpenEnv

{}

" + + +def _oauth_origin() -> str: + api = urlsplit(os.environ.get("GROUNDBOX_API_URL", "https://api.groundbox.dev/v1")) + return f"{api.scheme}://{api.netloc}" + + +def _wait_for_redirect(server: HTTPServer, timeout_s: float) -> dict[str, str]: + """Serve the loopback redirect until it brings `code` or `error`.""" + answer: dict[str, str] = {} + + class Handler(BaseHTTPRequestHandler): + def do_GET(self) -> None: + url = urlsplit(self.path) + params = {k: v[0] for k, v in parse_qs(url.query).items()} + if url.path != "/callback" or not ("code" in params or "error" in params): + self.send_response(404) + self.end_headers() + return + answer.update(params) + text = ( + "Signed in to Groundbox. You can close this tab." + if "code" in params + else "Sign-in did not finish. Run the command again." + ) + body = _PAGE.format(text).encode() + self.send_response(200) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args: object) -> None: + pass + + server.RequestHandlerClass = Handler + deadline = time.monotonic() + timeout_s + while not answer: + server.timeout = deadline - time.monotonic() + if server.timeout <= 0: + raise TimeoutError("Nobody finished signing in to Groundbox in time.") + server.handle_request() + return answer + + +@app.command() +def login( + no_browser: Annotated[ + bool, + typer.Option( + "--no-browser", help="Print the sign-in link instead of opening it" + ), + ] = False, + timeout: Annotated[ + float, + typer.Option("--timeout", help="Seconds to wait for the sign-in to finish"), + ] = 600.0, +) -> None: + """Sign in to Groundbox in the browser and save an API key for GroundboxProvider. + + A new account is made on the way, with free credit. The key is saved where the + Groundbox CLI keeps it (`~/.config/groundbox/credentials.json`). + """ + origin = _oauth_origin() + server = HTTPServer(("127.0.0.1", 0), BaseHTTPRequestHandler) + redirect_uri = f"http://127.0.0.1:{server.server_port}/callback" + try: + client_id = os.environ.get("GROUNDBOX_OAUTH_CLIENT_ID", _CLIENT_ID) + if not client_id: + registered = requests.post( + f"{origin}/oauth/register", + json={ + "client_name": "OpenEnv", + "redirect_uris": ["http://127.0.0.1/callback"], + }, + timeout=30, + ) + registered.raise_for_status() + client_id = registered.json()["client_id"] + + verifier = secrets.token_urlsafe(48) + challenge = ( + base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()) + .rstrip(b"=") + .decode() + ) + state = secrets.token_urlsafe(24) + authorize_url = f"{origin}/oauth/authorize?" + urlencode( + { + "response_type": "code", + "client_id": client_id, + "redirect_uri": redirect_uri, + "scope": _SCOPES, + "state": state, + "code_challenge": challenge, + "code_challenge_method": "S256", + "prompt": "create", + } + ) + console.print("Sign in to Groundbox (a new account gets free credit):") + console.print(authorize_url, soft_wrap=True) + if not no_browser: + webbrowser.open(authorize_url) + + answer = _wait_for_redirect(server, timeout) + finally: + server.server_close() + + if answer.get("state") != state: + console.print("[red]Groundbox sign-in came back with the wrong state.[/red]") + raise typer.Exit(1) + if "error" in answer: + console.print(f"[red]Groundbox sign-in failed: {answer['error']}[/red]") + raise typer.Exit(1) + + token = requests.post( + f"{origin}/oauth/token", + data={ + "grant_type": "authorization_code", + "code": answer["code"], + "redirect_uri": redirect_uri, + "client_id": client_id, + "code_verifier": verifier, + }, + timeout=30, + ) + token.raise_for_status() + + path = groundbox_credentials_path() + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w") as f: + json.dump({"api_key": token.json()["access_token"]}, f, indent=2) + console.print(f"Signed in to Groundbox. The API key is saved in {path}.") diff --git a/src/openenv/core/containers/runtime/groundbox_provider.py b/src/openenv/core/containers/runtime/groundbox_provider.py new file mode 100644 index 0000000000..6d3caf9f53 --- /dev/null +++ b/src/openenv/core/containers/runtime/groundbox_provider.py @@ -0,0 +1,329 @@ +# SPDX-License-Identifier: BSD-3-Clause + +""" +Groundbox container provider for running OpenEnv environments in Groundbox sandboxes. + +Requires the ``groundbox`` SDK: ``pip install openenv[groundbox]`` + +Each environment runs in its own Groundbox sandbox, a Linux microVM started +from a Docker image or a Groundbox template. The server's port gets an HTTPS +preview URL that ``EnvClient`` connects to over ``wss://``. +""" + +from __future__ import annotations + +import json +import os +import shlex +import time +from pathlib import Path +from typing import Any, Dict, Optional + +import requests + +from ._server_config import parse_openenv_app_field +from .providers import ContainerProvider + +_DEFAULT_PORT = 8000 +_LOG_PATH = "/tmp/openenv-server.log" +_PID_PATH = "/tmp/openenv-server.pid" +_KEY_HELP = ( + "Groundbox needs an API key. Run `openenv groundbox login` to sign in (a new " + "account gets free credit), set GROUNDBOX_API_KEY, or pass api_key=." +) + + +def groundbox_credentials_path() -> Path: + """Where the Groundbox CLI and `openenv groundbox login` keep the API key.""" + config_dir = os.environ.get("GROUNDBOX_CONFIG_DIR") + if config_dir: + return Path(config_dir) / "credentials.json" + xdg = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config") + return Path(xdg) / "groundbox" / "credentials.json" + + +def _resolve_api_key(api_key: Optional[str]) -> str: + if api_key: + return api_key + if os.environ.get("GROUNDBOX_API_KEY"): + return os.environ["GROUNDBOX_API_KEY"] + path = groundbox_credentials_path() + if path.is_file(): + saved = json.loads(path.read_text()).get("api_key") + if saved: + return saved + raise RuntimeError(_KEY_HELP) + + +def _refusal(exc: Any) -> RuntimeError: + """A readable error for a create Groundbox refused.""" + details = exc.details or {} + if exc.code == "trial_credit_exhausted": + message = ( + "The Groundbox account's free credit is used up. Add a card at " + "https://app.groundbox.dev/billing to keep starting sandboxes." + ) + elif exc.code == "trial_limit" and details.get("limit") == "sandbox_lifetime": + message = ( + "On free credit a Groundbox sandbox lives at most " + f"{details.get('max_sandbox_minutes')} minutes. Pass a smaller " + "timeout_minutes, or add a card at https://app.groundbox.dev/billing." + ) + elif exc.code == "trial_limit": + message = ( + "Groundbox starts sandboxes this size once the account has a card on " + "file. Pass smaller cpus/memory_gb, or add a card at " + "https://app.groundbox.dev/billing." + ) + else: + message = f"Groundbox refused to start the sandbox ({exc.code}: {exc.message})" + return RuntimeError(message) + + +class GroundboxProvider(ContainerProvider): + """ + Container provider that runs environments in Groundbox sandboxes. + + The sandbox starts from a Docker image (pulled once and kept as a disk, so + later starts take about a second) or from a Groundbox template. Groundbox + does not run the image's `CMD`: the server command is `cmd`, or is found + from the image's `openenv.yaml`. The server's port gets a public HTTPS + preview URL with an unguessable host name, which ends with the sandbox. + + Args: + image (`str`, *optional*): + Docker image to start from, such as + `"registry.hf.space/openenv-echo-env:latest"`. Images must be + `linux/amd64` and public, or in your Groundbox registry. + template (`str`, *optional*): + Groundbox template (id, name or `name:version`) to start from + instead of an image. + env_vars (`dict[str, str]`, *optional*): + Environment variables for the server. + api_key (`str`, *optional*): + Groundbox API key. Falls back to `GROUNDBOX_API_KEY`, then to the + key saved by `openenv groundbox login` or `groundbox login`. + cpus (`int`, *optional*): + vCPUs for the sandbox. Groundbox's default when omitted. + memory_gb (`int`, *optional*): + Memory in GB, at most 4 per vCPU. Groundbox's default when omitted. + timeout_minutes (`int`, *optional*, defaults to `60`): + Lifetime of the sandbox. It is deleted after this long even if + `stop_container()` is never called. + cmd (`str`, *optional*): + Shell command that starts the server inside the sandbox. + create_timeout (`float`, *optional*, defaults to `600`): + Seconds to wait for the sandbox to start. The first sandbox from an + image waits while the image is turned into a disk. + + Examples: + + ```python + from openenv.core.containers.runtime.groundbox_provider import GroundboxProvider + from openenv.core.generic_client import GenericEnvClient + + provider = GroundboxProvider(image="registry.hf.space/openenv-echo-env:latest") + with GenericEnvClient(provider=provider).sync() as env: + env.reset() + ``` + """ + + def __init__( + self, + *, + image: Optional[str] = None, + template: Optional[str] = None, + env_vars: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + cpus: Optional[int] = None, + memory_gb: Optional[int] = None, + timeout_minutes: int = 60, + cmd: Optional[str] = None, + create_timeout: float = 600, + ): + from groundbox import Groundbox + + if image is not None and template is not None: + raise ValueError("Pass image or template to GroundboxProvider, not both.") + self._client = Groundbox(api_key=_resolve_api_key(api_key)) + self._image = image + self._template = template + self._env_vars = env_vars + self._cpus = cpus + self._memory_gb = memory_gb + self._timeout_minutes = timeout_minutes + self._cmd = cmd + self._create_timeout = create_timeout + self._sandbox_id: Optional[str] = None + + @property + def sandbox_id(self) -> Optional[str]: + """Id of the running sandbox, or `None` when none is running.""" + return self._sandbox_id + + def start_container( + self, + image: Optional[str] = None, + port: Optional[int] = None, + env_vars: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> str: + """ + Start a Groundbox sandbox and the environment server in it. + + Args: + image (`str`, *optional*): + Docker image, or `"template:"` for a Groundbox template. + Defaults to the constructor's `image` or `template`. + port (`int`, *optional*, defaults to `8000`): + Port the server listens on inside the sandbox. + env_vars (`dict[str, str]`, *optional*): + Environment variables for the server. Defaults to the + constructor's `env_vars`. + **kwargs: + `cmd` (`str`) to override the server command. + + Returns: + `str`: HTTPS URL of the server. + """ + from groundbox import GroundboxError + + if self._sandbox_id is not None: + raise RuntimeError( + "GroundboxProvider already has a sandbox. Call stop_container() first." + ) + cmd = kwargs.pop("cmd", None) or self._cmd + if kwargs: + unsupported = ", ".join(sorted(kwargs)) + raise ValueError( + f"GroundboxProvider does not support start_container kwargs: {unsupported}" + ) + port = port or _DEFAULT_PORT + source: Dict[str, str] = {} + if image is not None and image.startswith("template:"): + source["template"] = image[len("template:") :] + elif image is not None: + source["image"] = image + elif self._template is not None: + source["template"] = self._template + elif self._image is not None: + source["image"] = self._image + else: + raise ValueError( + "GroundboxProvider requires an image or template. Pass it to the " + "constructor or start_container()." + ) + + deadline = time.monotonic() + self._create_timeout + while True: + try: + sandbox = self._client.create_sandbox( + **source, + cpus=self._cpus, + memory_gb=self._memory_gb, + timeout_minutes=self._timeout_minutes, + env=self._env_vars if env_vars is None else env_vars, + metadata={"created_by": "openenv"}, + ) + break + except GroundboxError as exc: + # 429: the account is at its limit of running sandboxes for now. + if exc.status != 429 or time.monotonic() + 5 > deadline: + if exc.code in ("trial_limit", "trial_credit_exhausted"): + raise _refusal(exc) from None + raise + time.sleep(5) + + self._sandbox_id = sandbox["id"] + try: + remaining = max(deadline - time.monotonic(), 1.0) + sandbox = self._client.wait_for_sandbox( + self._sandbox_id, timeout_s=remaining + ) + if sandbox["status"] != "running": + raise RuntimeError( + f"Groundbox sandbox {self._sandbox_id} is {sandbox['status']}: " + f"{sandbox.get('error') or 'it did not start in time'}" + ) + if cmd is None: + cmd = self._discover_server_cmd(port) + self._client.run_command( + self._sandbox_id, + f"nohup sh -c {shlex.quote(cmd)} > {_LOG_PATH} 2>&1 & echo $! > {_PID_PATH}", + timeout_s=30, + ) + preview = self._client.expose_port(self._sandbox_id, port, public=True) + except Exception: + self.stop_container() + raise + return preview["url"].rstrip("/") + + def _discover_server_cmd(self, port: int) -> str: + """Build the server command from the `openenv.yaml` inside the sandbox.""" + result = self._client.run_command( + self._sandbox_id, + "f=/app/env/openenv.yaml; [ -f $f ] || " + "f=$(find /app -maxdepth 4 -name openenv.yaml -print -quit 2>/dev/null); " + 'echo "$f"; cat "$f"', + timeout_s=30, + ) + path, _, content = result["stdout"].partition("\n") + app = parse_openenv_app_field(content) if path.startswith("/") else None + if app is None: + raise ValueError( + "Could not find openenv.yaml with an 'app' field inside the sandbox. " + "Pass cmd= to GroundboxProvider or start_container()." + ) + env_root = path.rsplit("/", 1)[0] + return ( + f"cd {shlex.quote(env_root)} && " + f"python -m uvicorn {shlex.quote(app)} --host 0.0.0.0 --port {port}" + ) + + def stop_container(self) -> None: + """Delete the Groundbox sandbox.""" + if self._sandbox_id is None: + return + try: + self._client.delete_sandbox(self._sandbox_id) + finally: + self._sandbox_id = None + + def wait_for_ready(self, base_url: str, timeout_s: float = 120.0) -> None: + """ + Poll the `/health` endpoint until the server answers. + + Args: + base_url (`str`): + URL returned by `start_container()`. + timeout_s (`float`, *optional*, defaults to `120.0`): + Maximum seconds to wait. + + Raises: + TimeoutError: If the server does not answer in time. + RuntimeError: If the server process exited. + """ + deadline = time.time() + timeout_s + while time.time() < deadline: + try: + if requests.get(f"{base_url}/health", timeout=5.0).status_code == 200: + return + except requests.RequestException: + pass + if self._sandbox_id is not None: + result = self._client.run_command( + self._sandbox_id, + f"kill -0 $(cat {_PID_PATH}) 2>/dev/null || cat {_LOG_PATH}", + timeout_s=30, + ) + if result["exit_code"] == 0 and result["stdout"]: + raise RuntimeError( + f"Server process died.\nLog:\n{result['stdout']}" + ) + time.sleep(1.0) + raise TimeoutError( + f"Groundbox sandbox at {base_url} did not become ready within {timeout_s}s" + ) + + +__all__ = ["GroundboxProvider", "groundbox_credentials_path"] diff --git a/tests/test_cli/test_groundbox_login.py b/tests/test_cli/test_groundbox_login.py new file mode 100644 index 0000000000..44767671b2 --- /dev/null +++ b/tests/test_cli/test_groundbox_login.py @@ -0,0 +1,160 @@ +# SPDX-License-Identifier: BSD-3-Clause + +"""Tests for `openenv groundbox login` (OAuth with PKCE and a loopback redirect).""" + +from __future__ import annotations + +import base64 +import hashlib +import json +import os +import stat +import threading +import urllib.error +import urllib.request +from unittest.mock import MagicMock, patch +from urllib.parse import parse_qs, urlencode, urlsplit + +import pytest +from openenv.cli.__main__ import app +from typer.testing import CliRunner + +runner = CliRunner() + + +def _response(payload): + response = MagicMock() + response.json.return_value = payload + return response + + +class _Browser: + """Plays the person: opens the authorize URL and follows the redirect back.""" + + def __init__(self, approve=True, state=None): + self.approve = approve + self.state = state + self.query = {} + + def open(self, url): + self.query = {k: v[0] for k, v in parse_qs(urlsplit(url).query).items()} + params = {"state": self.state or self.query["state"]} + params.update( + {"code": "the-code"} if self.approve else {"error": "access_denied"} + ) + target = f"{self.query['redirect_uri']}?{urlencode(params)}" + + def follow(): + # A stray request first, as browsers ask for a favicon. + origin = self.query["redirect_uri"].rsplit("/", 1)[0] + with pytest.raises(urllib.error.HTTPError): + urllib.request.urlopen(f"{origin}/favicon.ico", timeout=5) + urllib.request.urlopen(target, timeout=5).read() + + threading.Thread(target=follow, daemon=True).start() + return True + + +@pytest.fixture +def config_dir(tmp_path, monkeypatch): + monkeypatch.setenv("GROUNDBOX_CONFIG_DIR", str(tmp_path / "groundbox")) + monkeypatch.delenv("GROUNDBOX_API_URL", raising=False) + monkeypatch.delenv("GROUNDBOX_OAUTH_CLIENT_ID", raising=False) + return tmp_path / "groundbox" + + +def _login(browser, post): + with ( + patch("webbrowser.open", side_effect=browser.open), + patch("requests.post", side_effect=post), + ): + return runner.invoke(app, ["groundbox", "login", "--timeout", "10"]) + + +def test_login_saves_the_key(config_dir): + browser = _Browser() + post = MagicMock( + side_effect=[_response({"access_token": "gbx_new", "token_type": "Bearer"})] + ) + + result = _login(browser, post) + + assert result.exit_code == 0, result.output + saved = config_dir / "credentials.json" + assert json.loads(saved.read_text()) == {"api_key": "gbx_new"} + assert stat.S_IMODE(os.stat(saved).st_mode) == 0o600 + + query = browser.query + assert urlsplit(query["redirect_uri"]).hostname == "127.0.0.1" + assert query["client_id"] == "gbc_N9uJ9s2zobxBqPp8mDOsfsMW" + assert query["scope"] == "sandboxes:read sandboxes:write" + assert query["code_challenge_method"] == "S256" + assert query["prompt"] == "create" + + (token,) = post.call_args_list + assert token.args[0] == "https://api.groundbox.dev/oauth/token" + form = token.kwargs["data"] + assert form["code"] == "the-code" + assert form["client_id"] == query["client_id"] + assert form["redirect_uri"] == query["redirect_uri"] + challenge = ( + base64.urlsafe_b64encode( + hashlib.sha256(form["code_verifier"].encode()).digest() + ) + .rstrip(b"=") + .decode() + ) + assert challenge == query["code_challenge"] + + +def test_client_id_override(config_dir, monkeypatch): + monkeypatch.setenv("GROUNDBOX_OAUTH_CLIENT_ID", "gbc_other") + browser = _Browser() + post = MagicMock(side_effect=[_response({"access_token": "gbx_new"})]) + + result = _login(browser, post) + + assert result.exit_code == 0, result.output + assert browser.query["client_id"] == "gbc_other" + assert post.call_args.kwargs["data"]["client_id"] == "gbc_other" + + +def test_empty_client_id_registers_a_client(config_dir, monkeypatch): + monkeypatch.setenv("GROUNDBOX_OAUTH_CLIENT_ID", "") + browser = _Browser() + post = MagicMock( + side_effect=[ + _response({"client_id": "client-1"}), + _response({"access_token": "gbx_new"}), + ] + ) + + result = _login(browser, post) + + assert result.exit_code == 0, result.output + register, token = post.call_args_list + assert register.args[0] == "https://api.groundbox.dev/oauth/register" + assert register.kwargs["json"]["redirect_uris"] == ["http://127.0.0.1/callback"] + assert browser.query["client_id"] == "client-1" + assert token.kwargs["data"]["client_id"] == "client-1" + + +def test_denied_sign_in_saves_nothing(config_dir): + post = MagicMock() + + result = _login(_Browser(approve=False), post) + + assert result.exit_code == 1 + assert "access_denied" in result.output + post.assert_not_called() + assert not (config_dir / "credentials.json").exists() + + +def test_wrong_state_is_refused(config_dir): + post = MagicMock() + + result = _login(_Browser(state="forged"), post) + + assert result.exit_code == 1 + assert "wrong state" in result.output + assert not (config_dir / "credentials.json").exists() diff --git a/tests/test_core/test_groundbox_provider.py b/tests/test_core/test_groundbox_provider.py new file mode 100644 index 0000000000..e4cfce4e7e --- /dev/null +++ b/tests/test_core/test_groundbox_provider.py @@ -0,0 +1,254 @@ +# SPDX-License-Identifier: BSD-3-Clause + +"""Unit tests for GroundboxProvider. All tests use a fake groundbox SDK.""" + +from __future__ import annotations + +import json +import sys +import types +from unittest.mock import MagicMock, patch + +import pytest + + +class _FakeGroundboxError(Exception): + def __init__(self, code, message, status, details=None): + super().__init__(message) + self.code = code + self.message = message + self.status = status + self.details = details + + +_YAML = "spec_version: 1\nname: echo_env\napp: server.app:app\nport: 8000\n" + + +class _FakeGroundbox: + """Records calls; answers like the Groundbox API.""" + + def __init__(self, api_key=None): + self.api_key = api_key + self.created = [] + self.commands = [] + self.deleted = [] + self.create_errors = [] + self.status = "running" + self.alive = True + + def create_sandbox(self, **kwargs): + self.created.append(kwargs) + if self.create_errors: + raise self.create_errors.pop(0) + return {"id": "sbx_1", "status": "queued"} + + def wait_for_sandbox(self, sandbox_id, timeout_s=1800.0): + return {"id": sandbox_id, "status": self.status, "error": "pull failed"} + + def run_command(self, sandbox_id, cmd, timeout_s=None): + self.commands.append(cmd) + if "openenv.yaml" in cmd: + return {"exit_code": 0, "stdout": "/app/env/openenv.yaml\n" + _YAML} + if cmd.startswith("kill -0"): + out = "" if self.alive else "Traceback: boom" + return {"exit_code": 0, "stdout": out} + return {"exit_code": 0, "stdout": ""} + + def expose_port(self, sandbox_id, port, public=None): + self.exposed = (port, public) + return {"url": f"https://slug-{port}.groundbox.page/"} + + def delete_sandbox(self, sandbox_id): + self.deleted.append(sandbox_id) + return {} + + +@pytest.fixture +def fake_sdk(monkeypatch): + module = types.ModuleType("groundbox") + module.Groundbox = _FakeGroundbox + module.GroundboxError = _FakeGroundboxError + monkeypatch.setitem(sys.modules, "groundbox", module) + monkeypatch.setenv("GROUNDBOX_API_KEY", "gbx_env") + return module + + +@pytest.fixture +def provider_cls(fake_sdk): + from openenv.core.containers.runtime.groundbox_provider import GroundboxProvider + + return GroundboxProvider + + +class TestApiKey: + def test_argument_wins(self, provider_cls): + assert provider_cls(image="img", api_key="gbx_arg")._client.api_key == "gbx_arg" + + def test_env_var(self, provider_cls): + assert provider_cls(image="img")._client.api_key == "gbx_env" + + def test_saved_credentials(self, provider_cls, monkeypatch, tmp_path): + monkeypatch.delenv("GROUNDBOX_API_KEY") + monkeypatch.setenv("GROUNDBOX_CONFIG_DIR", str(tmp_path)) + (tmp_path / "credentials.json").write_text(json.dumps({"api_key": "gbx_saved"})) + assert provider_cls(image="img")._client.api_key == "gbx_saved" + + def test_missing_key_says_how_to_sign_in(self, provider_cls, monkeypatch, tmp_path): + monkeypatch.delenv("GROUNDBOX_API_KEY") + monkeypatch.setenv("GROUNDBOX_CONFIG_DIR", str(tmp_path)) + with pytest.raises(RuntimeError, match="openenv groundbox login"): + provider_cls(image="img") + + def test_xdg_config_home(self, fake_sdk, monkeypatch, tmp_path): + from openenv.core.containers.runtime.groundbox_provider import ( + groundbox_credentials_path, + ) + + monkeypatch.delenv("GROUNDBOX_CONFIG_DIR", raising=False) + monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path)) + assert ( + groundbox_credentials_path() == tmp_path / "groundbox" / "credentials.json" + ) + + +class TestStart: + def test_image_discovers_server_and_exposes_port(self, provider_cls): + provider = provider_cls(image="registry.hf.space/openenv-echo-env:latest") + url = provider.start_container() + + assert url == "https://slug-8000.groundbox.page" + client = provider._client + assert client.created[0]["image"] == "registry.hf.space/openenv-echo-env:latest" + assert client.created[0]["timeout_minutes"] == 60 + assert client.created[0]["metadata"] == {"created_by": "openenv"} + assert ( + "python -m uvicorn server.app:app --host 0.0.0.0 --port 8000" + in (client.commands[1]) + ) + assert "cd /app/env &&" in client.commands[1] + assert client.exposed == (8000, True) + assert provider.sandbox_id == "sbx_1" + + def test_template_and_explicit_cmd(self, provider_cls): + provider = provider_cls(template="echo", cmd="serve", cpus=4, memory_gb=8) + provider.start_container(port=9000, env_vars={"A": "1"}) + + created = provider._client.created[0] + assert created["template"] == "echo" + assert "image" not in created + assert (created["cpus"], created["memory_gb"], created["env"]) == ( + 4, + 8, + {"A": "1"}, + ) + assert len(provider._client.commands) == 1 + assert "nohup sh -c serve" in provider._client.commands[0] + assert provider._client.exposed == (9000, True) + + def test_template_prefix_in_start_container(self, provider_cls): + provider = provider_cls() + provider.start_container("template:echo:3", cmd="serve") + assert provider._client.created[0]["template"] == "echo:3" + + def test_requires_a_source(self, provider_cls): + with pytest.raises(ValueError, match="image or template"): + provider_cls().start_container() + + def test_image_and_template_conflict(self, provider_cls): + with pytest.raises(ValueError, match="not both"): + provider_cls(image="img", template="tpl") + + def test_unknown_kwargs_rejected(self, provider_cls): + with pytest.raises(ValueError, match="volumes"): + provider_cls(image="img").start_container(volumes={}) + + def test_second_start_refused(self, provider_cls): + provider = provider_cls(image="img") + provider.start_container() + with pytest.raises(RuntimeError, match="already has a sandbox"): + provider.start_container() + + def test_failed_sandbox_is_deleted(self, provider_cls): + provider = provider_cls(image="img") + provider._client.status = "failed" + with pytest.raises(RuntimeError, match="pull failed"): + provider.start_container() + assert provider._client.deleted == ["sbx_1"] + assert provider.sandbox_id is None + + def test_missing_openenv_yaml(self, provider_cls): + provider = provider_cls(image="img") + provider._client.run_command = MagicMock( + return_value={"exit_code": 1, "stdout": "\n"} + ) + with pytest.raises(ValueError, match="cmd="): + provider.start_container() + assert provider.sandbox_id is None + + def test_retries_while_rate_limited(self, provider_cls): + provider = provider_cls(image="img") + provider._client.create_errors = [ + _FakeGroundboxError("concurrency_limit", "Too many", 429) + ] + with patch("time.sleep") as sleep: + provider.start_container() + sleep.assert_called_once_with(5) + assert len(provider._client.created) == 2 + + @pytest.mark.parametrize( + ("code", "details", "match"), + [ + ("trial_credit_exhausted", None, "free credit is used up"), + ( + "trial_limit", + {"limit": "sandbox_lifetime", "max_sandbox_minutes": 60}, + "at most 60 minutes", + ), + ("trial_limit", {"limit": "sandbox_size"}, "smaller cpus/memory_gb"), + ], + ) + def test_trial_refusals_are_readable(self, provider_cls, code, details, match): + provider = provider_cls(image="img") + provider._client.create_errors = [ + _FakeGroundboxError(code, "refused", 402, details) + ] + with pytest.raises(RuntimeError, match=match): + provider.start_container() + + +class TestStopAndReady: + def test_stop_deletes_once(self, provider_cls): + provider = provider_cls(image="img") + provider.start_container() + provider.stop_container() + provider.stop_container() + assert provider._client.deleted == ["sbx_1"] + + def test_ready_when_health_answers(self, provider_cls): + provider = provider_cls(image="img") + provider.start_container() + ok = MagicMock(status_code=200) + with patch("requests.get", return_value=ok) as get: + provider.wait_for_ready("https://slug-8000.groundbox.page") + get.assert_called_once_with( + "https://slug-8000.groundbox.page/health", timeout=5.0 + ) + + def test_dead_server_raises_with_log(self, provider_cls): + provider = provider_cls(image="img") + provider.start_container() + provider._client.alive = False + with patch("requests.get", return_value=MagicMock(status_code=502)): + with pytest.raises(RuntimeError, match="Traceback: boom"): + provider.wait_for_ready("https://x", timeout_s=5) + + def test_times_out(self, provider_cls): + provider = provider_cls(image="img") + provider.start_container() + with ( + patch("requests.get", return_value=MagicMock(status_code=502)), + patch("time.sleep"), + patch("time.time", side_effect=[0, 0, 10]), + ): + with pytest.raises(TimeoutError): + provider.wait_for_ready("https://x", timeout_s=5)