Amoeba

mcp
Security Audit
Warn
Health Warn
  • License — License: MIT
  • Description — Repository has a description
  • Active repo — Last push 0 days ago
  • Low visibility — Only 5 GitHub stars
Code Pass
  • Code scan — Scanned 12 files during light audit, no dangerous patterns found
Permissions Pass
  • Permissions — No dangerous permissions requested

No AI report is available for this listing yet.

SUMMARY

Let AI build and deploy your internal apps, safely. One binary, no Kubernetes, idle apps cost nothing.

README.md
Amoeba logo

Amoeba

Let AI build and deploy your internal apps, safely. One binary, no Kubernetes, idle apps cost nothing.

Amoeba is a self-hosted gateway between AI and your systems. It lets agents use your internal systems without ever holding their secrets, and lets you deploy apps that Claude, ChatGPT, or Gemini built the moment they are ready.

New: amoeba-mcp — an MCP server that lets AI agents (Claude, ChatGPT, Gemini) deploy and manage microservices on Amoeba.

Describing an app for Amoeba? See the amoeba.yaml manifest reference and its JSON Schema.

Quick start

One command, on any machine with Docker:

curl -fsSL https://raw.githubusercontent.com/dickyj-grc/Amoeba/main/docker-compose.quickstart.yml | docker compose -p amoeba -f - up -d

Open http://localhost:8080 and sign in as admin. The first run creates that user with a random password and prints it once:

docker logs amoeba 2>&1 | grep password

Deploying the hello-world app from the Amoeba console: pick it from the App library, it starts on demand, and answers at /v1/hello-world behind a login
Deploy from the App library, start on demand, call it behind a login. Sharper MP4.

From the console, deploy an app from the App library, a Docker image, a Git repo or a Dockerfile. Stop everything with docker compose -p amoeba down (add -v to delete its data too). For TLS and a public hostname, see Deployment; to work on Amoeba itself, see Run Locally.

About the Docker socket. The quick start mounts /var/run/docker.sock so Amoeba can start and stop your apps as sibling containers. Access to that socket is equivalent to root on the host, so treat the Amoeba container as a privileged component: run it on a host or VM dedicated to Amoeba and its apps, keep the console off the public internet unless it is behind TLS (see Deployment), and consider rootless Docker. A Docker socket proxy can narrow the API Amoeba reaches, as long as it still allows containers, images and networks.

Highlights

Claude deploys the app it just wrote

Connect amoeba-mcp to Claude, ChatGPT or Gemini, and the assistant that wrote an app deploys it itself:

  1. It calls deploy_service with a Dockerfile, a source tarball or an image.
  2. amoeba-mcp builds the image on the Amoeba host, and Amoeba starts it at /v1/<app>/ behind a login. With a cooldown set, it sleeps when idle.
  3. If the build or start fails, the assistant reads get_build_logs or get_runtime_logs, fixes the code and deploys again.

No DNS record, TLS certificate, reverse-proxy rule or port to pick. Who may call the app is a role list you can change in the console.

Agents query your database and see only what their role allows

The database service lets agents use PostgreSQL without the password and without writing SQL. Callers run only approved queries and tables, and each column is shown, masked or hidden per role, in the SQL itself:

Caller's role GET /v1/finance-db/tables/customers/1 returns
cs_agent id, name, nik: "************8901"
compliance every column, nik in full, balance
a role not granted the table 403, and no row is read

Every approved query and table is also an MCP tool, and an agent is shown only the tools its roles may use.

How Amoeba compares

These projects overlap with parts of Amoeba, and each is the better choice for some jobs. Compared from each project's own documentation in November 2026; if something here is wrong or out of date, please open an issue.

Amoeba Docker MCP Gateway Obot agentgateway Sablier
What it is Gateway that runs your apps and MCP servers Docker CLI plugin that runs catalog MCP servers MCP platform: catalog, hosting, chat Proxy for MCP, A2A and LLM traffic Scale-to-zero add-on for reverse proxies
Language, license Rust, MIT Go, MIT Go, MIT Rust, Apache-2.0 Go, AGPL-3.0
Runs the workloads Yes, Docker or Apple containers Yes, MCP servers as containers Yes, MCP servers on Docker or Kubernetes No, proxies servers that already run Starts and stops containers you define
Deploys any HTTP app, from an image, Git or Dockerfile Yes No, MCP servers only No, MCP servers only No No
Stops idle workloads Yes, per-service cooldown Starts servers on demand Not documented for hosted servers No Yes, its main job
Who may call what Roles per operation, per organization, on every request OAuth to the services it calls; per-user access, policy and audit are in Docker's paid Enterprise Gateway Per user and group, per server and tool JWT and fine-grained RBAC None; leave it to the proxy
Keeps backend credentials from callers Yes, injected at the gateway Secrets mounted into the server container Yes, managed credentials and OAuth Yes, backend auth policies No
Database access with per-role column masking Yes No No No No
AI deploys apps itself Yes, amoeba-mcp Adds catalog servers on request No No No
Production setup One binary or container Docker Desktop or Docker Engine Kubernetes recommended One binary, or Kubernetes Next to Traefik, Caddy, Nginx and others

When to pick something else:

  • Docker MCP Gateway, if you want catalog MCP servers on your own machine through Docker Desktop, with signed images and secret scanning.
  • Obot, for an organization-wide MCP catalog with SSO groups, a chat client and Kubernetes hosting.
  • agentgateway, for a high-throughput proxy in front of agents and LLM providers that already run elsewhere, especially on Kubernetes.
  • Sablier, if you only want idle containers to sleep behind the reverse proxy you already use.

Amoeba is younger than these and has known limits: one machine per instance, PostgreSQL only for the database service, and plain HTTP from the gateway to the app (see Status).

What Amoeba Does

Amoeba does two jobs, and both go through the same gateway.

Job 1: Expose internal systems to agents, without exposing their secrets

AI agents are quick to create and hard to let near real systems. Each one needs an answer to "who may call this, with which key, and what does it cost to keep running?" before a security team will approve it.

Amoeba sits in front of every service at /v1/<service>/... and answers three questions on each request:

Question How Amoeba answers it
Who is calling, and may they? Verifies the caller's JWT (issued locally, or by your identity provider through JWKS), names the operation from the HTTP method and path, and checks the caller's roles for that operation, per organization if needed. A denied request never wakes the service.
With what credential? Strips the caller's token and attaches the backend's own key. Callers hold only a personal token that can be revoked; they never see the backend credential.
Is the service awake? Cold-boots the container on the first request, keeps it up while connections (including long streams) are live, and stops it after a cooldown.

Every request is logged with the caller, organization, service, operation, status, and latency.

