Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions FEATURES.md
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,8 @@ after each item, run via

### 10. **Jobs — Real Execution via Sibling Docker Containers** ✅

- ✅ The Jobs API is also served under `/api/2.1/jobs` and `/api/2.0/jobs` (aliases of `/api/2.2/jobs`) for older SDKs/CLIs. Browser clients can be allowed with `MINILAKE_CORS_ORIGINS` (see `docs/configuration.md`)

**Modules:** `minilake/services/jobs.py`, `minilake/docker_executor.py`
**Endpoints:**

Expand Down
3 changes: 3 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ services:
MINILAKE_DATA_DIR: /data
MINILAKE_HOST: 0.0.0.0
MINILAKE_PORT: 8000
# Browser origins allowed to call the API cross-origin (comma-separated, "*" for any).
# Defaults to a local web app such as OpenArchFlow; minilake has no auth, so keep it narrow.
MINILAKE_CORS_ORIGINS: ${MINILAKE_CORS_ORIGINS:-http://localhost:3000}
# Native HTTPS on :8443 (drop the external TLS proxy). Auto-generates a
# self-signed cert under /data/certs; trust it on the client via keychain
# import (macOS) or SSL_CERT_FILE (Linux). To bring your own CA-signed cert,
Expand Down
1 change: 1 addition & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Everything is set through environment variables. Nothing needs a config file.
| `MINILAKE_DUCKDB_MEMORY_LIMIT` | `4GB` | DuckDB `memory_limit`, applied to every connection. Each database (the shared Unity Catalog one and each warehouse) gets its own limit. An invalid value stops startup |
| `MINILAKE_STATEMENT_CACHE_SIZE` | `500` | How many executed statements to keep. Backs both `GET /statements/{id}` and query history; the oldest lose their rows first, then their metadata |
| `MINILAKE_DEV_CORS` | unset | `1` allows cross-origin API access, for running the web UI's Next.js dev server on another port. Leave off otherwise — minilake has no authentication ([Web UI](ui.md#development)) |
| `MINILAKE_CORS_ORIGINS` | unset | Comma-separated browser origins allowed to call the API cross-origin, e.g. `http://localhost:3000` (`*` allows any). Also answers Chrome Private Network Access preflights. Use it to let an external web app such as OpenArchFlow reach minilake. minilake has no authentication, so only list origins you trust |
| `MINILAKE_DUCKDB_EXTENSION_DIR` | unset (`/opt/duckdb-extensions` in the image) | Directory of pre-installed DuckDB extensions. When set, the server only `LOAD`s the `delta` extension and never downloads it, which is what makes the image work with no internet access |

### Persistence
Expand Down
67 changes: 64 additions & 3 deletions src/minilake/app.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
"""FastAPI application factory for minilake."""

import asyncio
import inspect
import logging
import mimetypes
import re
import textwrap
from contextlib import AsyncExitStack, asynccontextmanager
from importlib.metadata import PackageNotFoundError, version
Expand Down Expand Up @@ -204,6 +206,51 @@ def _resolve_ui_dir() -> Path | None:
return None


_JOBS_ALIAS_RE = re.compile(r"^/api/2\.[01]/jobs(?=/|$)")


class JobsApiVersionAliasMiddleware:
"""Rewrite /api/2.0/jobs and /api/2.1/jobs to the /api/2.2/jobs router."""

def __init__(self, app):
self.app = app

async def __call__(self, scope, receive, send):
if scope["type"] == "http":
path = scope["path"]
new_path = _JOBS_ALIAS_RE.sub("/api/2.2/jobs", path)
if new_path != path:
scope = dict(scope, path=new_path, raw_path=new_path.encode())
await self.app(scope, receive, send)


class PrivateNetworkAccessMiddleware:
"""Answer Chrome's Private Network Access preflights on Starlette versions without
native support (CORSMiddleware(allow_private_network=...)).

HTTPS pages calling a local server send ``Access-Control-Request-Private-Network``
and require ``Access-Control-Allow-Private-Network: true`` in the response.
"""

def __init__(self, app):
self.app = app

async def __call__(self, scope, receive, send):
if scope["type"] != "http":
await self.app(scope, receive, send)
return
wants_pna = any(k == b"access-control-request-private-network" and v == b"true" for k, v in scope["headers"])

async def send_wrapper(message):
if wants_pna and message["type"] == "http.response.start":
headers = list(message.get("headers", []))
headers.append((b"access-control-allow-private-network", b"true"))
message = dict(message, headers=headers)
await send(message)

await self.app(scope, receive, send_wrapper)


def create_app() -> FastAPI:
"""Create and configure the FastAPI application."""
app = FastAPI(
Expand All @@ -219,15 +266,29 @@ def create_app() -> FastAPI:
# Same-origin is the normal case (the UI is served from /ui by this same app);
# this exists only so the UI's Next.js dev server on another port can reach the
# API during development.
cors_origins = ["*"] if settings.dev_cors else settings.cors_origin_list
if settings.dev_cors:
logger.warning("MINILAKE_DEV_CORS is set: allowing cross-origin API access from any origin")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
if cors_origins:
logger.info(f"CORS enabled for origins: {cors_origins}")
cors_kwargs = dict(
allow_origins=cors_origins,
allow_credentials=False,
allow_methods=["*"],
allow_headers=["*"],
)
if "allow_private_network" in inspect.signature(CORSMiddleware.__init__).parameters:
# Recent Starlette answers Private Network Access preflights itself (and
# rejects them with 400 unless this is set).
app.add_middleware(CORSMiddleware, allow_private_network=True, **cors_kwargs)
else:
app.add_middleware(CORSMiddleware, **cors_kwargs)
# Registered after CORSMiddleware so it runs outermost and can decorate the
# preflight response CORSMiddleware generates.
app.add_middleware(PrivateNetworkAccessMiddleware)

# Older Databricks SDKs/CLIs call the Jobs API under /api/2.0 and /api/2.1.
app.add_middleware(JobsApiVersionAliasMiddleware)

# Include admin router unconditionally
app.include_router(admin_router)
Expand Down
12 changes: 12 additions & 0 deletions src/minilake/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,18 @@ class Settings(BaseSettings):
# and minilake has no auth to fall back on.
dev_cors: bool = os.getenv("MINILAKE_DEV_CORS", "").lower() in ("1", "true", "yes")

# Comma-separated allowlist of browser origins that may call the API cross-origin
# (e.g. "http://localhost:3000,https://app.example.com"); "*" allows any origin.
# Unset keeps the default same-origin behaviour. Unlike MINILAKE_DEV_CORS this lets
# an external web app (such as OpenArchFlow) talk to minilake.
# Kept as the raw string: pydantic-settings would parse a list-typed field from the
# environment as JSON, so "a,b" would stop startup. Use `cors_origin_list`.
cors_origins: str = ""

@property
def cors_origin_list(self) -> list[str]:
return [o.strip() for o in self.cors_origins.split(",") if o.strip()]

# DuckDB settings
duckdb_memory_limit: str = os.getenv("MINILAKE_DUCKDB_MEMORY_LIMIT", "4GB")
# Directory holding pre-installed DuckDB extensions. The Docker image sets this and
Expand Down
82 changes: 82 additions & 0 deletions tests/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,85 @@ def test_databricks_error_dict():
assert error_dict["error_code"] == "NOT_FOUND"
assert error_dict["message"] == "Resource not found"
print("✓ DatabricksError dict conversion works")


# --- CORS allowlist and Jobs API version aliases ---------------------------------------


def _client(monkeypatch, origins):
from starlette.testclient import TestClient

from minilake import app as app_module

monkeypatch.setattr(app_module.settings, "cors_origins", ",".join(origins))
monkeypatch.setattr(app_module.settings, "dev_cors", False)
# No context manager: skip the lifespan, these requests never touch state.
return TestClient(create_app())


PREFLIGHT = {
"Origin": "http://localhost:3000",
"Access-Control-Request-Method": "POST",
"Access-Control-Request-Headers": "authorization,content-type",
}


@pytest.mark.smoke
def test_cors_allowed_origin(monkeypatch):
client = _client(monkeypatch, ["http://localhost:3000"])
resp = client.options("/api/2.2/jobs/runs/submit", headers=PREFLIGHT)
assert resp.status_code == 200
assert resp.headers["access-control-allow-origin"] == "http://localhost:3000"


@pytest.mark.smoke
def test_cors_disallowed_origin(monkeypatch):
client = _client(monkeypatch, ["http://localhost:3000"])
resp = client.options("/api/2.2/jobs/runs/submit", headers={**PREFLIGHT, "Origin": "http://evil.example"})
assert "access-control-allow-origin" not in resp.headers


@pytest.mark.smoke
def test_cors_disabled_by_default(monkeypatch):
client = _client(monkeypatch, [])
resp = client.get("/_minilake/health", headers={"Origin": "http://localhost:3000"})
assert "access-control-allow-origin" not in resp.headers


@pytest.mark.smoke
def test_private_network_access_preflight(monkeypatch):
client = _client(monkeypatch, ["http://localhost:3000"])
resp = client.options(
"/api/2.2/jobs/runs/submit",
headers={**PREFLIGHT, "Access-Control-Request-Private-Network": "true"},
)
assert resp.headers["access-control-allow-private-network"] == "true"


@pytest.mark.smoke
@pytest.mark.parametrize("version", ["2.0", "2.1", "2.2"])
def test_jobs_api_version_aliases(version):
from starlette.testclient import TestClient

from minilake.app import JobsApiVersionAliasMiddleware

seen = []

async def inner(scope, receive, send):
seen.append(scope["path"])
await send({"type": "http.response.start", "status": 204, "headers": []})
await send({"type": "http.response.body", "body": b""})

client = TestClient(JobsApiVersionAliasMiddleware(inner))
client.get(f"/api/{version}/jobs/runs/get")
client.get(f"/api/{version}/clusters/list")
assert seen == ["/api/2.2/jobs/runs/get", f"/api/{version}/clusters/list"]


@pytest.mark.smoke
def test_cors_origins_env_is_comma_separated(monkeypatch):
"""Regression: a comma-separated env value must not be parsed as JSON."""
from minilake.config import Settings

monkeypatch.setenv("MINILAKE_CORS_ORIGINS", "http://a.example, http://b.example")
assert Settings().cors_origin_list == ["http://a.example", "http://b.example"]
Loading