diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 79894b0..27491f3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -51,7 +51,7 @@ jobs: strategy: fail-fast: false matrix: - router: [ts, go] + router: [ts, go, python] steps: - uses: actions/checkout@v4 @@ -84,6 +84,11 @@ jobs: uv venv --python 3.10 .venv uv pip install --python .venv/bin/python schemathesis pytest httpx jsonschema + - name: Install the Python router into the harness + if: matrix.router == 'python' + working-directory: conformance + run: uv pip install --python .venv/bin/python fastapi uvicorn -e ../routers/python + - name: Run conformance (${{ matrix.router }}) working-directory: conformance env: diff --git a/conformance/servers/py_server.py b/conformance/servers/py_server.py new file mode 100644 index 0000000..8aa59f9 --- /dev/null +++ b/conformance/servers/py_server.py @@ -0,0 +1,38 @@ +"""Boot the Python router for conformance testing. + +Default (mock) mode points at the in-memory mock via ``MONAD_API_BASE``; live +mode sets the same knobs to real Monad staging values. Every value falls back to +the mock fixture default, so nothing changes for the existing hermetic run. +""" + +import os + +import uvicorn +from fastapi import FastAPI + +from monad_embed import EmbedConfig, Provision, embed_router + +# A provisioned id may be intentionally empty (a live tenant with no store) → +# treat "" as "not provisioned" so the router falls back to a dev/null sink. +_store = os.environ.get("MONAD_STORE_ID", "out_store") or None +_source = os.environ.get("MONAD_SOURCE_ID", "in_source") or None +# Empty allow-list → expose the whole catalog (None), never the empty set. +_allow = [s.strip() for s in os.environ.get("MONAD_CATALOG_ALLOW", "aws-cloudtrail,okta-systemlog").split(",") if s.strip()] or None + +app = FastAPI() +app.include_router( + embed_router( + EmbedConfig( + api_key=os.environ.get("MONAD_API_KEY", "conf-key"), + api_base=os.environ["MONAD_API_BASE"], + frame_origin=os.environ.get("MONAD_FRAME_ORIGIN", "https://app.monad.com/embed"), + get_customer_org_id=lambda req: os.environ.get("MONAD_ORG_ID", "org_conf"), + get_provisioned_components=lambda org: Provision(destination_output_id=_store, source_input_id=_source), + catalog_allow=_allow, + ) + ), + prefix="/embed", +) + +if __name__ == "__main__": + uvicorn.run(app, host="127.0.0.1", port=int(os.environ.get("PORT", "8791")), log_level="warning") diff --git a/routers/python/.gitignore b/routers/python/.gitignore new file mode 100644 index 0000000..13f2046 --- /dev/null +++ b/routers/python/.gitignore @@ -0,0 +1,7 @@ +.venv/ +__pycache__/ +*.pyc +.pytest_cache/ +*.egg-info/ +dist/ +build/ diff --git a/routers/python/README.md b/routers/python/README.md new file mode 100644 index 0000000..3b54b53 --- /dev/null +++ b/routers/python/README.md @@ -0,0 +1,104 @@ +# Monad Embed — Python router + +A mountable `/embed` backend router for a Monad embed integration, as a FastAPI +`APIRouter`. Implements the [`/embed` route contract](../../packages/embed/openapi/embed.openapi.yaml). + +```python +from fastapi import FastAPI +from monad_embed import EmbedConfig, Provision, embed_router + +app = FastAPI() +app.include_router( + embed_router(EmbedConfig( + api_key=os.environ["MONAD_API_KEY"], + # your auth → the tenant's Monad team id (sync or async) + get_customer_org_id=lambda req: req.session["org_id"], + # server-side lookup of a tenant's pre-provisioned components + get_provisioned_components=lambda org: Provision(destination_output_id=STORES[org]), + )), + prefix="/embed", +) +``` + +Mounted with `prefix="/embed"`, the router serves `/embed/session`, +`/embed/pipelines/ingress`, etc. The browser holds only a session token; this +router holds the API key and is the seam to the Monad API. + +## Mounting on common frameworks + +`embed_router(cfg)` is a FastAPI `APIRouter` (ASGI), so it slots into any FastAPI +or Starlette app. Assume `router = embed_router(cfg)` below. + +**FastAPI** — include it in your app + +```python +app.include_router(router, prefix="/embed") +``` + +**FastAPI** — as an isolated sub-application (its own docs, middleware, lifespan) + +```python +embed_app = FastAPI() +embed_app.include_router(router) +app.mount("/embed", embed_app) +``` + +**Starlette** — [starlette](https://www.starlette.io) + +```python +from starlette.applications import Starlette +from starlette.routing import Mount + +embed_app = FastAPI() +embed_app.include_router(router) + +app = Starlette(routes=[ + Mount("/embed", app=embed_app), + # ... your other routes +]) +``` + +Serve it with any ASGI server: + +```sh +uvicorn app:app +# or: gunicorn -k uvicorn.workers.UvicornWorker app:app +# or: hypercorn app:app +``` + +**Flask / Django (WSGI)** — the router is ASGI, so either run it as its own +service, or host it inside your WSGI app with an ASGI bridge such as +[`a2wsgi`](https://github.com/abersheeran/a2wsgi): + +```python +from a2wsgi import ASGIMiddleware +from werkzeug.middleware.dispatcher import DispatcherMiddleware + +embed_app = FastAPI() +embed_app.include_router(router) + +# /embed/* → the ASGI embed app; everything else → Flask +flask_app.wsgi_app = DispatcherMiddleware( + flask_app.wsgi_app, + {"/embed": ASGIMiddleware(embed_app)}, +) +``` + +## Config + +| Field | Purpose | +| ---------------------------- | ------------------------------------------------------------------------------------------------------------ | +| `api_key` | Long-lived Monad API key (server-side only). | +| `api_base` | Monad API base. Optional — defaults to `https://app.monad.com/api` (production). | +| `frame_origin` | Iframe origin returned by `GET /embed/config`. Optional — defaults to production. | +| `get_customer_org_id` | `Request → org id`, sync or async. Return `""` / raise to reject (→ 401). | +| `get_provisioned_components` | `org → Provision(destination_output_id, source_input_id)`. Omit → ingress uses dev/null, egress unavailable. | +| `catalog_allow` | Restrict the catalog to these connector type ids. Omit → all. | + +## Develop + +```sh +uv venv --python 3.10 .venv +uv pip install --python .venv/bin/python "fastapi>=0.110" "httpx>=0.27" "pytest>=8" +.venv/bin/python -m pytest -q +``` diff --git a/routers/python/monad_embed/__init__.py b/routers/python/monad_embed/__init__.py new file mode 100644 index 0000000..3ff1c00 --- /dev/null +++ b/routers/python/monad_embed/__init__.py @@ -0,0 +1,34 @@ +"""monad-embed — a mountable ``/embed`` backend router (FastAPI). + +Implements the ``/embed`` route contract (``packages/embed/openapi/embed.openapi.yaml``) +for a Monad embed integration. + + from fastapi import FastAPI + from monad_embed import EmbedConfig, Provision, embed_router + + app = FastAPI() + app.include_router( + embed_router(EmbedConfig( + api_key=os.environ["MONAD_API_KEY"], + api_base="https://app.monad.com/api", + frame_origin="https://app.monad.com/embed", + get_customer_org_id=lambda req: req.session["org_id"], # your auth → Monad team + get_provisioned_components=lambda org: Provision(destination_output_id=STORES[org]), + )), + prefix="/embed", + ) +""" + +from .client import MonadClient +from .config import EmbedConfig, Provision +from .errors import EmbedError, MonadError +from .router import embed_router + +__all__ = [ + "EmbedConfig", + "Provision", + "MonadClient", + "EmbedError", + "MonadError", + "embed_router", +] diff --git a/routers/python/monad_embed/client.py b/routers/python/monad_embed/client.py new file mode 100644 index 0000000..5874424 --- /dev/null +++ b/routers/python/monad_embed/client.py @@ -0,0 +1,273 @@ +"""The hand-written Monad API client — the Python equivalent of the TS kit. + +Sequences Monad's /v1 + /v2 + /v3 calls; the router layer turns its results into +the ``/embed`` contract's responses. A failed call raises :class:`MonadError`, +which the router maps to ``502 upstream_error``. +""" + +from __future__ import annotations + +import asyncio +from typing import Any, Optional +from urllib.parse import quote + +import httpx + +from .errors import MonadError +from .models import ( + BuiltPipeline, + CatalogType, + ConfiguredConnector, + PipelineStatus, + Session, +) + +_POLL_ATTEMPTS = 15 +_POLL_INTERVAL = 2.0 + +# Rows per request when draining a Monad list. Monad defaults ``limit`` to 10 +# and enforces no maximum, so this is a round-trip/response-size trade-off only: +# correctness comes from draining every page. +_PAGE_SIZE = 200 + +# Hard ceiling on pages drained from a single list, so an upstream that never +# returns a short page (e.g. offset-clamping) bounds the loop instead of +# spinning forever / exhausting memory. _MAX_PAGES * _PAGE_SIZE = 200k rows — +# far beyond any real tenant. +_MAX_PAGES = 1000 + + +def _seg(value: Any) -> str: + """URL-encode a single path segment so browser-supplied ids can't inject + query params or traverse the path (``/``, ``?``, ``#`` are neutralised).""" + return quote(str(value), safe="") + + +def _collection(kind: str) -> str: + """The contract's singular ``kind`` → Monad's collection path segment. + Spelled out rather than appending "s", so the mapping is a fact.""" + return "inputs" if kind == "input" else "outputs" + + +class MonadClient: + """Talks to the Monad API with the host's long-lived key.""" + + def __init__( + self, + api_key: str, + api_base: str, + *, + transport: Optional[httpx.AsyncBaseTransport] = None, + ) -> None: + self._base = api_base.rstrip("/") + self._headers = { + "Authorization": f"ApiKey {api_key}", + "Content-Type": "application/json", + } + self._transport = transport + self._poll_attempts = _POLL_ATTEMPTS + self._poll_interval = _POLL_INTERVAL + + def _open(self) -> httpx.AsyncClient: + return httpx.AsyncClient(timeout=30.0, transport=self._transport) + + async def _do( + self, c: httpx.AsyncClient, method: str, path: str, json_body: Any = None + ) -> Any: + resp = await c.request(method, self._base + path, headers=self._headers, json=json_body) + if resp.status_code >= 400: + raise MonadError(resp.status_code, f"{resp.status_code} {path}: {resp.text[:300]}") + if not resp.content: + return None + return resp.json() + + async def mint_session(self, org: str) -> Session: + async with self._open() as c: + data = await self._do( + c, "POST", "/v3/sessions", {"ttl_seconds": 1800, "organization_id": org} + ) + return Session( + sessionToken=data["session_token"], + organizationId=org, + expiresAt=data["expires_at"], + ) + + async def list_catalog( + self, kind: str, allow: Optional[list[str]] + ) -> list[CatalogType]: + async with self._open() as c: + data = await self._do(c, "GET", f"/v1/{_collection(kind)}") + allow_set = set(allow) if allow else None + out: list[CatalogType] = [] + for t in data or []: + if allow_set is not None and t.get("type_id") not in allow_set: + continue + out.append(CatalogType(typeId=t["type_id"], name=t["name"])) + return out + + async def list_connectors(self, org: str, kind: str) -> list[ConfiguredConnector]: + """Every connector of a kind the tenant has configured. + + Monad pages this at ``limit=10`` by default with no maximum, and the + ``/embed`` contract returns a bare array with no pagination — so + draining the pages is the router's job. One large ``limit`` instead + would silently truncate whichever tenant outgrows it. + """ + key = _collection(kind) + out: list[ConfiguredConnector] = [] + async with self._open() as c: + # A short page is the only safe stop; trusting pagination.total to + # break early truncates the list when Monad under-reports it. + # _MAX_PAGES bounds an upstream that never returns a short page. + for page_index in range(_MAX_PAGES): + offset = page_index * _PAGE_SIZE + page = await self._do( + c, "GET", f"/v1/{_seg(org)}/{key}?limit={_PAGE_SIZE}&offset={offset}" + ) + # Monad returns the list as null (not []) for an empty page, so + # coalesce with `or []` — a bare .get(key, []) would return null. + rows = (page or {}).get(key) or [] + out.extend( + ConfiguredConnector(id=r["id"], typeId=r["type"], name=r["name"]) + for r in rows + ) + if len(rows) < _PAGE_SIZE: + return out + raise MonadError(502, f"pagination exceeded {_MAX_PAGES} pages draining {key}") + + async def wire_pipeline( + self, org: str, input_id: str, output_id: str, name: str + ) -> BuiltPipeline: + body = { + "name": name, + "description": "Created when the connector was configured via embed", + "enabled": True, + "nodes": [ + {"slug": "in", "component_id": input_id, "component_type": "input", "enabled": True}, + {"slug": "out", "component_id": output_id, "component_type": "output", "enabled": True}, + ], + "edges": [ + { + "from_node_instance_id": "in", + "to_node_instance_id": "out", + "description": "all records", + "conditions": {"operator": "always"}, + } + ], + } + async with self._open() as c: + created = await self._do(c, "POST", f"/v2/{_seg(org)}/pipelines/", body) + pid = created["id"] + # The pipeline now EXISTS. Polling for Running is a courtesy — a + # transient status-poll failure must NOT fail the request, or the + # caller treats a live pipeline as un-built and retries into a + # duplicate. On a poll error we stop with the last-known status. + status = "Pending" + for _ in range(self._poll_attempts): + try: + s = await self._do(c, "GET", f"/v2/{_seg(org)}/pipelines/{_seg(pid)}/status") + except MonadError: + break + status = (s or {}).get("status") or status + if status in ("Running", "Erroring"): + break + await asyncio.sleep(self._poll_interval) + return BuiltPipeline( + pipelineId=pid, outputId=output_id, status=status, active=status == "Running" + ) + + async def build_dev_null(self, org: str, input_id: str, name: str) -> BuiltPipeline: + async with self._open() as c: + out = await self._do( + c, + "POST", + f"/v2/{_seg(org)}/outputs", + { + # `type` is canonical; `output_type` is a deprecated alias. + "type": "dev-null", + "name": f"{name} → /dev/null", + "description": "Auto-created sink for embed pipeline", + "promise_id": "", + "config": {"settings": {}, "secrets": {}}, + }, + ) + try: + return await self.wire_pipeline(org, input_id, out["id"], name) + except Exception: + # The sink was created but wiring failed. Best-effort delete it so a + # retry doesn't accumulate dev/null outputs; if the cleanup itself + # fails, leave it for orphan monitoring + # (docs/embed-security-and-operations.md) and surface the original + # error. Create/delete are non-atomic — Monad offers no transaction. + try: + async with self._open() as c: + await self._do(c, "DELETE", f"/v1/{_seg(org)}/outputs/{_seg(out['id'])}") + except Exception: + pass + raise + + async def _pipeline_nodes(self, c: httpx.AsyncClient, org: str, pid: str) -> list[dict]: + """A pipeline's wiring. The detail response is flat — the nodes sit at + the top level, not under a ``config`` envelope.""" + data = await self._do(c, "GET", f"/v2/{_seg(org)}/pipelines/{_seg(pid)}") + return (data or {}).get("nodes") or [] + + async def pipeline_for(self, org: str, kind: str, connector_id: str) -> PipelineStatus: + """The pipeline a configured connector is wired into. + + Monad answers this directly: ``GET /v1/{org}/{kind}s/{id}`` returns + ``component_of``, the pipelines the component is a node of. Walking the + org's pipeline list instead would be both O(n) and wrong — that list + pages at 10, so any pipeline past the first page would read as "not + connected". + + ``component_of`` carries no wiring (the datastore fills only a summary + projection), so resolving the peer connector costs one further fetch. + Raises :class:`MonadError` with status 404 when the connector is gone. + """ + async with self._open() as c: + connector = await self._do( + c, "GET", f"/v1/{_seg(org)}/{_collection(kind)}/{_seg(connector_id)}" + ) + # The embed flow wires each connector into exactly one pipeline + # (Monad guarantees a pipeline has a single input, and embed never + # adds a connector to a second pipeline), so component_of has at most + # one entry and taking the first is unambiguous. + pipelines = (connector or {}).get("component_of") or [] + if not pipelines or not pipelines[0].get("id"): + return PipelineStatus(hasPipeline=False, enabled=False) + + pipeline = pipelines[0] + peer_type = "output" if kind == "input" else "input" + nodes = await self._pipeline_nodes(c, org, pipeline["id"]) + peer = next((n for n in nodes if n.get("component_type") == peer_type), None) + peer_id = peer.get("component_id") if peer else None + + return PipelineStatus( + hasPipeline=True, + enabled=bool(pipeline.get("enabled")), + pipelineId=pipeline["id"], + outputId=peer_id if kind == "input" else None, + inputId=peer_id if kind == "output" else None, + ) + + async def set_enabled(self, org: str, pipeline_id: str, enabled: bool) -> None: + """Flip a pipeline's enabled flag. + + ``PATCH`` is a true partial update: omitted fields keep their stored + value and the node/edge graph is preserved untouched. Reading the + pipeline and sending it back would replace the graph with whatever + subset of fields the round trip happened to reproduce — silently + dropping node ``config_overrides`` and edge ``schema_detection_spec``. + """ + async with self._open() as c: + await self._do( + c, + "PATCH", + f"/v2/{_seg(org)}/pipelines/{_seg(pipeline_id)}", + {"enabled": enabled}, + ) + + async def delete(self, path: str) -> None: + async with self._open() as c: + await self._do(c, "DELETE", path) diff --git a/routers/python/monad_embed/config.py b/routers/python/monad_embed/config.py new file mode 100644 index 0000000..5b97a13 --- /dev/null +++ b/routers/python/monad_embed/config.py @@ -0,0 +1,49 @@ +"""Configuration for the ``/embed`` router — uniform across every language.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Awaitable, Callable, Optional, Union + +from starlette.requests import Request + + +@dataclass +class Provision: + """What the host pre-provisions per tenant, resolved server-side. + + Never sent by the browser. + """ + + #: Ingress target. ``None`` → ingress goes to a dev/null sink. + destination_output_id: Optional[str] = None + #: Egress source. ``None`` → egress is unavailable. + source_input_id: Optional[str] = None + + +#: Resolve the authenticated request to the caller's Monad team id. Sync or async. +GetCustomerOrgID = Callable[[Request], Union[str, Awaitable[str]]] +#: Return a tenant's pre-provisioned resources. Sync or async. +GetProvisionedComponents = Callable[[str], Union[Provision, Awaitable[Provision]]] + + +@dataclass +class EmbedConfig: + """Uniform router configuration.""" + + #: Long-lived Monad API key. Server-side only. + api_key: str + #: Map the authenticated request → the caller's Monad team id. The one seam + #: only the host can fill. Raise (or return ``""``) to reject → 401. + get_customer_org_id: GetCustomerOrgID + #: Monad API base. Defaults to ``https://app.monad.com/api`` (production); + #: set only for non-prod. + api_base: str = "https://app.monad.com/api" + #: Iframe origin returned by ``GET /embed/config``. Defaults to + #: ``https://app.monad.com/embed`` (production); set only for non-prod. + frame_origin: str = "https://app.monad.com/embed" + #: Per-tenant pre-provisioned resources. ``None`` → ingress uses dev/null and + #: egress is unavailable. + get_provisioned_components: Optional[GetProvisionedComponents] = None + #: Restrict the catalog to these connector type ids. ``None`` → all. + catalog_allow: Optional[list[str]] = None diff --git a/routers/python/monad_embed/errors.py b/routers/python/monad_embed/errors.py new file mode 100644 index 0000000..451d95b --- /dev/null +++ b/routers/python/monad_embed/errors.py @@ -0,0 +1,27 @@ +"""Error types for the ``/embed`` router.""" + +from __future__ import annotations + + +class EmbedError(Exception): + """An error carrying the HTTP status + stable code from the contract's error model.""" + + def __init__(self, status: int, code: str, message: str) -> None: + super().__init__(message) + self.status = status + self.code = code + self.message = message + + +class MonadError(Exception): + """Raised by the Monad client on an API failure. Mapped to ``502 upstream_error``. + + Carries the upstream status + internal detail for server-side logging; the + router surfaces only a generic message so the upstream response body never + reaches the browser. + """ + + def __init__(self, status: int, detail: str) -> None: + super().__init__(detail) + self.status = status + self.detail = detail diff --git a/routers/python/monad_embed/models.py b/routers/python/monad_embed/models.py new file mode 100644 index 0000000..3cc5b8b --- /dev/null +++ b/routers/python/monad_embed/models.py @@ -0,0 +1,44 @@ +"""Response models for the ``/embed`` contract (camelCase, per the spec).""" + +from __future__ import annotations + +from typing import Optional + +from pydantic import BaseModel + + +class ConfigResponse(BaseModel): + frameOrigin: str + apiBase: str + + +class Session(BaseModel): + sessionToken: str + organizationId: str + expiresAt: str + + +class CatalogType(BaseModel): + typeId: str + name: str + + +class ConfiguredConnector(BaseModel): + id: str + typeId: str + name: str + + +class BuiltPipeline(BaseModel): + pipelineId: str + outputId: str + status: str + active: bool + + +class PipelineStatus(BaseModel): + hasPipeline: bool + enabled: bool + pipelineId: Optional[str] = None + inputId: Optional[str] = None + outputId: Optional[str] = None diff --git a/routers/python/monad_embed/router.py b/routers/python/monad_embed/router.py new file mode 100644 index 0000000..e9684f7 --- /dev/null +++ b/routers/python/monad_embed/router.py @@ -0,0 +1,216 @@ +"""The mountable ``/embed`` FastAPI router.""" + +from __future__ import annotations + +import functools +import inspect +import logging +from typing import Any, Awaitable, Callable, Optional + +from fastapi import APIRouter, Response +from fastapi.responses import JSONResponse +from starlette.requests import Request + +from .client import MonadClient, _seg +from .config import EmbedConfig, Provision +from .errors import EmbedError, MonadError +from .models import ConfigResponse + +logger = logging.getLogger("monad_embed") + + +def _error(status: int, code: str, message: str) -> JSONResponse: + return JSONResponse(status_code=status, content={"code": code, "message": message}) + + +async def _maybe_await(value: Any) -> Any: + if inspect.isawaitable(value): + return await value + return value + + +async def _resolve(config: EmbedConfig, request: Request) -> str: + try: + org = await _maybe_await(config.get_customer_org_id(request)) + except EmbedError: + raise + except Exception as exc: # noqa: BLE001 — any resolver failure means "not authenticated" + raise EmbedError( + 401, "unauthenticated", "Could not resolve a tenant for the request." + ) from exc + if not org: + raise EmbedError(401, "unauthenticated", "Could not resolve a tenant for the request.") + return org + + +async def _provision(config: EmbedConfig, org: str) -> Provision: + if config.get_provisioned_components is None: + return Provision() + return await _maybe_await(config.get_provisioned_components(org)) + + +def _require_kind(value: Optional[str]) -> str: + if value not in ("input", "output"): + raise EmbedError(400, "invalid_request", "'kind' must be 'input' or 'output'.") + return value + + +def _require_str(body: Any, field: str) -> str: + value = body.get(field) if isinstance(body, dict) else None + if not isinstance(value, str) or not value: + raise EmbedError(400, "invalid_request", f"Field '{field}' is required.") + return value + + +async def _json_body(request: Request) -> Any: + try: + return await request.json() + except Exception: # noqa: BLE001 — malformed/empty body → validated below + return None + + +def _guard( + fn: Callable[[Request], Awaitable[Response]], +) -> Callable[[Request], Awaitable[Response]]: + """Wrap a route so every failure returns the contract's uniform error body.""" + + @functools.wraps(fn) + async def wrapper(request: Request) -> Response: + try: + return await fn(request) + except EmbedError as exc: + return _error(exc.status, exc.code, exc.message) + except MonadError as exc: + # Translate Monad's own status codes into the contract's error model. + if exc.status == 404: + return _error( + 404, "not_found", "The referenced connector or pipeline does not exist." + ) + if exc.status == 409: + return _error(409, "conflict", "The request conflicts with existing state.") + # Anything else: log the detail server-side, return a generic 502. + logger.error("upstream Monad API call failed: %s", exc) + return _error(502, "upstream_error", "The upstream Monad API request failed.") + except Exception: # noqa: BLE001 + logger.exception("unexpected error handling embed request") + return _error(500, "internal_error", "An unexpected error occurred.") + + return wrapper + + +def embed_router( + config: EmbedConfig, *, monad_client: Optional[MonadClient] = None +) -> APIRouter: + """Build the ``/embed`` router. Mount with ``app.include_router(router, prefix="/embed")``. + + ``monad_client`` is an injection hook (mainly for tests); by default one is + built from ``config``. + """ + client = monad_client or MonadClient(config.api_key, config.api_base) + router = APIRouter() + + async def get_config(request: Request) -> Response: + return JSONResponse( + ConfigResponse(frameOrigin=config.frame_origin, apiBase=config.api_base).model_dump() + ) + + async def create_session(request: Request) -> Response: + org = await _resolve(config, request) + session = await client.mint_session(org) + return JSONResponse(session.model_dump()) + + async def list_catalog(request: Request) -> Response: + await _resolve(config, request) + kind = _require_kind(request.query_params.get("kind")) + types = await client.list_catalog(kind, config.catalog_allow) + return JSONResponse([t.model_dump() for t in types]) + + async def list_connectors(request: Request) -> Response: + org = await _resolve(config, request) + kind = _require_kind(request.query_params.get("kind")) + rows = await client.list_connectors(org, kind) + return JSONResponse([r.model_dump() for r in rows]) + + async def build_ingress(request: Request) -> Response: + org = await _resolve(config, request) + body = await _json_body(request) + input_id = _require_str(body, "inputId") + name = _require_str(body, "name") + prov = await _provision(config, org) + if prov.destination_output_id: + built = await client.wire_pipeline(org, input_id, prov.destination_output_id, name) + else: + built = await client.build_dev_null(org, input_id, name) + return JSONResponse(status_code=201, content=built.model_dump()) + + async def build_egress(request: Request) -> Response: + org = await _resolve(config, request) + body = await _json_body(request) + output_id = _require_str(body, "outputId") + name = _require_str(body, "name") + prov = await _provision(config, org) + if not prov.source_input_id: + raise EmbedError( + 500, + "internal_error", + "No source input is provisioned for this tenant; egress cannot be built.", + ) + built = await client.wire_pipeline(org, prov.source_input_id, output_id, name) + return JSONResponse(status_code=201, content=built.model_dump()) + + async def get_pipeline_status(request: Request) -> Response: + org = await _resolve(config, request) + connector_id = request.query_params.get("connectorId") + if not connector_id: + raise EmbedError(400, "invalid_request", "Query 'connectorId' is required.") + kind = _require_kind(request.query_params.get("kind")) + status = await client.pipeline_for(org, kind, connector_id) + return JSONResponse(status.model_dump(exclude_none=True)) + + async def set_pipeline_state(request: Request) -> Response: + org = await _resolve(config, request) + body = await _json_body(request) + pipeline_id = _require_str(body, "pipelineId") + enabled = body.get("enabled") if isinstance(body, dict) else None + if not isinstance(enabled, bool): + raise EmbedError(400, "invalid_request", "Field 'enabled' must be a boolean.") + await client.set_enabled(org, pipeline_id, enabled) + return Response(status_code=204) + + async def remove_integration(request: Request) -> Response: + org = await _resolve(config, request) + body = await _json_body(request) + connector_id = _require_str(body, "connectorId") + kind = _require_kind(body.get("kind") if isinstance(body, dict) else None) + + status = await client.pipeline_for(org, kind, connector_id) + # The pipeline references its connectors, so it goes first. + if status.pipelineId: + await client.delete(f"/v2/{_seg(org)}/pipelines/{_seg(status.pipelineId)}") + + if kind == "input": + await client.delete(f"/v1/{_seg(org)}/inputs/{_seg(connector_id)}") + # The tenant's provisioned store is shared; only a sink this + # pipeline created on the fly gets torn down with it. + prov = await _provision(config, org) + keep_store = bool( + prov.destination_output_id + and prov.destination_output_id == status.outputId + ) + if status.outputId and not keep_store: + await client.delete(f"/v1/{_seg(org)}/outputs/{_seg(status.outputId)}") + else: + # Keep the shared source input; remove only the user's output. + await client.delete(f"/v1/{_seg(org)}/outputs/{_seg(connector_id)}") + return Response(status_code=204) + + router.add_api_route("/config", _guard(get_config), methods=["GET"]) + router.add_api_route("/session", _guard(create_session), methods=["POST"]) + router.add_api_route("/catalog", _guard(list_catalog), methods=["GET"]) + router.add_api_route("/connectors", _guard(list_connectors), methods=["GET"]) + router.add_api_route("/pipelines/ingress", _guard(build_ingress), methods=["POST"]) + router.add_api_route("/pipelines/egress", _guard(build_egress), methods=["POST"]) + router.add_api_route("/pipelines", _guard(get_pipeline_status), methods=["GET"]) + router.add_api_route("/pipelines/state", _guard(set_pipeline_state), methods=["POST"]) + router.add_api_route("/pipelines/remove", _guard(remove_integration), methods=["POST"]) + return router diff --git a/routers/python/pyproject.toml b/routers/python/pyproject.toml new file mode 100644 index 0000000..772a589 --- /dev/null +++ b/routers/python/pyproject.toml @@ -0,0 +1,22 @@ +[project] +name = "monad-embed" +version = "0.1.0" +description = "Mountable /embed backend router (FastAPI) for a Monad embed integration." +readme = "README.md" +requires-python = ">=3.10" +license = { text = "Apache-2.0" } +authors = [{ name = "Monad Inc." }] +dependencies = ["fastapi>=0.110", "httpx>=0.27"] + +[project.optional-dependencies] +test = ["pytest>=8"] + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.hatch.build.targets.wheel] +packages = ["monad_embed"] + +[tool.pytest.ini_options] +testpaths = ["tests"] diff --git a/routers/python/tests/test_router.py b/routers/python/tests/test_router.py new file mode 100644 index 0000000..7e47def --- /dev/null +++ b/routers/python/tests/test_router.py @@ -0,0 +1,129 @@ +import httpx +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from monad_embed import EmbedConfig, MonadClient, Provision, embed_router + + +def _monad_handler(request: httpx.Request) -> httpx.Response: + """Stands in for the Monad API — just the endpoints these tests hit.""" + m, p = request.method, request.url.path + if m == "POST" and p == "/v3/sessions": + return httpx.Response(200, json={"session_token": "tok", "expires_at": "2026-01-01T00:00:00Z"}) + if m == "GET" and p == "/v1/inputs": + return httpx.Response( + 200, + json=[ + {"type_id": "aws-cloudtrail", "name": "AWS"}, + {"type_id": "secret", "name": "Hidden"}, + ], + ) + if m == "POST" and p == "/v2/org_1/outputs": + return httpx.Response(200, json={"id": "out_devnull"}) + if m == "POST" and p == "/v2/org_1/pipelines/": + return httpx.Response(200, json={"id": "pipe_1"}) + if m == "GET" and p == "/v2/org_1/pipelines/pipe_1/status": + return httpx.Response(200, json={"status": "Running"}) + return httpx.Response(500, json={"error": f"unmocked {m} {p}"}) + + +def make_client(over=None, resolve=lambda req: "org_1") -> TestClient: + cfg = EmbedConfig( + api_key="k", + api_base="http://monad", + frame_origin="https://app.monad.com/embed", + get_customer_org_id=resolve, + ) + if over: + over(cfg) + mc = MonadClient("k", "http://monad", transport=httpx.MockTransport(_monad_handler)) + app = FastAPI() + app.include_router(embed_router(cfg, monad_client=mc), prefix="/embed") + return TestClient(app) + + +def test_get_config(): + res = make_client(resolve=lambda req: (_ for _ in ()).throw(AssertionError("no auth"))).get( + "/embed/config" + ) + assert res.status_code == 200 + assert res.json() == {"frameOrigin": "https://app.monad.com/embed", "apiBase": "http://monad"} + + +def test_config_defaults(): + # api_base + frame_origin omitted → production defaults. + cfg = EmbedConfig(api_key="k", get_customer_org_id=lambda req: "org_1") + app = FastAPI() + app.include_router(embed_router(cfg), prefix="/embed") + res = TestClient(app).get("/embed/config") + assert res.json() == { + "frameOrigin": "https://app.monad.com/embed", + "apiBase": "https://app.monad.com/api", + } + + +def test_session(): + res = make_client().post("/embed/session") + assert res.status_code == 200 + assert res.json() == { + "sessionToken": "tok", + "organizationId": "org_1", + "expiresAt": "2026-01-01T00:00:00Z", + } + + +def test_catalog_allow_list(): + res = make_client(over=lambda c: setattr(c, "catalog_allow", ["aws-cloudtrail"])).get( + "/embed/catalog?kind=input" + ) + assert res.status_code == 200 + assert res.json() == [{"typeId": "aws-cloudtrail", "name": "AWS"}] + + +def test_ingress_dev_null(): + res = make_client().post("/embed/pipelines/ingress", json={"inputId": "in_1", "name": "CT"}) + assert res.status_code == 201 + body = res.json() + assert body["outputId"] == "out_devnull" + assert body["active"] is True + + +def test_ingress_store(): + res = make_client(over=lambda c: setattr(c, "get_provisioned_components", lambda org: Provision(destination_output_id="out_store"))).post( + "/embed/pipelines/ingress", json={"inputId": "in_1", "name": "CT"} + ) + assert res.status_code == 201 + assert res.json()["outputId"] == "out_store" + + +def test_egress_without_source_500s(): + res = make_client().post("/embed/pipelines/egress", json={"outputId": "out_1", "name": "Splunk"}) + assert res.status_code == 500 + assert res.json()["code"] == "internal_error" + + +def test_unauthenticated(): + res = make_client(resolve=lambda req: "").post("/embed/session") + assert res.status_code == 401 + assert res.json()["code"] == "unauthenticated" + + +def test_invalid_kind(): + res = make_client().get("/embed/catalog?kind=nope") + assert res.status_code == 400 + assert res.json()["code"] == "invalid_request" + + +def test_missing_body_field(): + res = make_client().post("/embed/pipelines/ingress", json={"name": "x"}) + assert res.status_code == 400 + + +def test_not_found(): + res = make_client().get("/embed/nope") + assert res.status_code == 404 + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-q"]))