agent ──(personal JWT)──►  Amoeba  ──(backend's own key)──►  service
                             │
                             ├─ verify token, resolve operation, check roles
                             ├─ start the container if it is asleep
                             └─ log who called what

For databases, the database service goes one step further: agents run only approved queries and table operations, and see only the columns their roles allow.

Job 2: Deploy apps that AI built, straight away

Ask Claude, ChatGPT, or Gemini to build a small app, and it can be running on Amoeba a few minutes later, as a Docker container, behind a login, at its own path.

  • From the AI itself: with amoeba-mcp connected, the assistant that wrote the app deploys it with one tool call (deploy_service), from a Dockerfile, a source tarball, or an image. It can then read the build and runtime logs and fix what broke.
  • From the web console: pick a ready-made app from the App library (its image, start command, port and API come set up, with no build), or paste a Dockerfile, point at a Git repo, or enter an image. Amoeba builds the image on its own host when needed and deploys it.
  • No platform work per app: no DNS record, TLS certificate, reverse-proxy rule, or port to pick. The app is reachable at /v1/<app>/, sleeps when idle, and gets its secrets from Amoeba instead of from its code.

Why they belong together

An AI-built app is usually built to do something with your systems: read a report, update a ticket, query a database. On Amoeba it sits behind the same access control as everything else, and it calls your internal systems through the gateway, so the app never needs their passwords either. Only people and agents with the right roles can use it.

Who It Is For

  • Teams running MCP tool servers that need per-tool access control and do not want every server running all day.
  • Teams letting Claude, ChatGPT, or Gemini build small apps who need somewhere safe to run them the same day (job 2).
  • Security and data teams asked to give agents access to internal systems and databases without handing out credentials (job 1).
  • Anyone putting an open-source tool behind a login when the tool ships with no authentication of its own.
  • Home labs and small VMs that want many services on one machine without paying for idle containers.

Why Amoeba?

1. Access Control for Agents and Services

Amoeba enforces JWT-based access control in front of any HTTP service without modifying the service.

  • Every service gets role-based permissions. Operations default to read, add, update, and delete by HTTP method, and path rules let you name finer ones such as loans.create (see section 4).
  • Permissions can differ per organization, so one service can serve several tenants with separate role maps.
  • Local HMAC mode bootstraps users from a simple JSON file. JWKS mode plugs into a corporate identity provider, so agents and people use the logins you already manage.
  • The verified user, organization, and roles are forwarded to the service as x-amoeba-user, x-amoeba-org, and x-amoeba-roles. Copies sent by the client are stripped.

2. Backend Credentials Stay at the Gateway

Amoeba keeps sensitive material out of callers' hands, compose files, and config.

  • upstream_auth replaces the caller's JWT with a backend-specific static token or custom header before forwarding.
  • env_from_secret injects secrets from a protected directory at container-start time. header_from_secret keeps a secret on the gateway and sends it to the service per request.
  • A configured credential that cannot be produced fails closed with 503, so a request is never forwarded with an empty key.
  • App packages can carry secrets encrypted with age.

3. Cut Energy and Infrastructure Costs

Amoeba's scale-to-zero lifecycle means workloads are only running when they are actually being used.

  • Local machines: a home lab or workstation no longer has to keep every container — GPU models, scrapers, databases, dashboards — idling 24/7. Services cold-boot on demand and stop after a configurable cooldown, directly reducing power draw and fan noise.
  • Cloud VMs: because containers are started only when requested, a single VM can host far more services than it could if everything were always-on. You pay for compute only when it is being used, and you can pack more workloads onto smaller instances.
  • Scale-to-zero is optional per service. An always-on, stateful app can sit behind Amoeba for access control and credential injection alone.

4. Protect Machine Resources With Declared Capacity Budgets

Instead of guessing whether a machine can handle another workload, Amoeba enforces declared CPU, memory, and GPU-VRAM budgets before admitting a request that would cold-start a service.

  • Services declare their footprint in services.json.
  • Amoeba sums currently-occupying siblings and rejects the request with 503 if the new workload would exceed the budget.
  • This lets you safely pack more services onto the same box without accidentally starving the GPU or RAM.

5. Built-In Usage Metering and Auditability

Every proxied request emits a telemetry log containing the caller, organization, service, operation, status code, and latency.

  • No extra observability tooling is required to answer "who called what and when."
  • A backend that only knows one shared service account still gets a per-person and per-agent trail at the gateway.
  • The same logs form the basis for chargeback, debugging, and security auditing.

6. Deploy New Apps Without Subdomain or SSL Plumbing

Adding a containerized app usually means DNS records, reverse-proxy rules, TLS certificates, and port management. Amoeba removes that toil:

  • New services are reached via /v1/<service_name>/<subpath>; no custom subdomain is required.
  • The edge proxy (Caddy, Traefik, etc.) handles SSL termination once for the whole gateway.
  • Adding or removing an app is a single entry in services.json; Amoeba hot-reloads it without a restart.
  • The web console and the MCP server can build an image from a Git repo or a Dockerfile and deploy it in one step.

7. Safe Defaults for AI-Built Apps

An app an AI just wrote runs confined, so a security team can approve one-shot deploys.

  • The gateway is the only way in. Each app has a network shared only with the gateway, and requests carry a signed caller identity (x-amoeba-identity) apps can verify, so one app cannot reach another directly or pose as a different caller.
  • A sandbox by default: read-only root filesystem, no Linux capabilities, no root user, no outbound network, and limits on processes and memory. Each relaxes per app in its manifest (sandbox).
  • MCP tools under control: permissions per tool ("analysts may search invoices, only admins delete them"), and a tool whose description changes after approval is blocked until an admin approves it again.
  • Rate limits on failed sign-ins and on each caller's requests to each service.

8. Minimal, Self-Hosted, and Portable

Amoeba is designed for environments where you want control without operational overhead, including ones where data may not leave your own servers.

  • The release image is a small static binary; no Kubernetes or managed control plane is required.
  • Works with Docker on Linux/Windows and Apple's native container CLI on macOS/Apple Silicon.
  • Each machine runs its own instance with its own config, so scaling out is as simple as adding another box.

Status

Area State
JWT auth (local HMAC and JWKS), roles, per-organization permissions Shipped
Operation rules by HTTP method and by path Shipped
Verified identity headers (x-amoeba-user, x-amoeba-org, x-amoeba-roles) Shipped
Upstream credential injection, fail-closed Shipped
Gateway-only access: a network per app, a signed caller identity (x-amoeba-identity) apps can verify Shipped
Sandbox for AI-built apps: read-only root, no capabilities, non-root, no egress, process and memory limits Shipped
MCP: per-tool permissions, pinned tool lists, OAuth Protected Resource Metadata Shipped
Built-in OAuth server: add one URL to ChatGPT or Claude, sign in, done; per-service tokens, connected-apps view Shipped
Rate limits on sign-ins and per caller per service Shipped
Scale-to-zero for single containers and compose stacks, capacity budgets Shipped
Zero-idle tool hub (/mcp/hub): search every app's tools without starting any; only call_tool wakes an app Shipped
Task-aware scale-to-zero: an MCP app with a task in flight is never stopped, so idle costs nothing and no task is dropped Shipped
Streaming responses (SSE, Streamable HTTP for MCP) Shipped
WebSockets, e.g. Playwright or Puppeteer driving a hosted browser over CDP Shipped
App packages, web console deploys, source builds, amoeba-mcp Shipped
Database service (PostgreSQL): approved queries, table CRUD, column masking, MCP tools Shipped
Pluggable secret backends (Vault, HTTP provider) Planned
External upstreams: services Amoeba does not start itself, HTTPS to the upstream Planned

Current limits: every service must be a container or compose stack that Amoeba starts; the hop from Amoeba to the service is plain http:// on a private network; request bodies are capped at 10 MB.

Roadmap

The goal: AI agents and AI-built apps can use any internal system or external API through Amoeba, and no code they write or run ever holds a production credential.

Phase What it delivers State
1. Gateway foundations Requests fail closed when a backend credential is missing; path-based operation rules (loans.create); verified roles forwarded as x-amoeba-roles Done
2. Database service Approved queries and table CRUD over PostgreSQL; show/mask/hide columns per role; read-only reads, row caps with rollback, org scoping, audit; MCP tools filtered by role (section 8) Done, except idempotency keys on creates
3. Secret providers Pluggable secret sources behind one interface: files (today), environment, HashiCorp Vault, and an HTTP provider that fetches by reference with a short cache and fails closed Planned
4. Egress: external upstreams A service that is just an HTTPS URL (Stripe, a CRM, another server), with no container. Amoeba checks the caller, injects the real API key, and logs the call, so AI-built apps can use any API without holding its key Planned

Other databases (SQL Server, Oracle) would need their own work in phase 2.

Ideas being explored (not scheduled; open an issue if you need one):

  • Pre-warming: start a service ahead of known demand, on a schedule or a learned pattern, so the first call of the day does not wait for a cold boot.
  • stdio MCP servers as HTTP: run an MCP server that only speaks stdio behind Amoeba without a separate bridge, so any MCP server on GitHub can be hosted.
  • Compose stacks from amoeba-mcp: let deploy_service take a compose file, so an assistant can deploy a multi-container app in one call.

Run Locally

To try Amoeba, use the quick start. To work on Amoeba itself, run it from a checkout with live code changes:

git clone https://github.com/dickyj-grc/Amoeba.git && cd Amoeba
scripts/dev.sh
  API:      http://localhost:8064
  Console:  http://localhost:3064
  User:     admin
  Password: <printed on first run>

On first run it creates .env with a random JWT secret, an empty service catalog, and an admin user. It prints that user's password, which is also saved in the mode's state directory as .dev-admin-password. The console stays in the foreground; Ctrl-C stops it, and the API keeps running.

The script picks a mode for your machine:

Mode When How apps run State
native macOS with Apple's container CLI and a Rust toolchain Amoeba runs as a native binary; each app is an Apple container micro-VM. No Docker Desktop VM, no x86 emulation. .dev/native/
docker everywhere else The orchestrator runs in Docker Compose and starts apps as Docker containers. config/

Compose-based apps (such as the Obscura and streaming-echo examples) need Docker, so use --docker for those even on a Mac.

Command Does
scripts/dev.sh --down Stop the API and the app containers it started
scripts/dev.sh --no-console Start only the API
scripts/dev.sh --reset-admin Give admin a new random password
scripts/dev.sh --docker / --native Override the mode
scripts/dev.sh --build Docker mode: build the image from your checkout instead of pulling ghcr.io/dickyj-grc/amoeba:latest (amd64 only, emulated on Apple Silicon)

Logs are in .dev/native/amoeba.log (native) or docker logs -f amoeba-orchestrator (docker). To try it, sign in to the console and deploy an image, or install an app package with the admin API (7.2) using a token from POST /auth/login. Those examples use the server's default port 8080; under scripts/dev.sh use localhost:8064.

For a production setup with Caddy and TLS, see 5. Deployment.


1. System Architecture Overview

The system follows a two-tier architecture: Edge Reverse Proxy Layer (public-facing) and Compute Orchestrator Layer (internal control plane).

                                  [ PUBLIC INTERNET ]
                                           │
                                           │ Port 80 / 443
                                           ▼
                       ┌───────────────────────────────────────┐
                       │   EDGE PROXY (Caddy / Traefik / etc)  │
                       │   - Public SSL/TLS Termination    │
                       │   - Domain & Subdomain Handling       │
                       └───────────────────┬───────────────────┘
                                           │
                                           │ Loopback / Private Subnet (Port 8080)
                                           ▼
┌───────────────────────────────────────────────────────────────────────────────────────────┐
│                           Amoeba COMPUTE ENGINE (Axum Proxy)                            │
│                                                                                           │
│   ┌───────────────────────────┐  ┌──────────────────────────┐  ┌──────────────────────┐   │
│   │ Unified Auth & Claims     │  │  Capacity & Concurrency  │  │ Usage Metering &     │   │
│   │ (Local HMAC / Remote JWKS)│  │  Limiter (Semaphore)     │  │ Telemetry Extractor  │   │
│   └─────────────┬─────────────┘  └────────────┬─────────────┘  └──────────┬───────────┘   │
│                 │                             │                           │               │
│                 └─────────────────────────────┼───────────────────────────┘               │
│                                               ▼                                           │
│                            ┌─────────────────────────────────────┐                        │
│                            │   Container Lifecycle Manager       │                        │
│                            │   - Cold-boot trigger (<400ms)      │                        │
│                            │   - Active Connection Counter       │                        │
│                            │   - Lock-free ArcSwap Config Engine │                        │
│                            └──────────────────┬──────────────────┘                        │
└───────────────────────────────────────────────┼───────────────────────────────────────────┘
                                                │
                          ┌─────────────────────┴─────────────────────┐
                          │                                           │
                          ▼                                           ▼
          ┌───────────────────────────────┐           ┌───────────────────────────────┐
          │     Scale-to-Zero Workers     │           │    Warm Stateful Services     │
          │   (Gemma 4, Obscura, Docling) │           │     (Metabase, Postgres)      │
          │  - Dynamic start/stop         │           │  - Always running             │
          │  - Token injection/translation│           │  - Telemetry & Auth gated     │
          └───────────────────────────────┘           └───────────────────────────────┘

2. Dynamic Routing & Services Specification

Services are defined declaratively in /etc/amoeba/services.json. The orchestrator watches this file at runtime, executing lock-free atomic memory pointer swaps (ArcSwap) via notify kernel events without process restarts.

2.1 Configuration Schema (services.json)

Every service declares where it's reached (placement) and how Amoeba drives its container lifecycle — exactly one of container (a single image Amoeba starts/stops directly) or stack_spec (a multi-container stack driven through the docker compose CLI):

{
  "version": 1,
  "machines": {
    "local": { "type": "vm", "drivers": ["docker"], "resources": { "memory": "16Gi" } }
  },
  "services": {
    "gemma4": {
      "placement": { "type": "vm", "ip": "gemma4", "port": 11434, "cooldown_seconds": 180 },
      "container": {
        "image": "ollama/ollama:latest",
        "resources": { "limits": { "memory": "8Gi" } }
      },
      "operation_rules": [
        { "operation": "read", "match_type": "http_method", "values": ["GET", "HEAD"] },
        { "operation": "execute", "match_type": "http_method", "values": ["POST"] }
      ],
      "permissions": {
        "read": ["admin", "analyst", "viewer"],
        "execute": ["admin", "analyst"]
      },
      "upstream_auth": null
    },
    "docling": {
      "placement": { "type": "vm", "ip": "docling", "port": 5000, "cooldown_seconds": 120 },
      "container": { "image": "ds4sd/docling-serve:latest" },
      "permissions": {
        "read": ["admin", "analyst"],
        "add": ["admin", "analyst"]
      },
      "upstream_auth": {
        "type": "bearer_static",
        "token_env_var": "INTERNAL_DOCLING_KEY"
      }
    }
  }
}

machines and placement.machine can be omitted while there's only ever one machine — it's implied. They become required fields once a second machine exists (see 2.4).

public (optional, defaults to false) — set "public": true on a service to skip JWT verification and the permission check entirely for it. This is an explicit opt-in: a service with permissions omitted or empty is not public by default — it still requires a valid token, it just denies every role (fails closed with 403) until you add roles to permissions. Only use public: true for endpoints that are genuinely meant to be reachable with no auth at all (e.g. a health check or webhook receiver).

2.2 Workload Types: container vs. stack_spec

A service is exactly one of two shapes — validated at load time (both startup and hot-reload), rejecting a service that sets both or neither:

container — a single image. Amoeba owns the full lifecycle directly via the Docker Engine API (create/start on cold boot, stop on cooldown). placement.ip is both the upstream host and the name Amoeba creates the container under, attached to the shared Docker network (AMOEBA_DOCKER_NETWORK, default amoeba-net) so it's reachable by name from Amoeba's own container.

stack_spec — a multi-container stack, driven through the docker compose CLI instead. placement.primary_service names which container in the stack the gateway routes to. Exactly one of:

  • compose_file — a path to a docker-compose file a human already wrote (e.g. a vendored product stack). Amoeba never re-derives it; it just runs docker compose -f <file> -p <project_name> {up -d|start|stop} against it.
  • services — an inline, Amoeba-authored stack (no file exists yet). Amoeba regenerates an equivalent compose file on disk before every start, then drives it through the identical CLI path. Every network a service references defaults to external: true (must already exist — e.g. a network shared with Amoeba's own container) unless stack_spec.networks explicitly marks it {"external": false} to have this stack create it fresh.

project_name defaults to the service's own key when omitted. A cooldown on a stack_spec service always means stop, not down — containers/networks stick around so the next activation is a fast start rather than a full up -d reconciliation.

{
  "gorules": {
    "placement": { "type": "vm", "cooldown_seconds": 1800, "primary_service": "gorules", "port": 80 },
    "stack_spec": {
      "compose_file": "/etc/amoeba/stacks/gorules/docker-compose.yml",
      "project_name": "gorules"
    },
    "permissions": { "read": ["admin", "analyst"] },
    "env_from_secret": { "DB_PASSWORD": "gorules/db_password" },
    "upstream_auth": null
  },
  "brms": {
    "placement": { "type": "vm", "cooldown_seconds": 1800, "primary_service": "brms", "port": 3000 },
    "stack_spec": {
      "compose_version": "3.8",
      "env_vars": { "LOG_LEVEL": "info" },
      "services": {
        "brms": {
          "image": "gorules/brms:latest",
          "container_name": "gorules-brms",
          "ports": ["3000"],
          "depends_on": ["postgres"],
          "networks": ["gorules_network", "proxy-network"]
        },
        "postgres": {
          "image": "postgres:18.4",
          "container_name": "gorules-postgres",
          "networks": ["gorules_network"]
        }
      }
    },
    "permissions": { "read": ["admin", "analyst"] },
    "env_from_secret": { "DB_PASSWORD": "brms/db_password" },
    "upstream_auth": null
  }
}

See config/services.local.example.json for these two alongside a container service (gemma4) in one file — the three local-machine scenarios Amoeba supports today.

env_from_secret (optional) — env var name -> "<service>/<key>", resolved fresh at every start from <AMOEBA_SECRETS_DIR, default /etc/amoeba/secrets>/<service>/<key> and injected directly into the container/compose-subprocess environment. Never written into Amoeba's own config or a generated compose file — a referenced compose file needs to consume it via normal Compose variable interpolation (${DB_PASSWORD}) or the environment: [DB_PASSWORD] passthrough shorthand.

2.3 A Second container Backend: apple-container (macOS/Apple Silicon)

A machine's drivers list picks which backend drives its container-workload services. drivers: ["docker"] (the default assumed throughout this doc) talks to the Docker Engine API. drivers: ["apple-container"] instead shells out to Apple's native container CLI — one lightweight Linux micro-VM per container via Containerization + Virtualization.framework, with sub-second boots and no Docker Desktop/OrbStack VM overhead. It accepts ordinary Docker image references (ollama/ollama:latest resolves to docker.io/library/... exactly like the Docker CLI) and requires container system start to have been run once beforehand.

{
  "version": 1,
  "machines": {
    "local": { "type": "vm", "drivers": ["apple-container"], "resources": { "memory": "16Gi" } }
  },
  "services": {
    "gemma4": {
      "placement": { "type": "vm", "port": 11434, "cooldown_seconds": 180 },
      "container": {
        "image": "ollama/ollama:latest",
        "resources": { "limits": { "memory": "8Gi" } }
      },
      "permissions": { "read": ["admin", "analyst"] },
      "upstream_auth": null
    }
  }
}

See config/services.applecontainer.example.json. Note what's missing: placement.ip is omitted, and validation requires it stay that way for a container workload on an apple-container machine. Apple's container tool assigns each container a fresh IP on every start (confirmed by hand: stopping and restarting the same container moved it from 192.168.64.2 to 192.168.64.3), and — unlike a Docker container on a shared bridge network — the bare macOS process running Amoeba can't resolve it by name; there's no DNS between the host and a container-managed VM. So the upstream host isn't a static config value here: Amoeba resolves it dynamically after every cold-boot (container inspect) and caches it in memory for warm requests to reuse, re-resolving again the next time the service cold-boots.

To try this on a Mac without writing the catalog yourself, run scripts/dev.sh (see Run Locally); it picks this driver automatically.

stack_spec (2.2) has no apple-container equivalent yet — Apple's CLI has no compose-like multi-container orchestration today, so multi-container stacks always go through docker compose regardless of a machine's drivers.

2.4 Machine Capacity Gating (optional)

Rather than have the orchestrator introspect the host's real CPU/memory (which doesn't work consistently across bare metal, Docker cgroup limits, and serverless sandboxes like RunPod/Modal — and can't see GPU/VRAM at all), operators declare a capacity budget per machine, and the orchestrator checks declared usage against it before admitting a request that would newly activate a service. No runtime introspection, no platform-specific behavior.

{
  "version": 1,
  "machines": {
    "gpu-box-1": { "type": "vm", "drivers": ["docker"], "resources": { "memory": "32Gi", "gpu_vram": "24Gi" } }
  },
  "services": {
    "gemma4": {
      "placement": {
        "type": "vm", "ip": "gpu-box-1-gemma4", "port": 11434, "cooldown_seconds": 180, "machine": "gpu-box-1"
      },
      "container": {
        "image": "ollama/ollama:latest",
        "resources": { "limits": { "memory": "16Gi", "gpu_vram": "16Gi" } }
      },
      "permissions": { "read": ["admin", "analyst"] }
    }
  }
}

See config/services.capacity.example.json for a fuller example with multiple services sharing one machine.

  • placement.machine — the entry in the top-level machines map this service's usage counts against. Optional only while machines has exactly one entry (implied); referencing an undefined machine, or omitting it once a second machine exists, fails config validation (both at startup and on hot-reload) rather than silently skipping the gate or picking one arbitrarily.
  • Quantities (memory, gpu_vram on both a machine's resources and a container's resources.limits) accept Kubernetes-style sized strings ("16Gi", "512Mi") or a bare number (interpreted as MB). cpu_cores is always a bare count. Every field is independently opt-in: a field missing from a container's resources.limits means it requests zero of that dimension (never competes for or is blocked by that budget line); a field missing from a machine's budget means that dimension is completely unconstrained. Omitting resources entirely (or using a stack_spec workload, which never declares one) means the service requests nothing on any dimension — it's nominally "on" the machine but exempt from capacity accounting.
  • On exceeding budget: the request is rejected with 503 Service Unavailable before any upstream call is attempted. No queueing — retry later.
  • Resource usage is per-service, not per-request: a container's resources.limits represents its footprint while running. N concurrent calls to an already-warm service still count as one instance of its declared resources, not N×. Once a service is warm (within its cooldown_seconds window, or always-on when cooldown_seconds is omitted), further requests to it aren't re-checked against the budget — only the request that newly activates a cold service is gated, and only that same moment triggers the driver's cold-boot (2.2) too.

2.5 Subpath Mapping Protocol

Routing does not require unique DNS subdomains. Any service is reachable via path parameters:

$$\text{Target URL} = \texttt{https:///v1/<service_name>/}$$

Incoming Request Target Extracted service_name Extracted subpath Upstream Proxy Destination
POST /v1/gemma4/v1/chat/completions gemma4 v1/chat/completions [http://gemma4:11434/v1/chat/completions](http://gemma4:11434/v1/chat/completions)
POST /v1/docling/api/v1/parse docling api/v1/parse [http://docling:5000/api/v1/parse](http://docling:5000/api/v1/parse)

3. Dual Auth Mode: Local vs. Amoeba Identity Provider

The orchestrator abstracts token verification into a single JwtEngine. The engine operates either in Offline/Local Mode or Cloud/Amoeba OIDC Mode based on /etc/amoeba/config.toml.

# /etc/amoeba/config.toml

[server]
bind_addr = "127.0.0.1:8080"
mode = "standalone"

[auth]
# Modes: "local_jwt" or "jwks"
mode = "jwks"
issuer = "https://auth.amoeba.com"
jwks_url = "https://auth.amoeba.com/.well-known/jwks.json"
audience = "amoeba-compute"

# Required only if mode = "local_jwt"
jwt_secret = "env:AMOEBA_LOCAL_JWT_SECRET"
users_file = "/etc/amoeba/users.json"
revocation_file = "/etc/amoeba/revoked_tokens.json"

The server reads this file from $AMOEBA_CONFIG (default /etc/amoeba/config.toml) once at startup. Startup fails closed: if auth.jwt_secret = "env:VAR_NAME" references an unset variable (or the config file is absent and AMOEBA_LOCAL_JWT_SECRET is unset), the process exits with an error rather than falling back to a known default secret. If no config file exists at all, Amoeba falls back to legacy environment-based configuration (local_jwt mode, fixed paths, 0.0.0.0:8080).


3.1 Authentication Sequence Comparison

┌────────────────────────────────────────────────────────────────────────────────────────┐
│ MODE A: LOCAL JWT MODE (Standalone / Offline)                                          │
│                                                                                        │
│ [ Client ] ──( 1. POST /auth/login )──► [ Axum Engine ] ──( 2. Verifies Argon2 Hash ) │
│                                                │                                       │
│                                       3. Issues Local HMAC JWT                         │
│                                                │                                       │
│ [ Client ] ◄───────────────────────────────────┘                                       │
│                                                                                        │
│ [ Client ] ──( 4. GET /v1/gemma4 + Bearer JWT )──► [ Axum Engine ]                     │
│                                                         │                              │
│                                                5. Decodes with local secret            │
└────────────────────────────────────────────────────────────────────────────────────────┘

┌────────────────────────────────────────────────────────────────────────────────────────┐
│ MODE B: Amoeba JWKS MODE (Distributed / Multi-Tenant)                                │
│                                                                                        │
│ [ Background Task ] ──( Periodically Syncs )──► [ Amoeba IdP (/.well-known/jwks) ]   │
│         │                                                                              │
│         ▼                                                                              │
│ [ Local JWKS Cache ]                                                                   │
│         ▲                                                                              │
│         │                                                                              │
│ [ Client ] ──( 1. GET /v1/gemma4 + Amoeba Signed JWT )──► [ Axum Engine ]          │
│                                                                    │                   │
│                                                      2. Validates via cached public key│
└────────────────────────────────────────────────────────────────────────────────────────┘

3.2 Rust Unified Verification Engine Implementation

use axum::{
    extract::{Request, State},
    http::{header::AUTHORIZATION, StatusCode},
    middleware::Next,
    response::Response,
};
use jsonwebtoken::{decode, decode_header, DecodingKey, Validation};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tokio::sync::RwLock;

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Claims {
    pub sub: String,
    pub org_id: Option<String>,
    pub roles: Vec<String>,
    pub exp: usize,
}

#[derive(Clone)]
pub enum AuthMode {
    LocalJwt {
        secret: Vec<u8>,
    },
    Jwks {
        jwks_url: String,
        cached_keys: Arc<RwLock<jsonwebtoken::jwk::JwkSet>>,
    },
}

pub struct JwtEngine {
    pub mode: AuthMode,
    pub validation: Validation,
}

impl JwtEngine {
    pub async fn verify_token(&self, token: &str) -> Result<Claims, String> {
        match &self.mode {
            AuthMode::LocalJwt { secret } => {
                let key = DecodingKey::from_secret(secret);
                decode::<Claims>(token, &key, &self.validation)
                    .map(|d| d.claims)
                    .map_err(|e| format!("Local HMAC failed: {}", e))
            }
            AuthMode::Jwks { cached_keys, .. } => {
                let header = decode_header(token).map_err(|e| e.to_string())?;
                let kid = header.kid.ok_or("Token missing 'kid' header")?;

                let keys = cached_keys.read().await;
                let jwk = keys.find(&kid).ok_or("Key ID not found in JWKS cache")?;

                let decoding_key = DecodingKey::from_jwk(jwk).map_err(|e| e.to_string())?;
                decode::<Claims>(token, &decoding_key, &self.validation)
                    .map(|d| d.claims)
                    .map_err(|e| format!("Amoeba JWKS validation failed: {}", e))
            }
        }
    }
}

// Unified Middleware Function
pub async fn unified_auth_middleware(
    State(engine): State<Arc<JwtEngine>>,
    mut req: Request,
    next: Next,
) -> Result<Response, StatusCode> {
    let auth_header = req
        .headers()
        .get(AUTHORIZATION)
        .and_then(|h| h.to_str().ok())
        .ok_or(StatusCode::UNAUTHORIZED)?;

    if !auth_header.starts_with("Bearer ") {
        return Err(StatusCode::UNAUTHORIZED);
    }

    let token = &auth_header[7..];

    match engine.verify_token(token).await {
        Ok(claims) => {
            req.extensions_mut().insert(claims);
            Ok(next.run(req).await)
        }
        Err(err) => {
            tracing::error!("Authentication failure: {}", err);
            Err(StatusCode::UNAUTHORIZED)
        }
    }
}

3.3 One-URL sign-in for ChatGPT and Claude (built-in OAuth server)

Without an identity team, you don't need Keycloak or Auth0 for this. Turn on Amoeba's own OAuth 2.1 server in config.toml:

[oauth]
enabled = true
public_url = "https://gw.example.com"

Then add https://gw.example.com/v1/finance-db/mcp as a connector in ChatGPT (developer mode) or Claude. The app finds Amoeba from the 401, sends the person to Amoeba's consent page ("Claude wants to use finance-db as you"), and gets a token that works on that one service only. Roles and tool:<name> permissions still decide which tools it may call.

  • Clients identify themselves with a Client ID Metadata Document; by default only OpenAI's and Anthropic's domains are accepted (allowed_client_hosts, or allow_any_client = true). Fetches are SSRF-guarded.
  • PKCE S256 is required; codes last 60 s and work once; refresh tokens rotate, and reusing one revokes the whole connection.
  • The console's Connected apps dialog lists every connection per user with a Revoke button; deleting a user ends theirs.
  • Dynamic Client Registration (dynamic_client_registration = true) is off by default.

Without a config file, AMOEBA_OAUTH_PUBLIC_URL=https://gw.example.com turns it on with the defaults.

4. Operation Mapping & Role Security

Requests are evaluated prior to waking or scaling containers.

Incoming Request Method / Path
              │
              ▼
    Resolve Operation Name ──► [ "read" | "add" | "update" | "delete" | a named rule ]
              │
              ▼
    Compare `claims.roles` against `service.permissions[operation]`
              │
      ┌───────┴───────┐
      ▼               ▼
 [ Matched ]    [ Unmatched ]
      │               │
      ▼               ▼
Proceed to Proxy    403 Forbidden (Container remains offline)
  1. REST Defaults: Maps GET $\rightarrow$ read, POST $\rightarrow$ add, PUT/PATCH $\rightarrow$ update, DELETE $\rightarrow$ delete.
  2. Named Operations (operation_rules): A service can name its own operations. Rules are checked in order and the first match wins; with no match, the REST defaults apply.
    • http_method rules match on the method: { "operation": "execute", "match_type": "http_method", "values": ["POST"] }.
    • path rules match on the subpath after /v1/<service>/, optionally narrowed by method: { "operation": "loans.create", "match_type": "path", "path": "tables/loans", "values": ["POST"] }. In a pattern, {name} and * match exactly one segment, and a final ** matches any remaining segments.
    • The operation name is the key looked up in permissions, so "loans.create": ["loan_officer"] grants that one call to that one role. Rules are validated when the catalog loads, so a malformed rule fails the reload instead of silently never matching.
  3. Upstream Token Injection: If upstream_auth is set in services.json, the proxy strips the incoming caller token and attaches the service-specific static key or custom header before dispatching the request over internal loopback networks. If the configured credential cannot be produced, the request is rejected with 503 and x-amoeba-rejection-reason: secret-unavailable.
  4. Caller Identity Headers: The proxy forwards x-amoeba-user, x-amoeba-org, and x-amoeba-roles taken from the verified token, and drops any copies the client sent, so a service can trust them for its own decisions (for example, per-role column masking).

5. Deployment (Docker Compose)

The simplest way to run Amoeba alongside a containerized edge proxy is a single docker-compose.yml that puts Caddy and the orchestrator on a shared Docker bridge network. Caddy handles automatic HTTPS and domain routing; the orchestrator manages backend container lifecycles over the host's Docker socket.

5.1 Project Layout

Everything lives in the repo, using paths relative to it — clone it anywhere and docker compose up works, no fixed install path required:

Amoeba/
├── docker-compose.yml
├── Dockerfile
├── Caddyfile
├── .env.example
└── config/
    ├── config.example.toml
    ├── services.example.json
    ├── services.docker.example.json
    └── users.example.json

5.2 Quickstart

# 1. Clone the repo
git clone https://github.com/dickyj-grc/Amoeba.git && cd Amoeba

# 2. Set your own JWT signing secret
cp .env.example .env
# edit .env and replace the placeholder with a long random string

# 3. Provide a service catalog (container-name based, see 5.3 below)
cp config/services.docker.example.json config/services.json

# 4. Start the stack
docker compose up -d --build

This builds the orchestrator image, then starts both amoeba-caddy and amoeba-orchestrator on the shared amoeba-net bridge network. docker-compose.yml mounts ./config to /etc/amoeba inside the orchestrator container and refuses to start if AMOEBA_LOCAL_JWT_SECRET isn't set, rather than silently falling back to an insecure default.

5.3 Routing to Workers on the Same Network

Any worker container joined to amoeba-net is reachable by its container/service name via Docker's built-in DNS — no static IPs needed. Point services.json at those names instead of IP addresses:

{
  "version": 1,
  "machines": { "local": { "type": "vm", "drivers": ["docker"], "resources": {} } },
  "services": {
    "gemma4": {
      "placement": { "type": "vm", "ip": "amoeba-gemma4-worker", "port": 11434, "cooldown_seconds": 180 },
      "container": { "image": "ollama/ollama:latest" },
      "permissions": { "read": ["admin", "analyst"] }
    }
  }
}

Add each worker as its own service in docker-compose.yml, give it a container_name matching what you put in services.json, and attach it to amoeba-net:

services:
  gemma4:
    image: ollama/ollama:latest
    container_name: amoeba-gemma4-worker
    restart: unless-stopped
    networks:
      - amoeba-net

5.4 Hot Reload

Editing ./config/services.json on the host is picked up immediately by the orchestrator's notify-based file watcher inside the container — no restart of the orchestrator or Caddy required.

5.5 Why This Is Easy to Operate

  1. Zero system dependencies — only Docker and Docker Compose are required; no Rust toolchain, Caddy, or system libraries need to be installed on the host.
  2. Automatic TLS — Caddy fetches and renews Let's Encrypt/ZeroSSL certificates on port 443 once Caddyfile points at a real domain with DNS pointing at the host.
  3. Small image — the multi-stage Dockerfile produces a ~30MB Alpine-based runtime image with just the two release binaries (amoeba, amoeba-admin) and CA certificates.

5.6 Running Across Multiple Machines

If your services are spread across more than one machine — say, a local box for a GPU model and a cloud VM for a lighter CPU-only service — run one Amoeba instance per machine, not one central instance trying to reach into the others.

Each instance gets its own services.json, listing only the services physically on that box, with a machines entry for itself:

// on the local machine
{
  "version": 1,
  "machines": {
    "local-machine": { "type": "vm", "drivers": ["docker"], "resources": { "memory": "32Gi", "gpu_vram": "8Gi" } }
  },
  "services": {
    "gemma4": {
      "placement": { "type": "vm", "ip": "localhost", "port": 11434, "cooldown_seconds": 180 },
      "container": {
        "image": "ollama/ollama:latest",
        "resources": { "limits": { "memory": "16Gi", "gpu_vram": "8Gi" } }
      },
      "permissions": { "read": ["admin", "analyst"] }
    }
  }
}

See config/services.local.example.json and config/services.cloud.example.json for a full matching pair.

Why per-machine rather than one shared file:

  • ip only ever needs to be local — localhost, a loopback address, or a Docker container name on that machine's own network. Nothing in a service's config ever needs to name another machine, since each instance never reaches outside its own host.
  • Container lifecycle stays local — each instance only ever needs to talk to its own Docker socket (the same /var/run/docker.sock mount docker-compose.yml already sets up) to eventually start/stop its own containers. There's no remote Docker API, no per-machine control agent, no SSH to build or secure.
  • machine/machines naming stays unambiguous — a service's machine field always refers to this instance's own machine, not a name that has to stay in sync across a shared file describing every box in the fleet.

Routing — independent entry points, no shared edge layer. Each instance is reachable at its own address; they don't talk to each other. A cloud VM's instance can sit behind its own public Caddy exactly as in 5.2–5.3. A local machine's instance typically has no public IP (home networks sit behind NAT), so it's reachable only over a private tunnel (Tailscale, WireGuard, Cloudflare Tunnel) between the two — never exposed directly to the internet. Whoever calls a service just needs to know which endpoint to hit for it; that knowledge lives with the caller, not inside Amoeba.

One thing this implies for auth: AMOEBA_LOCAL_JWT_SECRET and users.json are also per-instance. If you want the same caller/token to work against both machines, either configure the same JWT secret on both instances, or point both at the same mode = "jwks" identity provider (section 3) instead of two independent local_jwt stores.


6. User Access Management (Local JWT Mode)

When auth.mode = "local_jwt", users live in /etc/amoeba/users.json — username, Argon2id password hash, roles, and org. There are two ways to manage that file, and they're deliberately gated differently.

6.1 users.json Schema

{
  "users": {
    "dicky": {
      "password_hash": "$argon2id$v=19$m=65536,t=3,p=4$c29tZXNhbHRzdHJpbmc$9x2aX5q2K8mQp1vT6y8uZ1wA7sK4jL3mP0nO9rS8tU",
      "roles": ["admin", "analyst"],
      "org_id": "org_amoeba_hq"
    },
    "analyst_user": {
      "password_hash": "$argon2id$v=19$m=65536,t=3,p=4$YW5vdGhlcnNhbHQ$2y8uZ1wA7sK4jL3mP0nO9rS8tU9x2aX5q2K8mQp1vT6",
      "roles": ["analyst"],
      "org_id": "org_client_alpha"
    },
    "viewer_bot": {
      "password_hash": "$argon2id$v=19$m=65536,t=3,p=4$Ym90c2FsdHN0cmluZw$7sK4jL3mP0nO9rS8tU9x2aX5q2K8mQp1vT62y8uZ1wA",
      "roles": ["viewer"],
      "org_id": "org_client_alpha"
    }
  }
}

password_hash is never a plaintext password — it's generated by hashing with Argon2id and a random salt (see 6.2/6.3 below). Never hand-write this field.

6.2 Bootstrap: the amoeba-admin CLI

There's a bootstrapping problem with managing users purely over HTTP: you can't get an admin-scoped JWT before an admin user exists. amoeba-admin is the local, on-box tool that breaks that cycle — run it once to seed the first admin, then manage everyone else through the API (6.3).

# Create the first admin user
amoeba-admin add-user dicky hunter2 --roles admin,analyst --org org_amoeba_hq

# Change a password and/or roles
amoeba-admin update-user dicky --password new-password --roles admin

# Remove a user
amoeba-admin delete-user analyst_user

# Point at a non-default file (defaults to /etc/amoeba/users.json)
amoeba-admin add-user viewer_bot secret --roles viewer --org org_client_alpha --users-file ./config/users.json

Each command loads users.json, applies the change, and rewrites the file with 0600 permissions (owner read/write only) — the file holds password hashes, so it's never left world-readable. In the Docker Compose deployment, run this via docker compose exec orchestrator amoeba-admin ... against the mounted /etc/amoeba/users.json.

6.3 /admin/users HTTP API

Once at least one admin exists, everyone else can be managed over HTTP instead of shelling into the box. These routes require the same JWT verification as every other endpoint, plus "admin" in the caller's roles — there's no separate secret to provision or rotate.

Method Path Body Result
GET /admin/users — 200 with every user (never a password hash), what each can reach, and known roles
POST /admin/users {"username", "password", "roles", "org_id"} 201 Created, 409 Conflict if the username exists, 400 for a weak password (under 8 characters), bad username or a role with a comma
PATCH /admin/users/:username any of {"password", "roles", "org_id"} 200 OK, 404 if unknown, 400 if body is empty, 409 if it would remove the last admin or your own admin role
DELETE /admin/users/:username — 204 No Content, 404 if unknown, 409 for yourself or the last admin

The web console's Users page uses these routes. A new password ends the user's connected AI apps (OAuth); new roles end their current access tokens so the next refresh carries the new roles. With auth.mode = "jwks" users are managed in your identity provider and these routes answer 409.

curl -X POST https://compute.yourdomain.com/admin/users \
  -H "Authorization: Bearer $ADMIN_JWT" \
  -H "Content-Type: application/json" \
  -d '{"username": "new_analyst", "password": "a-long-password", "roles": ["analyst"], "org_id": "org_client_alpha"}'

A request without a valid token gets 401; a valid token without the admin role gets 403 — the same per-service pattern used for proxied requests (section 4), just with a fixed required role instead of a per-service permission map.

6.4 Obtaining a Token: POST /auth/login

In local JWT mode, call the public login endpoint with a username and password from users.json:

curl -X POST https://compute.yourdomain.com/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username": "dicky", "password": "hunter2"}'

On success it returns a short-lived JWT:

{
  "token": "eyJhbG...",
  "expires_at": 1722070800
}

Use the token as Authorization: Bearer <token> for subsequent API calls. Token lifetime defaults to 1 hour and can be changed with AMOEBA_TOKEN_TTL_SECONDS.

6.5 Revoking a Token: POST /auth/revoke

An admin can revoke their own current token (or any token they hold) before it naturally expires:

curl -X POST https://compute.yourdomain.com/auth/revoke \
  -H "Authorization: Bearer $TOKEN"

Revocations are persisted to revocation_file (default /etc/amoeba/revoked_tokens.json, settable in config.toml) and survive process restarts: a revoked token stays rejected until it naturally expires, even if the server restarts with the same signing secret. Unrevoked tokens remain valid across a restart.

6.6 Choosing Between User Management Paths

  • CLI: local/break-glass only. Whoever can shell into the host and write /etc/amoeba/users.json can run it — there's no additional app-level auth on top, so restrict host/SSH access accordingly.
  • API: the ongoing, day-to-day path. Every action is tied to a real sub in an admin's JWT, giving you an audit trail the CLI doesn't. Consider binding /admin/* to an internal-only network or loopback port in front-line deployments, as defense in depth beyond the role check.

7. Amoeba App Packages

Amoeba supports a self-contained app package format so any open-source project can ship a deployable bundle. A package is a zip file containing an amoeba.yaml manifest and a standard compose.yaml (or image reference). Install and uninstall are token-gated admin API calls; Amoeba hot-reloads services.json without a restart.

Every manifest field is documented in the amoeba.yaml manifest reference, with a JSON Schema for editors and AI tools.

See examples/app-packages/hello-world/ for a working example, examples/app-packages/streaming-echo/ for an SSE streaming example, examples/app-packages/obscura/ for a headless-browser package, and library/ for the apps in the console's App library.

7.1 Package structure

hello-world.amoeba.zip
└── amoeba.yaml      # metadata, image, routing, permissions, form schema

obscura.amoeba.zip   # a multi-service app adds a compose file
├── amoeba.yaml
└── compose.yaml     # standard Docker Compose file (Docker only)

7.2 Install and uninstall via curl

# Install
curl -X POST http://localhost:8080/admin/apps \
  -H "Authorization: Bearer $ADMIN_JWT" \
  -F "[email protected]" \
  -F 'values={"env":{"ECHO_TEXT":"Hello!"}};type=application/json'

# List installed apps
curl http://localhost:8080/admin/apps \
  -H "Authorization: Bearer $ADMIN_JWT"

# Check app readiness state (installed / pulling / ready / error)
curl http://localhost:8080/admin/apps/hello-world \
  -H "Authorization: Bearer $ADMIN_JWT"

# Uninstall
curl -X DELETE http://localhost:8080/admin/apps/hello-world \
  -H "Authorization: Bearer $ADMIN_JWT"

7.3 Encrypted secrets with age

Packages can include age-encrypted secret files. The target Amoeba instance decrypts them at install time using AMOEBA_AGE_SECRET_KEY.

Install age-keygen

age-keygen is shipped with the age CLI tool.

  • macOS: brew install age
  • Debian/Ubuntu: sudo apt install age
  • Fedora: sudo dnf install age
  • Arch: sudo pacman -S age
  • Pre-built binaries: github.com/FiloSottile/age/releases
  • Go: go install filippo.io/age/cmd/age-keygen@latest
  • Rust alternative: cargo install rage (uses rage-keygen instead of age-keygen)

Generate and configure the age key

On the Amoeba server:

age-keygen -o amoeba.age.key
export AMOEBA_AGE_SECRET_KEY=$(grep AGE-SECRET-KEY amoeba.age.key)

Declare and encrypt a package secret

In amoeba.yaml:

schema:
  secrets:
    API_KEY:
      description: API key
      required: true
      file: secrets/api_key.age

Encrypt the secret to the server's public key:

age -r age1... -o secrets/api_key.age < api_key.txt

Include secrets/api_key.age in the zip. Amoeba decrypts it at install time and writes the plaintext to /etc/amoeba/secrets/<app>/API_KEY. User-provided secret values in the install payload still take precedence over encrypted files.

7.4 App lifecycle state

After install Amoeba does not immediately return the app to callers. Instead it runs a background readiness probe:

installed -> pulling -> ready
                     -> error
  • installed: catalog updated, probe not started yet.
  • pulling: docker pull or docker compose pull is running.
  • ready: image is present and the app's TCP port responds.
  • error: pull or readiness probe failed; message contains the error.

Check state at any time:

curl http://localhost:8080/admin/apps/hello-world \
  -H "Authorization: Bearer $ADMIN_JWT"

Response:

{
  "name": "hello-world",
  "state": {
    "state": "ready",
    "message": null,
    "updated_at": 1712345678
  }
}

Until the app is ready, the proxy rejects requests with 503 Service Unavailable and x-amoeba-rejection-reason: app-not-ready (or app-error). This prevents the first API call from blocking on a slow registry download or a broken image, and gives the operator a clear signal when something is wrong. A request at least 30 seconds after a failed start starts the app again, so a passing failure (a registry outage, a lost container network) does not keep it down.

The proxy also supports streaming responses (SSE, MCP Streamable HTTP, and any chunked body). It does not buffer the response body; instead it forwards headers and streams chunks to the client while keeping active_connections open until the stream finishes or the client disconnects. A read (inactivity) timeout on the upstream client ensures silent streams can still scale to zero once they end.


8. Database Service

The database is the system agents most often need and the one a security team is least willing to open. The usual choices are to hand a service the database password, or to write and review a new API for every question someone wants to ask.

The database service (amoeba-db, in services/amoeba-db/) is a third option: one generic, reviewed service holds the connection, and everything callers can do is an approved definition, either a named query or a table opened for specific operations. No caller ever sends SQL, and no other service ever holds the password. It supports PostgreSQL.

8.1 How it works

agent ──► Amoeba ──► database service ──► PostgreSQL
           │              │
           │              ├─ runs only approved definitions, with bound parameters
           │              ├─ applies the column policy for the caller's roles
           │              └─ scopes rows to the caller's organization
           └─ checks the caller's roles for this table or query
  • Definitions are data, not code. They are a JSON document (DB_DEFINITIONS_FILE, re-read when it changes, or DB_DEFINITIONS). The service binary is reviewed once; each definition is a few lines that a data owner can approve. An invalid edit is logged and the previous definitions stay in force.
  • One service per database credential, not per query. Separate databases get separate services, so a fault in one cannot reach another's connection.
  • It scales to zero like any other Amoeba service.
  • It is an installable app package (image ghcr.io/dickyj-grc/amoeba-db), not part of the gateway binary.

8.2 Routes

GET    /v1/<db>/tables/loans?status=overdue    select (equality filters, limit, offset)
GET    /v1/<db>/tables/loans/42                select one by key
POST   /v1/<db>/tables/loans                   insert   (JSON body)
PATCH  /v1/<db>/tables/loans/42                update   (JSON body)
DELETE /v1/<db>/tables/loans/42                delete

POST   /v1/<db>/queries/overdue-loans          run a named query (JSON parameters)
POST   /v1/<db>/mcp                            MCP: the definitions above as tools

For plain table access nobody writes SQL: you open a table for the operations you want and the service generates the statements. Named queries cover reports and joins. Every definition the caller's roles may use is also an MCP tool (query_<name>, <table>_list, _get, _insert, _update, _delete), so an agent sees only the tools it may use.

8.3 Definitions

{
  "schema": "public",
  "statement_timeout_ms": 5000,
  "tables": {
    "customers": {
      "key": "id",
      "org_column": "org_id",
      "operations": { "select": ["cs_agent", "compliance"], "update": ["compliance"] },
      "columns": {
        "id":      { "default": "show" },
        "name":    { "default": "show" },
        "nik":     { "mask": ["cs_agent"], "show": ["compliance"] },
        "balance": { "show": ["compliance"] }
      }
    }
  },
  "queries": {
    "overdue-loans": {
      "mode": "read",
      "sql": "SELECT id, branch, amount, due_date FROM loans WHERE status = 'overdue' AND branch = $1",
      "params": [{ "name": "branch", "type": "text" }],
      "row_limit": 500,
      "roles": ["analyst"],
      "columns": { "id": { "default": "show" }, "branch": { "default": "show" }, "amount": { "mask": ["analyst"], "show": ["finance"] }, "due_date": { "default": "show" } }
    }
  }
}
curl -X POST https://gateway.example.com/v1/finance-db/queries/overdue-loans \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"branch": "JKT-01"}'
  • Tables: operations maps each opened operation to roles ("*" means any caller). key addresses one row. row_limit caps a select (default 500), and write_row_limit caps an update or delete (default 1). org_column limits rows to the caller's organization: reads filter on it, inserts fill it in, and nobody can set it.
  • Queries: mode is read or write. params (text, integer, number or boolean) bind to $1..$n in order and arrive as text, so cast where you need another type ($1::int). A read query must list its output columns, since columns are closed unless listed. A write query returns rows_affected.
  • Validation at load: names must be lowercase identifiers, placeholders must match the declared params, and unknown fields are rejected.

8.4 Guardrails

Guardrail What it prevents
Callers send a name and values, never SQL; values are always bound parameters SQL injection
Read definitions run in a READ ONLY transaction, on DATABASE_URL_READ if set A "read" that writes
Writes use DATABASE_URL_WRITE if set, so that account can have rights only on writable tables Writes outside the approved tables
Row limit on every definition; a write that touches more rows than its limit is rolled back (409) Bulk reads, and an update meant for one row that matches thousands
statement_timeout per transaction (504 when exceeded) A query that ties up the database
The caller's organization, from the verified token, is set as app.org for org_column filters and row-level security policies One tenant reading or writing another tenant's rows
Tables and columns are closed until explicitly opened A new column becoming visible by accident
One audit record per call (log target amoeba_db_audit): user, org, roles, definition, parameters, rows, status Untraceable access

Values written to a table are left out of the audit record (only their column names are kept), since those are often the sensitive part.

8.5 Column policy: show, mask, or hide per role

Access to an endpoint and access to a column are separate decisions. The gateway decides whether a caller may use tables/customers at all; the database service decides which columns that caller gets back.

With the policy in 8.3, a cs_agent calling GET /v1/finance-db/tables/customers/1 gets id, name, and nik as ************8901. A compliance caller using the same URL gets every column. Masking is applied in the SQL the service generates (all but the last four characters are starred), so a value the caller is not entitled to never leaves the database.

  • The default is hide.
  • When a caller has several roles, the most permissive one applies.
  • Writes may name only columns the caller sees in full.
  • Filters are allowed only on columns the caller sees in full, since filtering on a masked column would reveal it one guess at a time.

8.6 Installing it

examples/app-packages/finance-db is a working package with demo data (demo.sql):

  • Connection string: a secret, DATABASE_URL, so only the database service's container receives it.
  • Definitions: shipped as the DB_DEFINITIONS env default. Override it at install to use your own.
  • Gateway access rules: operation_rules give each table and query its own operation name, and permissions map those names to roles:
operation_rules:
  - { operation: customers.read,  match_type: path, path: "tables/customers/**", values: [GET] }
  - { operation: customers.write, match_type: path, path: "tables/customers/**", values: [POST, PATCH, DELETE] }
  - { operation: reports.run,     match_type: path, path: "queries/**",          values: [POST] }
  - { operation: mcp,             match_type: path, path: mcp,                   values: [POST] }
permissions:
  customers.read:  [cs_agent, compliance]
  customers.write: [compliance]
  reports.run:     [analyst, compliance]
  mcp:             [analyst, cs_agent, compliance]
cd examples/app-packages/finance-db && zip -r /tmp/finance-db.zip amoeba.yaml && cd -
curl -X POST http://localhost:8064/admin/apps \
  -H "Authorization: Bearer $ADMIN_JWT" \
  -F package=@/tmp/finance-db.zip \
  -F 'values={"secrets":{"DATABASE_URL":"postgres://reader:...@db-host:5432/finance"}}'

The service reads the caller's verified identity from x-amoeba-user, x-amoeba-org, and x-amoeba-roles, which the gateway sets from the token and a client cannot forge. Keep the service reachable only through the gateway: a request without those headers has no roles.

Current limits: PostgreSQL only; connections are unencrypted (no TLS to the database yet), so keep the database on a private network; filters are equality only.


9. Nightly End-to-End Test on DigitalOcean

A Python orchestrator spins up a DigitalOcean droplet, installs Caddy and Amoeba, exercises the admin/proxy APIs, verifies scale-to-zero, and destroys the droplet. It is designed to run nightly in GitHub Actions.

9.1 Required GitHub Secrets

Secret Purpose
DIGITALOCEAN_TOKEN DO API personal access token
DO_SSH_PRIVATE_KEY Private SSH key for the droplet
DO_SSH_PUBLIC_KEY Public SSH key registered in DO
AMOEBA_LOCAL_JWT_SECRET Amoeba JWT signing secret
AMOEBA_AGE_SECRET_KEY (optional) Age identity for encrypted app secrets

9.2 Files

  • scripts/e2e-do.py — thin wrapper that invokes pytest
  • scripts/e2e/ — pytest test suite and shared fixtures
    • conftest.py — droplet provisioning, login tokens, and helpers
    • do_client.py — DigitalOcean API client
    • ssh_client.py — paramiko wrapper
    • test_admin_apps.py, test_rbac.py, test_errors.py, test_scale_to_zero.py — test cases
  • scripts/e2e-cloud-init.sh — cloud-init user-data that provisions the droplet
  • .github/workflows/nightly-e2e.yml — GitHub Actions schedule

9.3 Run locally

export DIGITALOCEAN_TOKEN="dop_v1_..."
export DO_SSH_PRIVATE_KEY="/path/to/id_ed25519"
export DO_SSH_PUBLIC_KEY="ssh-ed25519 AAAAC3NzaC..."
export AMOEBA_LOCAL_JWT_SECRET="..."

python3 -m venv .venv-e2e
source .venv-e2e/bin/activate
pip install -r scripts/requirements-e2e.txt
python scripts/e2e-do.py

Add --keep-droplet to leave the droplet alive for debugging. You can also run pytest directly:

pytest scripts/e2e/ -v

9.4 What the test verifies

  1. Droplet creation and SSH readiness.
  2. Amoeba + Caddy come up via Docker Compose.
  3. Admin login returns a JWT.
  4. POST /admin/apps installs the hello-world app package.
  5. GET /admin/apps/hello-world polls until the app reaches the ready state.
  6. GET /admin/apps lists the installed app.
  7. Admin creates analyst and viewer users with different roles.
  8. Role-based access control:
    • analyst can read and add to hello-world.
    • viewer can read but not add to hello-world.
    • Non-admin users get 403 on /admin/apps.
  9. GET /v1/hello-world/ returns the expected response and wakes the container.
  10. Error cases fail closed:
    • Missing/invalid token on a private service → 401
    • Wrong password or unknown user login → 401
    • Unknown service → 404
    • Duplicate user creation → 409
    • Malformed or missing app package → 400
    • Non-admin user creation attempt → 403
    • Revoked token → 401
  11. Streaming responses are not buffered: GET /v1/streaming-echo/stream receives multiple SSE chunks over several seconds.
  12. Obscura headless browser installs, its MCP endpoint is reachable through the proxy, and a browser_navigate + browser_snapshot tool call round-trip returns real page content.
  13. After the cooldown, the container is stopped (scale-to-zero).
  14. Droplet is destroyed.

Reviews (0)

No results found