feat(lambda): add AWS Lambda integration in examples/integrations/aws_lambda/ (#177)

feat(lambda): add AWS Lambda one-shot scrape integration

Self-contained example in examples/integrations/aws_lambda/ — Dockerfile,
entrypoint, handler, and docs for running CloakBrowser stealth scrapes in
AWS Lambda (container image). Includes smart_wait DOM-stability polling,
Xvfb headed mode, and Lambda-specific Chromium flags.

Contributed by @AlexTech314.
This commit is contained in:
Alex Stepansky
2026-04-27 17:20:02 +02:00
committed by GitHub
parent a9a0ba13ba
commit 74b1ff64db
4 changed files with 491 additions and 0 deletions
@@ -0,0 +1,79 @@
# CloakBrowser on AWS Lambda — derived from the official CloakHQ image.
#
# `FROM cloakhq/cloakbrowser:<tag>` is an official distribution channel under
# the CloakBrowser Binary License — pulling it isn't redistribution. We just
# layer Lambda glue on top: the Lambda Runtime Interface Client (awslambdaric),
# the Lambda Runtime Interface Emulator (for local `docker run` testing), the
# dual-mode entrypoint, and the handler module.
#
# This directory is self-contained — copy/clone it anywhere and build from
# inside it. No files outside this directory are referenced.
#
# ─── Lambda invocation (default CMD) ──────────────────────────────────────────
# # From inside this directory:
# docker buildx build --platform linux/arm64 -t cloakbrowser-lambda:arm64 --load .
#
# # Or from a parent dir, pointing at this directory as the build context:
# docker buildx build --platform linux/arm64 \
# -f path/to/aws_lambda/Dockerfile -t cloakbrowser-lambda:arm64 --load \
# path/to/aws_lambda
#
# docker run --rm -p 9000:8080 cloakbrowser-lambda:arm64
# curl -XPOST http://localhost:9000/2015-03-31/functions/function/invocations \
# -d '{"url":"https://example.com"}'
#
# ─── Same as the canonical CloakHQ image (CMD overridden) ─────────────────────
# docker run --rm -it cloakbrowser-lambda:arm64 python # REPL
# docker run --rm cloakbrowser-lambda:arm64 python examples/basic.py # examples
# docker run --rm -p 9222:9222 cloakbrowser-lambda:arm64 cloakserve --port=9222 # CDP server
# docker run --rm cloakbrowser-lambda:arm64 cloaktest # stealth tests
# docker run --rm -it cloakbrowser-lambda:arm64 node # JS wrapper
# docker run --rm -it cloakbrowser-lambda:arm64 bash # shell
#
# Pin a specific tag (e.g. cloakhq/cloakbrowser:0.3.25) for reproducible builds;
# `latest` floats with CloakHQ's release cadence.
FROM cloakhq/cloakbrowser:latest
# ─── Lambda Runtime Interface Client ──────────────────────────────────────────
RUN pip install --no-cache-dir awslambdaric
# ─── Lambda Runtime Interface Emulator (local `docker run` testing) ───────────
# Bundled into the image so users can hit the standard local-invoke endpoint
# without mounting the RIE separately. TARGETARCH is provided by buildx.
ARG TARGETARCH
ADD https://github.com/aws/aws-lambda-runtime-interface-emulator/releases/latest/download/aws-lambda-rie-${TARGETARCH} \
/usr/local/bin/aws-lambda-rie
RUN chmod +x /usr/local/bin/aws-lambda-rie
# ─── Lambda glue ──────────────────────────────────────────────────────────────
# Dual-mode entrypoint replaces the canonical bin/docker-entrypoint.sh: same
# Xvfb startup, plus routing for `module.func` CMDs through awslambdaric.
COPY lambda-entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
# Handler sits at /app (already on Python's import path in the canonical image,
# WORKDIR=/app), imports cloakbrowser as a normal library.
COPY lambda_handler.py /app/lambda_handler.py
# ─── Lambda non-root readability fix ──────────────────────────────────────────
# The canonical image bakes the Chromium binary at /root/.cloakbrowser/ (root's
# HOME at build time). Lambda runs the container as a non-root user that can't
# read /root by default (mode 750). Make the whole binary tree world-readable
# and traversable. Also restore the .welcome_shown marker the canonical image
# rm's (Lambda's read-only runtime FS can't recreate it, so the welcome would
# print to CloudWatch on every cold start otherwise).
RUN touch /root/.cloakbrowser/.welcome_shown \
&& chmod -R o+rX /root /root/.cloakbrowser
# ─── Lambda runtime env ───────────────────────────────────────────────────────
# HOME=/tmp gives Chromium a writable scratch dir (Lambda only allows writes
# under /tmp). CLOAKBROWSER_CACHE_DIR points at the baked binary location since
# HOME=/tmp would otherwise make get_cache_dir() resolve to /tmp/.cloakbrowser
# (empty). Auto-update is disabled because the runtime FS is read-only.
ENV HOME=/tmp \
CLOAKBROWSER_CACHE_DIR=/root/.cloakbrowser \
CLOAKBROWSER_AUTO_UPDATE=false
ENTRYPOINT ["/entrypoint.sh"]
CMD ["lambda_handler.handler"]
@@ -0,0 +1,158 @@
# CloakBrowser on AWS Lambda
Run stealth Chromium one-shot scrapes inside an AWS Lambda function (container image package type). The image derives directly from the official CloakHQ Docker Hub image (`cloakhq/cloakbrowser`) and adds Lambda runtime support on top — Lambda is an additional invocation surface, not a replacement. Every other surface from the canonical image (`python`, `cloakserve`, `cloaktest`, `node`, `bash`, examples) keeps working.
This document covers what the image is, how to build and locally test it, and the event/response contract. **It does not prescribe a deployment method** — push the resulting image to ECR and create the Lambda function however you prefer (AWS CLI, CDK, Terraform, SAM, console, etc.). Configuration tips for whichever tool you use are at the bottom.
## Files in this directory
| File | Purpose |
|---|---|
| `Dockerfile` | `FROM cloakhq/cloakbrowser` plus a thin Lambda layer. Self-contained — no files outside this directory are referenced. |
| `lambda-entrypoint.sh` | Dual-mode entrypoint. Starts Xvfb, then routes `module.func` CMDs through `awslambdaric` (via the bundled `aws-lambda-rie` locally, or the AWS Runtime API in production), and execs everything else (`python`, `cloakserve`, `cloaktest`, `node`, `bash`) directly. |
| `lambda_handler.py` | Default handler. Takes `{url, ...}`, returns `{title, url, html, screenshot_b64?}`. Always headed via Xvfb. |
| `INSTRUCTIONS.md` | This file. |
The Lambda layer is ~30 lines on top of the official image — no apt list, no Node install, no JS-wrapper build, no Chromium download. The canonical CloakHQ image owns those.
This directory is **standalone**: copy or clone it anywhere (its own repo, a subdirectory of an existing project, a CI artifact bundle) and the build still works. It depends only on the upstream `cloakhq/cloakbrowser` image on Docker Hub and the `aws-lambda-rie` binary on GitHub Releases — both fetched at build time.
## Build
From inside this directory:
```bash
docker buildx build --platform linux/arm64 -t cloakbrowser-lambda:arm64 --load .
```
Or from anywhere, pointing at this directory as the build context:
```bash
docker buildx build --platform linux/arm64 \
-f path/to/aws_lambda/Dockerfile \
-t cloakbrowser-lambda:arm64 --load \
path/to/aws_lambda
```
The build pulls `cloakhq/cloakbrowser:latest` from Docker Hub and adds the Lambda layer on top. Pin a specific tag (e.g. `cloakhq/cloakbrowser:0.3.25`) in the `FROM` line for reproducible builds; `latest` floats with the upstream release cadence.
For x86_64, switch `--platform linux/amd64` (slower on Apple Silicon under emulation).
## Local smoke test (no AWS account needed)
> **What's the RIE?** Lambda container images can't be run with a plain `docker run` — they expect to talk to AWS's Runtime API (the HTTP service Lambda exposes inside its sandbox to deliver events and collect responses). AWS publishes a small binary called the **Runtime Interface Emulator** that stands up a fake Runtime API on localhost so you can test the container exactly the way Lambda will invoke it, without deploying. We bake the RIE into the image, and the dual-mode entrypoint uses it automatically when `AWS_LAMBDA_RUNTIME_API` isn't set (i.e. you're not running in real Lambda).
The image bakes in `aws-lambda-rie`, so the standard Lambda local-invoke endpoint works without mounting anything:
```bash
docker run --rm -p 9000:8080 cloakbrowser-lambda:arm64
# In another shell:
curl -sS -XPOST "http://localhost:9000/2015-03-31/functions/function/invocations" \
-d '{"url":"https://example.com"}'
```
Other invocation surfaces stay intact (these match the canonical CloakHQ image):
```bash
docker run --rm -it cloakbrowser-lambda:arm64 python # REPL
docker run --rm cloakbrowser-lambda:arm64 python examples/basic.py # examples
docker run --rm -p 9222:9222 cloakbrowser-lambda:arm64 cloakserve --port=9222 # CDP server
docker run --rm cloakbrowser-lambda:arm64 cloaktest # stealth tests
docker run --rm -it cloakbrowser-lambda:arm64 node # JS wrapper
```
## Event schema
Only `url` is required. Everything else is optional.
### Launch options (forwarded to `cloakbrowser.launch_context_async`)
| Field | Type | Default |
|---|---|---|
| `url` | str | required |
| `proxy` | str / dict | none — `http://user:pass@host:port` or a Playwright proxy dict |
| `humanize` | bool | `false` — enable human-like mouse / keyboard / scroll |
| `human_preset` | str | `"default"` or `"careful"` |
| `geoip` | bool | `false` — auto timezone+locale from proxy IP |
| `timezone` | str | none — IANA tz, e.g. `"America/New_York"` |
| `locale` | str | none — BCP-47, e.g. `"en-US"` |
| `viewport` | `{width,height}` | `1920x947` (cloakbrowser default) |
| `user_agent` | str | none |
| `extra_args` | `list[str]` | `[]` — extra Chromium CLI flags |
### Navigation
| Field | Type | Default |
|---|---|---|
| `wait_until` | str | `"domcontentloaded"``load` / `domcontentloaded` / `networkidle` / `commit` |
| `goto_timeout_ms` | int | `30000` |
### Post-navigation waits
`smart_wait` is the default when no other wait is specified. It polls `document.documentElement.outerHTML.length` and returns when the size hasn't changed for `dom_stable_ms`. Robust for at-scale scraping because it ignores network activity (analytics beacons, long-poll, websockets) that doesn't mutate the DOM — `wait_until: "networkidle"` is unreliable on modern SPAs for exactly this reason.
| Field | Type | Default |
|---|---|---|
| `smart_wait` | bool | `true` if no other wait is set |
| `dom_stable_ms` | int | `1500` |
| `max_settle_ms` | int | `15000` |
| `wait_for_load_state` | str | none — `load` / `domcontentloaded` / `networkidle` |
| `wait_for_load_state_timeout_ms` | int | `30000` |
| `wait_for_selector` | str | none — CSS or XPath |
| `wait_for_selector_state` | str | `"visible"` — also `attached` / `detached` / `hidden` |
| `wait_for_selector_timeout_ms` | int | `30000` |
| `wait_for_function` | str | none — JS expression returning truthy when ready |
| `wait_for_function_timeout_ms` | int | `30000` |
| `wait_ms` | int | none — fixed pause |
### Capture
| Field | Type | Default |
|---|---|---|
| `screenshot` | bool | `true` |
| `full_page_screenshot` | bool | `false` |
### Response
```json
{
"title": "...",
"url": "https://example.com/",
"html": "<!DOCTYPE html>...",
"screenshot_b64": "<base64 PNG>"
}
```
## Lambda-specific Chromium hardening (baked in, do not remove)
Two flags are forced on every launch by `lambda_handler.py`:
- `--disable-dev-shm-usage` — Lambda's `/dev/shm` is ~64 MB; Chromium's renderer crashes mid-paint without this.
- `--no-zygote` — Lambda's restricted process model can't fork from Chromium's zygote process; without this the browser launches but child renderers fail to spawn and the first `page.new_page()` raises `TargetClosedError`.
## Function configuration recommendations
Whatever tool you use to create the Lambda function (CLI, CDK, Terraform, SAM, console), apply these settings:
| Setting | Value | Why |
|---|---|---|
| Package type | Image | Required — this is a container image, not a zip. |
| Architecture | `arm64` | Roughly 20% cheaper than x86_64. Native build on Apple Silicon. Match the architecture you built for. |
| Memory | 3008 MB | Memory in Lambda is tied to vCPU. Below ~1769 MB Chromium starts noticeably slower. |
| Timeout | 60120 s | Cold start can hit 80+ s on this image; warm invocations are 315 s depending on site. |
| Ephemeral storage (`/tmp`) | 1024 MB | Chromium profile dirs and screenshots can fill the 512 MB default. |
| Networking | Default (no VPC) | Binary is baked in, no network needed at cold start. Add VPC + NAT only if your proxy egress requires it. |
| Execution role | `AWSLambdaBasicExecutionRole` | Just CloudWatch Logs. Add more permissions only if your handler needs them. |
## Cold start
First invocation in a new container takes ~8090 s (image extraction, Chromium binary mmap, JS engine warmup, no DNS/TLS caches). Subsequent warm invocations on the same container are 315 s.
For latency-sensitive use cases: provision concurrency, schedule a CloudWatch/EventBridge warmer ping, or accept the cold tail.
If you see empty/missing dynamic content on cold-start invocations, raise `max_settle_ms` in the event payload (e.g. `25000`) — the default `15000` is tuned for warm runs.
## License
The patched Chromium binary inside the upstream `cloakhq/cloakbrowser` image is governed by the **CloakBrowser Binary License** (published at https://github.com/CloakHQ/CloakBrowser/blob/main/BINARY-LICENSE.md). Internal organizational use (private ECR, your own scraping pipelines, your own business) is free. Exposing this Lambda as a paid API to third-party customers — i.e. browser-as-a-service — requires an OEM/SaaS license from CloakHQ (`cloakhq@pm.me`). Do not push the resulting image to a public registry; that would be redistribution and is prohibited.
@@ -0,0 +1,35 @@
#!/bin/sh
# Dual-mode entrypoint for the CloakBrowser Lambda image.
#
# 1. Always start Xvfb on :99 (same as the canonical bin/docker-entrypoint.sh)
# so headed Chromium works no matter how the container is invoked.
# 2. Detect whether the CMD looks like a Lambda handler (a single
# `module.func`-shaped argument). If yes, route through the Lambda runtime
# client (using the bundled aws-lambda-rie locally, or talking to the real
# Lambda Runtime API when AWS_LAMBDA_RUNTIME_API is set in production).
# 3. Otherwise exec the CMD directly — preserving the canonical Dockerfile's
# interaction surface (`python`, `cloakserve`, `cloaktest`, `node`, `bash`,
# `python examples/basic.py`, etc.).
set -e
mkdir -p /tmp/.X11-unix
chmod 1777 /tmp/.X11-unix 2>/dev/null || true
Xvfb :99 -screen 0 1920x1080x24 -nolisten tcp >/tmp/Xvfb.log 2>&1 &
sleep 0.5
# Lambda handler shape: exactly one arg, dotted identifier (no spaces, no slashes,
# no leading dot). `python`, `cloakserve`, `cloaktest`, `bash`, `node` all fail
# this test and pass through to plain exec.
if [ $# -eq 1 ] && \
echo "$1" | grep -qE '^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)+$'; then
if [ -z "${AWS_LAMBDA_RUNTIME_API}" ]; then
# Local invocation via bundled RIE.
exec /usr/local/bin/aws-lambda-rie /usr/local/bin/python -m awslambdaric "$@"
else
# Real Lambda — runtime API endpoint already provided by the platform.
exec /usr/local/bin/python -m awslambdaric "$@"
fi
fi
exec "$@"
@@ -0,0 +1,219 @@
"""AWS Lambda handler for one-off stealth-browser invocations.
Always runs **headed** via the Xvfb display started by `lambda-entrypoint.sh`.
Event schema (all fields except `url` are optional):
Launch options (passed to cloakbrowser.launch_context_async):
url str required, the page to scrape
proxy str|dict http://user:pass@host:port or Playwright proxy dict
humanize bool False — enable human-like mouse/keyboard/scroll
human_preset str "default" | "careful"
geoip bool False — auto timezone+locale from proxy IP
timezone str IANA tz, e.g. "America/New_York"
locale str BCP-47, e.g. "en-US"
viewport {width,height} defaults to 1920x947 (cloakbrowser DEFAULT_VIEWPORT)
user_agent str custom UA (rare — cloakbrowser sets one already)
extra_args list[str] additional Chromium CLI flags
Navigation options (passed to page.goto):
wait_until str "load"|"domcontentloaded"|"networkidle"|"commit"
default "domcontentloaded"
goto_timeout_ms int 30000
Post-navigation waits (run in this order if specified):
smart_wait bool ON by default if no other wait is set.
Polls document.outerHTML.length and bails when it
hasn't changed for `dom_stable_ms`. Handles lazy
hydration, async chunks, and lazy images, and is
immune to analytics beacons / long-poll that keep
the network busy without mutating the DOM.
dom_stable_ms int 1500 — how long DOM must be quiet
max_settle_ms int 15000 — hard cap on smart_wait
wait_for_load_state str "load"|"domcontentloaded"|"networkidle"
wait_for_load_state_timeout_ms int 30000
wait_for_selector str CSS or XPath selector
wait_for_selector_state str "attached"|"detached"|"visible"|"hidden", default "visible"
wait_for_selector_timeout_ms int 30000
wait_for_function str JS expression that returns truthy when ready
wait_for_function_timeout_ms int 30000
wait_ms int fixed pause in ms (page.wait_for_timeout)
Capture options:
screenshot bool True
full_page_screenshot bool False — capture entire scrollable page
Returns:
{"title": ..., "url": ..., "html": ..., "screenshot_b64"?: ...}
"""
from __future__ import annotations
import asyncio
import base64
import logging
import subprocess
from pathlib import Path
from typing import Any
from cloakbrowser import launch_context_async
logger = logging.getLogger("cloakbrowser.lambda")
logger.setLevel(logging.INFO)
def _diag_snapshot() -> str:
"""Capture Xvfb status, Xvfb log, X11 socket state, and env for error reports."""
import os
parts = []
try:
r = subprocess.run(["pgrep", "-fa", "Xvfb"], capture_output=True, text=True)
parts.append(f"pgrep Xvfb: rc={r.returncode} stdout={r.stdout.strip()!r}")
except Exception as e:
parts.append(f"pgrep failed: {e}")
try:
r = subprocess.run(["ls", "-la", "/tmp/.X11-unix"], capture_output=True, text=True)
parts.append(f"ls /tmp/.X11-unix:\n{r.stdout}{r.stderr}")
except Exception as e:
parts.append(f"ls /tmp/.X11-unix failed: {e}")
try:
log = Path("/tmp/Xvfb.log").read_text()
parts.append(f"/tmp/Xvfb.log:\n{log}")
except Exception as e:
parts.append(f"Xvfb log unreadable: {e}")
parts.append(f"env: DISPLAY={os.environ.get('DISPLAY')!r} HOME={os.environ.get('HOME')!r}")
return "\n".join(parts)
def handler(event: dict, context: Any) -> dict:
return asyncio.run(_run(event))
def _build_launch_kwargs(event: dict) -> dict:
"""Translate the event dict into kwargs for launch_context_async.
Only includes keys explicitly set in the event so cloakbrowser's defaults
(DEFAULT_VIEWPORT etc.) kick in when fields are absent — passing
viewport=None would *disable* viewport emulation, which we don't want.
"""
kwargs: dict = {
"headless": False, # always headed via Xvfb
"args": [
# Lambda /dev/shm is ~64 MB — Chromium crashes mid-render without this.
"--disable-dev-shm-usage",
# Lambda's restricted process model can't fork from Chromium's zygote
# — without this, child renderer processes fail to spawn.
"--no-zygote",
*event.get("extra_args", []),
],
}
for key in ("proxy", "humanize", "human_preset", "geoip",
"timezone", "locale", "viewport", "user_agent"):
if key in event:
kwargs[key] = event[key]
return kwargs
async def _smart_wait(page, dom_stable_ms: int = 1500, max_settle_ms: int = 15000) -> None:
"""Wait until the document HTML hasn't changed for `dom_stable_ms`.
Generic stopping condition for at-scale scraping when you can't tune
selectors per site. More robust than `networkidle` because it ignores
network activity that doesn't mutate the DOM (analytics beacons,
long-poll, websockets, web vitals streams).
"""
js = f"""
(() => {{
if (!window.__cb_settle) {{
window.__cb_settle = {{ len: -1, since: Date.now() }};
}}
const cur = document.documentElement.outerHTML.length;
const s = window.__cb_settle;
if (cur !== s.len) {{
s.len = cur;
s.since = Date.now();
return false;
}}
return (Date.now() - s.since) >= {int(dom_stable_ms)};
}})()
"""
try:
await page.wait_for_function(js, timeout=max_settle_ms, polling=200)
except Exception:
# Hit max_settle_ms cap — return what we have rather than fail the whole invoke
logger.warning("smart_wait hit max_settle_ms=%d cap", max_settle_ms)
_EXPLICIT_WAIT_KEYS = (
"wait_for_load_state", "wait_for_selector", "wait_for_function", "wait_ms",
)
async def _post_nav_waits(page, event: dict) -> None:
"""Run waits in priority order. smart_wait is the default unless the
caller asked for a more specific stopping condition."""
explicit = any(k in event for k in _EXPLICIT_WAIT_KEYS)
if event.get("smart_wait", not explicit):
await _smart_wait(
page,
dom_stable_ms=event.get("dom_stable_ms", 1500),
max_settle_ms=event.get("max_settle_ms", 15000),
)
if "wait_for_load_state" in event:
await page.wait_for_load_state(
event["wait_for_load_state"],
timeout=event.get("wait_for_load_state_timeout_ms", 30000),
)
if "wait_for_selector" in event:
await page.wait_for_selector(
event["wait_for_selector"],
state=event.get("wait_for_selector_state", "visible"),
timeout=event.get("wait_for_selector_timeout_ms", 30000),
)
if "wait_for_function" in event:
await page.wait_for_function(
event["wait_for_function"],
timeout=event.get("wait_for_function_timeout_ms", 30000),
)
if "wait_ms" in event:
await page.wait_for_timeout(event["wait_ms"])
async def _run(event: dict) -> dict:
url = event["url"]
try:
ctx = await launch_context_async(**_build_launch_kwargs(event))
except Exception as e:
diag = _diag_snapshot()
logger.error("launch_context_async failed: %s\nDIAG:\n%s", e, diag)
raise RuntimeError(f"launch failed: {e}\n--- DIAG ---\n{diag}") from e
try:
page = await ctx.new_page()
await page.goto(
url,
wait_until=event.get("wait_until", "domcontentloaded"),
timeout=event.get("goto_timeout_ms", 30000),
)
await _post_nav_waits(page, event)
result: dict = {
"title": await page.title(),
"url": page.url,
"html": await page.content(),
}
if event.get("screenshot", True):
png = await page.screenshot(
full_page=event.get("full_page_screenshot", False),
)
result["screenshot_b64"] = base64.b64encode(png).decode()
return result
finally:
try:
await ctx.close()
except Exception:
pass