Build an Accountable Bot Gateway with Localtonet
Expose a local bot API while enforcing scoped access, audit logs, rate limits, robots.txt rules, Retry-After handling, suspension, and reactivation.
In this article 10 sections
Build a durable control API that authenticates callers, constrains destinations, respects upstream policy, and records every important decision
A bot can authenticate correctly and still behave unsafely because of a malformed job, scheduler bug, unsafe redirect, excessive request rate, or failure to respond to an upstream instruction. This tutorial builds a runnable Python gateway with bearer-token scopes, SQLite-backed job and audit state, destination allowlisting, SSRF checks, coordinated rate limits, robots.txt evaluation, bounded HTTP 429 backoff, suspension, and deliberate reactivation. After verifying the gateway locally, we expose only its narrow control API through a Localtonet HTTP tunnel. Localtonet supplies public reachability, while the application remains responsible for authentication, authorization, outbound safety, and accountable automation.
📋 What's in this guide
Identity is the beginning of bot accountability, not the end
Authentication answers a narrow question: did the caller present a credential accepted by the gateway? It does not prove that the requested destination is authorized, that a submitted URL is safe to resolve, that a long-running job remains within its budget, or that the bot will respond correctly when a destination asks it to slow down.
Continuous accountability evaluates those conditions throughout the job lifecycle. The gateway authenticates each control request, authorizes the requested operation, validates destinations before storage and dispatch, checks current job state before each outbound request, coordinates host-level pacing, evaluates robots.txt, processes upstream rate-limit responses, and records the resulting decisions. An operator can then explain why work was accepted, delayed, denied, suspended, cancelled, or reactivated.
The Localtonet client runs on a device that can reach the gateway and establishes an outbound connection to a Localtonet relay. An HTTP tunnel gives the local service a public HTTPS address without inbound router port forwarding, firewall changes, VPN setup, or a public IP address. The tunnel forwards requests to the configured local IP address and port. It does not assign application scopes, inspect submitted destinations, parse robots.txt, or schedule outbound retries.
Run automated requests only against systems you own or are explicitly authorized to access. You must also comply with the destination's access controls, published policies, terms, applicable law, and direct instructions. Localtonet terms prohibit using the service to aid unauthorized botting, scraping, data mining, hacking, or other unauthorized automation. An allowed robots.txt path is not a substitute for authorization.
Prerequisites and project scope
This reference implementation deliberately favors a small, inspectable deployment over a distributed crawler platform. It runs one FastAPI process with one background scheduler and stores state in SQLite. That gives the tutorial durable job state, restart-safe counters, persistent host pauses, and reproducible control routes without requiring a separate queue or database service.
Use the following prerequisites:
- Python 3.12.
- A device that can run the Python gateway and the Localtonet client.
- An authorized public HTTP or HTTPS origin for behavioral testing.
- A list of exact destination hostnames the gateway may contact.
- Two randomly generated application secrets, one for submission and inspection and one for operator actions.
- A current Localtonet account and a device-specific authentication token handled through the supported Localtonet client workflow.
The implementation retrieves one configured URL repeatedly until it reaches its request budget, is cancelled, fails, or is suspended. It is not a general web crawler. It does not discover links, execute browser JavaScript, solve access challenges, rotate identities, or evade destination controls. Extending it into a distributed system requires a shared transactional database, distributed leases, and a coordinated rate limiter rather than multiple independent SQLite processes.
Project layout
accountable-gateway/
├── app.py
├── requirements.txt
└── data/
└── gateway.db
Pinned dependencies
Create requirements.txt with the following versions. These pins make the tutorial reproducible, but they are not a promise that a version will remain appropriate indefinitely. Review security updates before production deployment.
fastapi==0.115.6
uvicorn==0.34.0
httpx==0.28.1
protego==0.4.0
Install the application
mkdir -p accountable-gateway/data
cd accountable-gateway
python3.12 -m venv .venv
. .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install -r requirements.txt
On Windows PowerShell, activate the environment with:
.\.venv\Scripts\Activate.ps1
Configuration variables
| Variable | Purpose | Example shape |
|---|---|---|
GATEWAY_SUBMIT_TOKEN |
Bearer token permitted to create and inspect jobs. | A long random secret generated locally |
GATEWAY_OPERATOR_TOKEN |
Separate bearer token permitted to suspend, reactivate, and cancel jobs. | A different long random secret |
ALLOWED_HOSTS |
Comma-separated, exact, lowercase destination hostnames. | test.example.org,api.example.org |
GATEWAY_DB |
Path to the SQLite database. | data/gateway.db |
BOT_USER_AGENT |
Accurate user agent used for robots.txt evaluation and retrieval. | AuthorizedGatewayBot/1.0 |
WORKER_ENABLED |
Set to 0 for control-plane tests or 1 to dispatch authorized work. |
0 or 1 |
Generate secrets locally instead of placing example credentials in source control:
python -c "import secrets; print(secrets.token_urlsafe(48))"
python -c "import secrets; print(secrets.token_urlsafe(48))"
Store the generated values in your process manager or a local environment file excluded from version control. Do not put them in a public shell history, screenshots, job payloads, URLs, or Localtonet tunnel settings. The Localtonet device token is separate from these application credentials and must also remain private.
Define the security boundary before accepting destinations
A gateway that accepts caller-selected URLs can become a server-side request forgery, or SSRF, primitive. A simple hostname allowlist is not sufficient by itself. DNS can resolve an apparently public name to loopback, a private LAN, a link-local service, or a cloud metadata address. Redirects can also move a request from an approved public URL to a prohibited destination.
The reference implementation applies the following controls before storing a job and again before every outbound request:
- Only
httpandhttpsschemes are accepted. - User information in URLs is rejected.
- Only ports 80 and 443 are accepted.
- The hostname must exactly match an entry in
ALLOWED_HOSTS. - Every resolved IPv4 and IPv6 address must be globally routable.
- Loopback, private, link-local, multicast, reserved, unspecified, and other non-global addresses are rejected.
- Redirects are not followed automatically. Each redirect location is normalized and revalidated.
- Redirect count is bounded.
- Response bodies are streamed with a maximum accepted byte count.
- Connection, read, write, and pool timeouts are finite.
These checks explicitly reject common metadata destinations such as link-local addresses because they are not globally routable. The same rule blocks loopback services, private RFC 1918 networks, IPv6 unique-local addresses, and local infrastructure discovered through DNS.
The application resolves and validates addresses before each request, but a conventional hostname-based HTTP client may resolve the name again when opening the socket. A malicious or compromised DNS service could change the answer between validation and connection. In production, combine application validation with an outbound firewall, container network policy, or egress proxy that blocks private and special-use address ranges. Permit only required destination ports and, where practical, approved destination networks. Network-level denial provides a second boundary if application validation is bypassed or loses a DNS race.
Do not expose an unrestricted worker administration interface, development console, arbitrary command route, or generic proxy. The public service should contain only narrow job-control operations. Keep the health response minimal, return generic errors to clients, and retain detailed diagnostics only in access-controlled logs.
Standards-backed robots.txt behavior
The robots exclusion protocol is standardized by RFC 9309. The implementation fetches /robots.txt from the target origin, evaluates rules using the configured bot user agent, and caches a successful policy for no longer than 24 hours. A 404 response is treated as an unavailable robots file, which permits access under the protocol. A 401 or 403 response is treated as complete disallow. Server errors, unsafe redirects, parse failures, and network failures conservatively suspend the job instead of treating uncertainty as permission.
That failure policy is intentionally stricter than the minimum behavior needed for some protocol cases. Organizations can adopt stricter local policy, and this gateway does so to avoid dispatching when it cannot safely determine the applicable rules.
Standards-backed 429 and Retry-After behavior
HTTP 429 is defined in RFC 9110, section 15.5.30. A server can use it to report that a client has sent too many requests. The Retry-After field defined in RFC 9110, section 10.2.3 can contain either a non-negative delay in seconds or an HTTP date.
The implementation parses both forms, caps any accepted delay at one hour, and adds a small amount of jitter. If the field is missing or invalid, it uses exponential backoff capped at five minutes. A job is suspended after five 429 responses. The host-level next-eligible timestamp is stored in SQLite so a process restart does not erase the pause.
Build the runnable Python gateway
Save the following application as app.py. It creates the database schema during startup, validates bearer-token scopes, persists jobs and audit events, runs one scheduler task, coordinates host pacing through SQLite, checks robots.txt, processes redirects manually, and applies bounded 429 backoff.
import asyncio
import hashlib
import hmac
import ipaddress
import json
import os
import random
import socket
import sqlite3
import time
import uuid
from contextlib import asynccontextmanager
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.parse import urljoin, urlsplit, urlunsplit
import httpx
from fastapi import Depends, FastAPI, Header, HTTPException, Request
from pydantic import BaseModel, Field
from protego import Protego
DB_PATH = os.getenv("GATEWAY_DB", "data/gateway.db")
SUBMIT_TOKEN = os.getenv("GATEWAY_SUBMIT_TOKEN", "")
OPERATOR_TOKEN = os.getenv("GATEWAY_OPERATOR_TOKEN", "")
ALLOWED_HOSTS = {
item.strip().lower().rstrip(".")
for item in os.getenv("ALLOWED_HOSTS", "").split(",")
if item.strip()
}
BOT_USER_AGENT = os.getenv("BOT_USER_AGENT", "AuthorizedGatewayBot/1.0")
WORKER_ENABLED = os.getenv("WORKER_ENABLED", "0") == "1"
MAX_RESPONSE_BYTES = 1_000_000
MAX_REDIRECTS = 3
ROBOTS_TTL_SECONDS = 86_400
MAX_RETRY_AFTER_SECONDS = 3_600
MAX_429_RETRIES = 5
os.makedirs(os.path.dirname(DB_PATH) or ".", exist_ok=True)
def db():
connection = sqlite3.connect(DB_PATH, timeout=30, isolation_level=None)
connection.row_factory = sqlite3.Row
connection.execute("PRAGMA journal_mode=WAL")
connection.execute("PRAGMA foreign_keys=ON")
return connection
def now_ts():
return int(time.time())
def init_db():
with db() as connection:
connection.executescript(
"""
CREATE TABLE IF NOT EXISTS jobs (
id TEXT PRIMARY KEY,
actor TEXT NOT NULL,
url TEXT NOT NULL,
host TEXT NOT NULL,
status TEXT NOT NULL,
max_requests INTEGER NOT NULL,
completed_requests INTEGER NOT NULL DEFAULT 0,
requests_per_minute INTEGER NOT NULL,
next_eligible_at INTEGER NOT NULL,
retry_429_count INTEGER NOT NULL DEFAULT 0,
last_status INTEGER,
reason TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS host_limits (
host TEXT PRIMARY KEY,
next_eligible_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS robots_cache (
origin TEXT PRIMARY KEY,
body TEXT NOT NULL,
fetched_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS audit_events (
id TEXT PRIMARY KEY,
occurred_at INTEGER NOT NULL,
actor TEXT NOT NULL,
job_id TEXT,
action TEXT NOT NULL,
decision TEXT NOT NULL,
reason TEXT NOT NULL,
details TEXT NOT NULL
);
"""
)
def audit(connection, actor, action, decision, reason, job_id=None, details=None):
connection.execute(
"""
INSERT INTO audit_events
(id, occurred_at, actor, job_id, action, decision, reason, details)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""",
(
str(uuid.uuid4()),
now_ts(),
actor,
job_id,
action,
decision,
reason,
json.dumps(details or {}, separators=(",", ":")),
),
)
def authenticate(expected_token, authorization):
if not expected_token:
raise HTTPException(503, "Required application credential is not configured")
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(401, "Bearer authentication required")
supplied = authorization[7:]
if not hmac.compare_digest(supplied, expected_token):
raise HTTPException(401, "Invalid application credential")
def submitter(authorization: str | None = Header(default=None)):
authenticate(SUBMIT_TOKEN, authorization)
return "submitter"
def operator(authorization: str | None = Header(default=None)):
authenticate(OPERATOR_TOKEN, authorization)
return "operator"
def normalize_url(raw_url):
parsed = urlsplit(raw_url)
if parsed.scheme.lower() not in {"http", "https"}:
raise ValueError("Only http and https schemes are permitted")
if parsed.username or parsed.password:
raise ValueError("User information in URLs is prohibited")
if not parsed.hostname:
raise ValueError("A hostname is required")
host = parsed.hostname.lower().rstrip(".")
if host not in ALLOWED_HOSTS:
raise ValueError("Destination hostname is not allowlisted")
try:
port = parsed.port
except ValueError as exc:
raise ValueError("Invalid destination port") from exc
effective_port = port or (443 if parsed.scheme.lower() == "https" else 80)
if effective_port not in {80, 443}:
raise ValueError("Only destination ports 80 and 443 are permitted")
netloc = host
if port:
netloc = f"{host}:{port}"
path = parsed.path or "/"
return urlunsplit((parsed.scheme.lower(), netloc, path, parsed.query, ""))
def resolve_public_addresses(url):
parsed = urlsplit(url)
port = parsed.port or (443 if parsed.scheme == "https" else 80)
answers = socket.getaddrinfo(
parsed.hostname,
port,
type=socket.SOCK_STREAM,
)
addresses = {item[4][0] for item in answers}
if not addresses:
raise ValueError("Destination did not resolve")
for raw_address in addresses:
address = ipaddress.ip_address(raw_address)
if not address.is_global:
raise ValueError(
f"Destination resolved to prohibited address category: {address}"
)
return sorted(addresses)
def validate_destination(raw_url):
normalized = normalize_url(raw_url)
addresses = resolve_public_addresses(normalized)
return normalized, addresses
def parse_retry_after(value):
if not value:
return None
value = value.strip()
if value.isdigit():
return min(int(value), MAX_RETRY_AFTER_SECONDS)
try:
retry_date = parsedate_to_datetime(value)
if retry_date.tzinfo is None:
retry_date = retry_date.replace(tzinfo=timezone.utc)
delay = int(
(retry_date - datetime.now(timezone.utc)).total_seconds()
)
return min(max(delay, 0), MAX_RETRY_AFTER_SECONDS)
except (TypeError, ValueError, OverflowError):
return None
async def bounded_get(client, raw_url):
current = raw_url
for redirect_number in range(MAX_REDIRECTS + 1):
current, addresses = await asyncio.to_thread(
validate_destination, current
)
async with client.stream(
"GET",
current,
headers={
"User-Agent": BOT_USER_AGENT,
"Accept": "*/*",
},
follow_redirects=False,
) as response:
if response.status_code in {301, 302, 303, 307, 308}:
location = response.headers.get("location")
if not location:
raise ValueError("Redirect response omitted Location")
if redirect_number == MAX_REDIRECTS:
raise ValueError("Redirect limit exceeded")
current = urljoin(current, location)
continue
received = 0
async for chunk in response.aiter_bytes():
received += len(chunk)
if received > MAX_RESPONSE_BYTES:
raise ValueError("Response exceeded configured byte limit")
return {
"status": response.status_code,
"headers": dict(response.headers),
"url": current,
"addresses": addresses,
"bytes": received,
}
raise ValueError("Redirect processing failed")
async def robots_allowed(client, target_url):
parsed = urlsplit(target_url)
origin = f"{parsed.scheme}://{parsed.netloc}"
robots_url = f"{origin}/robots.txt"
current_time = now_ts()
with db() as connection:
cached = connection.execute(
"""
SELECT body FROM robots_cache
WHERE origin = ? AND expires_at > ?
""",
(origin, current_time),
).fetchone()
if cached:
parser = Protego.parse(cached["body"])
return parser.can_fetch(target_url, BOT_USER_AGENT), "cached"
result = await bounded_get(client, robots_url)
status = result["status"]
if status == 404:
return True, "robots_unavailable_404"
if status in {401, 403}:
return False, "robots_access_denied"
if status >= 500:
raise RuntimeError("robots_server_error")
if status != 200:
raise RuntimeError(f"robots_unexpected_status_{status}")
response = await client.get(
result["url"],
headers={"User-Agent": BOT_USER_AGENT},
follow_redirects=False,
)
body = response.text[:500_000]
with db() as connection:
connection.execute(
"""
INSERT INTO robots_cache
(origin, body, fetched_at, expires_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(origin) DO UPDATE SET
body = excluded.body,
fetched_at = excluded.fetched_at,
expires_at = excluded.expires_at
""",
(
origin,
body,
current_time,
current_time + ROBOTS_TTL_SECONDS,
),
)
parser = Protego.parse(body)
return parser.can_fetch(target_url, BOT_USER_AGENT), "fetched"
def claim_job():
current_time = now_ts()
with db() as connection:
connection.execute("BEGIN IMMEDIATE")
row = connection.execute(
"""
SELECT j.*
FROM jobs j
LEFT JOIN host_limits h ON h.host = j.host
WHERE j.status IN ('pending', 'delayed')
AND j.next_eligible_at <= ?
AND COALESCE(h.next_eligible_at, 0) <= ?
ORDER BY j.created_at
LIMIT 1
""",
(current_time, current_time),
).fetchone()
if not row:
connection.execute("COMMIT")
return None
connection.execute(
"""
UPDATE jobs
SET status = 'active', updated_at = ?
WHERE id = ?
""",
(current_time, row["id"]),
)
audit(
connection,
"scheduler",
"job.claim",
"allowed",
"eligible_for_dispatch",
row["id"],
)
connection.execute("COMMIT")
return dict(row)
def suspend_job(job_id, reason, details=None):
with db() as connection:
connection.execute("BEGIN IMMEDIATE")
connection.execute(
"""
UPDATE jobs
SET status = 'suspended', reason = ?, updated_at = ?
WHERE id = ?
""",
(reason, now_ts(), job_id),
)
audit(
connection,
"scheduler",
"job.suspend",
"suspended",
reason,
job_id,
details,
)
connection.execute("COMMIT")
async def process_job(client, job):
job_id = job["id"]
try:
normalized, addresses = await asyncio.to_thread(
validate_destination, job["url"]
)
except Exception as exc:
suspend_job(job_id, "destination_validation_failed", {"error": str(exc)})
return
try:
allowed, robots_source = await robots_allowed(client, normalized)
except Exception as exc:
suspend_job(job_id, "robots_policy_unavailable", {"error": str(exc)})
return
if not allowed:
suspend_job(
job_id,
"robots_disallowed",
{"source": robots_source, "url": normalized},
)
return
try:
result = await bounded_get(client, normalized)
except Exception as exc:
suspend_job(job_id, "outbound_request_failed", {"error": str(exc)})
return
current_time = now_ts()
status = result["status"]
with db() as connection:
connection.execute("BEGIN IMMEDIATE")
current = connection.execute(
"SELECT * FROM jobs WHERE id = ?",
(job_id,),
).fetchone()
if not current or current["status"] != "active":
audit(
connection,
"scheduler",
"job.dispatch",
"denied",
"job_no_longer_active",
job_id,
)
connection.execute("COMMIT")
return
interval = max(1, int(60 / current["requests_per_minute"]))
if status == 429:
retries = current["retry_429_count"] + 1
supplied_delay = parse_retry_after(
result["headers"].get("retry-after")
)
fallback = min(300, 2 ** min(retries, 8))
delay = supplied_delay if supplied_delay is not None else fallback
delay += random.randint(0, 3)
eligible = current_time + delay
connection.execute(
"""
INSERT INTO host_limits (host, next_eligible_at)
VALUES (?, ?)
ON CONFLICT(host) DO UPDATE SET
next_eligible_at = MAX(next_eligible_at, excluded.next_eligible_at)
""",
(current["host"], eligible),
)
if retries >= MAX_429_RETRIES:
new_status = "suspended"
reason = "repeated_upstream_429"
else:
new_status = "delayed"
reason = "upstream_429_backoff"
connection.execute(
"""
UPDATE jobs
SET status = ?, retry_429_count = ?, last_status = 429,
next_eligible_at = ?, reason = ?, updated_at = ?
WHERE id = ?
""",
(
new_status,
retries,
eligible,
reason,
current_time,
job_id,
),
)
audit(
connection,
"scheduler",
"upstream.response",
new_status,
reason,
job_id,
{
"retry_after_seconds": delay,
"retry_number": retries,
},
)
connection.execute("COMMIT")
return
completed = current["completed_requests"] + 1
if completed >= current["max_requests"]:
new_status = "completed"
reason = "request_budget_completed"
elif 200 <= status < 400:
new_status = "delayed"
reason = "host_pacing"
else:
new_status = "suspended"
reason = f"unexpected_upstream_status_{status}"
eligible = current_time + interval
connection.execute(
"""
INSERT INTO host_limits (host, next_eligible_at)
VALUES (?, ?)
ON CONFLICT(host) DO UPDATE SET
next_eligible_at = MAX(next_eligible_at, excluded.next_eligible_at)
""",
(current["host"], eligible),
)
connection.execute(
"""
UPDATE jobs
SET status = ?, completed_requests = ?, last_status = ?,
retry_429_count = 0, next_eligible_at = ?,
reason = ?, updated_at = ?
WHERE id = ?
""",
(
new_status,
completed,
status,
eligible,
reason,
current_time,
job_id,
),
)
audit(
connection,
"scheduler",
"upstream.response",
new_status,
reason,
job_id,
{
"status": status,
"bytes": result["bytes"],
"resolved_addresses": addresses,
},
)
connection.execute("COMMIT")
async def scheduler():
timeout = httpx.Timeout(15.0, connect=5.0)
limits = httpx.Limits(max_connections=4, max_keepalive_connections=2)
async with httpx.AsyncClient(
timeout=timeout,
limits=limits,
trust_env=False,
) as client:
while True:
job = await asyncio.to_thread(claim_job)
if job:
await process_job(client, job)
else:
await asyncio.sleep(1)
@asynccontextmanager
async def lifespan(app):
init_db()
if not SUBMIT_TOKEN or not OPERATOR_TOKEN:
raise RuntimeError("Both gateway tokens must be configured")
if hmac.compare_digest(SUBMIT_TOKEN, OPERATOR_TOKEN):
raise RuntimeError("Submit and operator tokens must be different")
if not ALLOWED_HOSTS:
raise RuntimeError("ALLOWED_HOSTS must contain at least one hostname")
task = None
if WORKER_ENABLED:
task = asyncio.create_task(scheduler())
yield
if task:
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
app = FastAPI(
title="Accountable Bot Gateway",
docs_url=None,
redoc_url=None,
lifespan=lifespan,
)
class JobCreate(BaseModel):
url: str
max_requests: int = Field(ge=1, le=100)
requests_per_minute: int = Field(ge=1, le=30)
class OperatorAction(BaseModel):
reason: str = Field(min_length=3, max_length=300)
@app.get("/health")
def health():
return {"status": "ok"}
@app.post("/v1/jobs", status_code=201)
async def create_job(
payload: JobCreate,
request: Request,
actor: str = Depends(submitter),
):
try:
normalized, addresses = await asyncio.to_thread(
validate_destination, payload.url
)
except Exception as exc:
raise HTTPException(400, str(exc)) from exc
parsed = urlsplit(normalized)
job_id = str(uuid.uuid4())
created = now_ts()
with db() as connection:
connection.execute("BEGIN IMMEDIATE")
connection.execute(
"""
INSERT INTO jobs
(id, actor, url, host, status, max_requests,
completed_requests, requests_per_minute,
next_eligible_at, retry_429_count,
created_at, updated_at)
VALUES (?, ?, ?, ?, 'pending', ?, 0, ?, ?, 0, ?, ?)
""",
(
job_id,
actor,
normalized,
parsed.hostname,
payload.max_requests,
payload.requests_per_minute,
created,
created,
created,
),
)
audit(
connection,
actor,
"job.create",
"allowed",
"validated_destination",
job_id,
{
"request_id": request.headers.get("x-request-id"),
"resolved_addresses": addresses,
"max_requests": payload.max_requests,
"requests_per_minute": payload.requests_per_minute,
},
)
connection.execute("COMMIT")
return {"id": job_id, "status": "pending"}
@app.get("/v1/jobs/{job_id}")
def get_job(job_id: str, actor: str = Depends(submitter)):
with db() as connection:
row = connection.execute(
"""
SELECT id, url, host, status, max_requests,
completed_requests, requests_per_minute,
next_eligible_at, retry_429_count,
last_status, reason, created_at, updated_at
FROM jobs WHERE id = ?
""",
(job_id,),
).fetchone()
if not row:
raise HTTPException(404, "Job not found")
return dict(row)
@app.get("/v1/jobs/{job_id}/events")
def get_events(job_id: str, actor: str = Depends(submitter)):
with db() as connection:
rows = connection.execute(
"""
SELECT id, occurred_at, actor, action, decision, reason, details
FROM audit_events
WHERE job_id = ?
ORDER BY occurred_at, id
""",
(job_id,),
).fetchall()
return [dict(row) for row in rows]
def operator_transition(job_id, target_status, reason, allowed_states):
with db() as connection:
connection.execute("BEGIN IMMEDIATE")
row = connection.execute(
"SELECT status FROM jobs WHERE id = ?",
(job_id,),
).fetchone()
if not row:
connection.execute("ROLLBACK")
raise HTTPException(404, "Job not found")
if row["status"] not in allowed_states:
connection.execute("ROLLBACK")
raise HTTPException(409, "Transition is not allowed from current state")
connection.execute(
"""
UPDATE jobs
SET status = ?, reason = ?, next_eligible_at = ?, updated_at = ?
WHERE id = ?
""",
(target_status, reason, now_ts(), now_ts(), job_id),
)
audit(
connection,
"operator",
f"job.{target_status}",
target_status,
reason,
job_id,
)
connection.execute("COMMIT")
@app.post("/v1/jobs/{job_id}/suspend")
def suspend(
job_id: str,
payload: OperatorAction,
actor: str = Depends(operator),
):
operator_transition(
job_id,
"suspended",
payload.reason,
{"pending", "active", "delayed"},
)
return {"id": job_id, "status": "suspended"}
@app.post("/v1/jobs/{job_id}/reactivate")
def reactivate(
job_id: str,
payload: OperatorAction,
actor: str = Depends(operator),
):
operator_transition(
job_id,
"pending",
payload.reason,
{"suspended"},
)
return {"id": job_id, "status": "pending"}
@app.post("/v1/jobs/{job_id}/cancel")
def cancel(
job_id: str,
payload: OperatorAction,
actor: str = Depends(operator),
):
operator_transition(
job_id,
"cancelled",
payload.reason,
{"pending", "active", "delayed", "suspended"},
)
return {"id": job_id, "status": "cancelled"}
The robots fetch helper limits and validates the initial robots request, but then performs a second request to obtain the text for parsing. For a production implementation, refactor the bounded request helper to return the already streamed bytes so the policy file is fetched only once. Preserve the same byte limit, redirect validation, destination checks, timeouts, and outbound network restrictions when making that change.
The application does not log bearer tokens. It records internal actor labels, job identifiers, decisions, reasons, counters, statuses, and selected destination-validation details. Protect the SQLite file because it still contains destination URLs and operational history.
Start in control-plane test mode
Export the required variables. Replace test.example.org with an exact hostname you own or are authorized to test. Keep the worker disabled until authentication, authorization, validation, and state transitions have been checked.
export GATEWAY_SUBMIT_TOKEN='your-locally-generated-submit-secret'
export GATEWAY_OPERATOR_TOKEN='your-different-operator-secret'
export ALLOWED_HOSTS='test.example.org'
export BOT_USER_AGENT='AuthorizedGatewayBot/1.0'
export GATEWAY_DB='data/gateway.db'
export WORKER_ENABLED='0'
uvicorn app:app --host 127.0.0.1 --port 8080
Binding to 127.0.0.1 is appropriate when the Localtonet client runs on the same host. If the client runs on another device, bind only to a deliberately selected reachable interface and protect the local network path. Do not use a broad network bind without understanding who can reach it.
Verify the gateway locally before enabling work
Open a second terminal, activate the same environment if needed, and export the application credentials there. The variables keep secrets out of request URLs and out of the article's example output.
export BASE_URL='http://127.0.0.1:8080'
export SUBMIT_TOKEN='your-locally-generated-submit-secret'
export OPERATOR_TOKEN='your-different-operator-secret'
export OWNED_TEST_URL='https://test.example.org/authorized-test-resource'
1. Check the minimal health route
curl -i "$BASE_URL/health"
Expect HTTP 200 and {"status":"ok"}. This proves only that the process is listening. It does not prove protected-route behavior.
2. Confirm that missing credentials are rejected
curl -i \
-H 'Content-Type: application/json' \
-d "{\"url\":\"$OWNED_TEST_URL\",\"max_requests\":1,\"requests_per_minute\":1}" \
"$BASE_URL/v1/jobs"
Expect HTTP 401. No job should be created.
3. Confirm that prohibited destinations fail before storage
curl -i \
-H "Authorization: Bearer $SUBMIT_TOKEN" \
-H 'Content-Type: application/json' \
-d '{"url":"http://127.0.0.1/","max_requests":1,"requests_per_minute":1}' \
"$BASE_URL/v1/jobs"
Expect HTTP 400 because loopback is not allowlisted and is not a globally routable destination. Repeat with a private address, link-local address, non-approved hostname, unsupported scheme, embedded credentials, and non-approved port. Each request should fail without creating work.
4. Create an authorized job while dispatch remains disabled
curl -sS \
-H "Authorization: Bearer $SUBMIT_TOKEN" \
-H 'Content-Type: application/json' \
-H 'X-Request-ID: local-verification-001' \
-d "{\"url\":\"$OWNED_TEST_URL\",\"max_requests\":2,\"requests_per_minute\":1}" \
"$BASE_URL/v1/jobs"
Copy the returned job identifier into a local variable:
export JOB_ID='returned-job-id'
Inspect the persisted state:
curl -sS \
-H "Authorization: Bearer $SUBMIT_TOKEN" \
"$BASE_URL/v1/jobs/$JOB_ID"
Expect the job to remain pending because WORKER_ENABLED is set to 0.
5. Test operator-only state changes
First try to suspend with the submission credential:
curl -i \
-H "Authorization: Bearer $SUBMIT_TOKEN" \
-H 'Content-Type: application/json' \
-d '{"reason":"scope boundary test"}' \
"$BASE_URL/v1/jobs/$JOB_ID/suspend"
Expect HTTP 401 because the route requires the separate operator token. Now perform the authorized action:
curl -sS \
-H "Authorization: Bearer $OPERATOR_TOKEN" \
-H 'Content-Type: application/json' \
-d '{"reason":"local suspension verification"}' \
"$BASE_URL/v1/jobs/$JOB_ID/suspend"
Reactivate it deliberately:
curl -sS \
-H "Authorization: Bearer $OPERATOR_TOKEN" \
-H 'Content-Type: application/json' \
-d '{"reason":"local controls verified"}' \
"$BASE_URL/v1/jobs/$JOB_ID/reactivate"
Inspect the audit events:
curl -sS \
-H "Authorization: Bearer $SUBMIT_TOKEN" \
"$BASE_URL/v1/jobs/$JOB_ID/events"
Confirm that the event sequence identifies creation, suspension, and reactivation without containing either bearer token.
6. Test restart persistence
Stop Uvicorn with Ctrl+C, start it again with the same environment and database path, and request the job:
uvicorn app:app --host 127.0.0.1 --port 8080
curl -sS \
-H "Authorization: Bearer $SUBMIT_TOKEN" \
"$BASE_URL/v1/jobs/$JOB_ID"
The job, counters, current state, reason, and events should still exist. A restart must not silently reactivate a suspended job or reset a request budget.
7. Enable the worker against your controlled origin
Stop the process, change WORKER_ENABLED to 1, and restart:
export WORKER_ENABLED='1'
uvicorn app:app --host 127.0.0.1 --port 8080
Your controlled origin should provide a known robots.txt policy and a small authorized test resource. Create a one-request job and inspect its state and events. Then configure your controlled origin to return a 429 with a valid Retry-After value. Confirm that the job enters delayed, the event contains a bounded delay, and the host is not contacted again before the eligibility time.
Also test a Retry-After HTTP date, an invalid value, a redirect to another approved hostname, a redirect to an unapproved hostname, a robots disallow rule, a 403 robots response, a 404 robots response, a 5xx robots response, an oversized body, and five consecutive 429 responses. The final case should suspend the job rather than retry forever.
Generate robots responses, redirects, failures, and rate limits only from an origin you control or are explicitly authorized to test. Keep request budgets low while validating scheduler behavior.
Configure the Localtonet HTTP tunnel
Add public ingress only after local authentication, authorization, state transitions, destination validation, and restart behavior work correctly. The Localtonet client must run on a device that can reach the gateway's configured local address and port.
HTTP tunnels may use Random Sub Domain, Custom Sub Domain, or Custom Domain as the Process Type. All serve the configured content at a public HTTPS address. Use the options currently available in your dashboard. Do not copy a server code, region, custom-domain record, device token, or public hostname from an example.
Install and run the Localtonet client
Install the Localtonet application for the operating system on the device that can reach the gateway. Run the client before configuring the HTTP tunnel.
Select the HTTP tunnel Process Type
Open the HTTP tunnel configuration and select Random Sub Domain, Custom Sub Domain, or Custom Domain according to the choices currently available to you.
Select the device token and relay server
Select the device-specific authentication token for the client that will run the tunnel, then choose an available server or region from the current dashboard. Keep the token private and do not hardcode server values in application source.
Enter the local gateway target
Enter the local IP address and port where the verified gateway listens. Use 127.0.0.1 and port 8080 only if the Localtonet client and gateway run on the same host with this tutorial's startup command.
Start the tunnel
Press Start after reviewing the configuration. Creating a tunnel does not mean it is running. The assigned public endpoint is available only while the selected client is connected and the tunnel is running.
Consult the Localtonet HTTP tunnel documentation for the current dashboard workflow and currently available choices. Exact custom-domain DNS requirements must come from the current product documentation rather than an old or unrelated example.
Internet-facing endpoints receive unexpected traffic. Keep authentication mandatory on every job and event route, retain the minimal unauthenticated health response, disable framework documentation routes, reject unsupported methods, constrain request bodies, and monitor failed access attempts. A Localtonet tunnel provides reachability, not application authorization.
Verify the public endpoint separately
Public verification is not part of creating the tunnel. Perform it after the documented configuration sequence is complete and the tunnel is running. Assign the Localtonet HTTPS address to a shell variable:
export PUBLIC_URL='https://your-assigned-public-address'
Confirm public connectivity
curl -i "$PUBLIC_URL/health"
Expect the same minimal HTTP 200 response produced locally. If local health works but public health does not, investigate the Localtonet client, selected device, tunnel state, and local target before changing application authentication.
Confirm that protected routes remain protected
curl -i "$PUBLIC_URL/v1/jobs/not-a-real-job"
Expect HTTP 401. A successful tunnel must not make protected routes public.
Submit one authorized public request
curl -sS \
-H "Authorization: Bearer $SUBMIT_TOKEN" \
-H 'Content-Type: application/json' \
-H 'X-Request-ID: public-verification-001' \
-d "{\"url\":\"$OWNED_TEST_URL\",\"max_requests\":1,\"requests_per_minute\":1}" \
"$PUBLIC_URL/v1/jobs"
Confirm that the request produces a new job and audit event. Do not paste the command with an expanded token into tickets, screenshots, chat messages, or shared shell transcripts.
Repeat the scope test publicly
Attempt an operator route with the submission credential and confirm it fails. Then use the operator credential to suspend the test job. This verifies that the public route reaches the same application policy boundary rather than a debug or alternate listener.
Verify tunnel shutdown
Stop the HTTP tunnel and confirm that the public address no longer reaches the gateway. The local health route should remain available. Remember that stopping ingress does not automatically stop already queued outbound work. Suspend affected jobs or stop the worker when outbound execution must cease.
Operate the gateway safely
Run it under a process manager
Interactive Uvicorn is suitable for verification, but routine operation needs a process manager appropriate to the operating system. Configure it to set secrets through protected environment handling, start in the correct working directory, preserve the SQLite path, restart after failure, and capture sanitized standard output. Do not place secrets directly in a globally readable service definition.
Run only one worker-enabled application process with this SQLite scheduler. Multiple Uvicorn workers would each start a scheduler task. SQLite transactions prevent some duplicate claims, but this tutorial is not designed or tested as a multi-process distributed scheduler. For horizontal scaling, move jobs, leases, host pacing, and audit writes to a shared transactional service with explicit distributed coordination.
Back up and protect durable state
Back up the database using a SQLite-aware process rather than copying files while ignoring write-ahead logging. Restrict filesystem access to the gateway account and authorized operators. Test restoration and verify that restored suspended jobs remain suspended. Decide how long audit events must be retained based on operational, privacy, and legal requirements.
Monitor decisions instead of uptime alone
Track authentication failures, authorization failures, rejected destinations, jobs by state, robots denials, robots retrieval failures, 429 responses, selected backoff times, exhausted budgets, suspensions, reactivations, cancellations, and unexpected upstream statuses. Alert on meaningful patterns, such as repeated prohibited destinations from one caller or repeated reactivation without corrective action.
Avoid placing complete URLs in broad metric labels because query strings may contain private information and high-cardinality values can damage monitoring performance. Keep detailed job records in the protected audit store and use bounded categories for metrics.
Use a deliberate incident sequence
- Stop new dispatches by suspending the affected job, identity, or destination.
- Stop the Localtonet tunnel if public control access should also be removed.
- Preserve the database, logs, policy configuration, and relevant process information.
- Determine whether the cause was an unsafe caller, compromised credential, DNS change, redirect, stale policy, scheduler defect, or destination feedback.
- Rotate application or Localtonet credentials if exposure is suspected.
- Correct the root cause and test against a controlled origin.
- Reactivate through the operator route with a meaningful reason.
- Observe the first resumed requests and suspend again if the unsafe pattern returns.
Separate a delay from a suspension
A delayed job has a known next-eligible time, such as host pacing or bounded 429 backoff. A suspended job represents a safety or policy intervention and has no automatic recovery path. Keeping these states separate prevents a timer from undoing a serious intervention.
Reactivation preserves request counters and audit history. It does not reset a consumed budget or erase previous 429 events. If a materially different target or policy is required, create a replacement job so the original decision history remains intact.
Troubleshoot by layer
| Symptom | Likely layer | Checks |
|---|---|---|
| The application exits during startup | Configuration | Confirm both tokens are present and different, ALLOWED_HOSTS is non-empty, the database directory is writable, and dependencies were installed in the active environment. |
| Local health does not respond | Gateway process | Confirm Uvicorn is running on 127.0.0.1:8080, another process is not using the port, and the request uses the same address family and port. |
| An approved hostname is rejected | Destination policy | Check exact lowercase allowlist spelling, trailing dots, scheme, effective port, DNS answers, and whether any returned address is non-global. |
| A hostname sometimes passes and sometimes fails | DNS or mixed addressing | Inspect every A and AAAA answer. The reference policy rejects the destination if any resolved address is prohibited. |
| A job remains pending | Worker configuration | Confirm WORKER_ENABLED=1, restart after changing it, and inspect host eligibility timestamps and the process log. |
| A job is suspended before retrieval | Robots or destination validation | Inspect the job reason and audit events for robots access denial, server failure, unsafe redirect, prohibited resolution, or parsing failure. |
| Requests continue sooner than expected | Rate coordination | Confirm only one worker-enabled process is running, inspect host_limits, and verify the jobs use the same normalized host. |
| A 429 causes suspension | Bounded retry policy | Inspect the retry counter. Five 429 responses suspend the job by design. Review destination feedback before reactivation. |
| The local URL works but the public URL does not | Localtonet lifecycle or target | Confirm the selected client is connected, the tunnel was started, and the configured local address and port are reachable from the client device. |
| Public health works but protected calls fail | Application authentication | Confirm the correct application token is sent in the Authorization header and that shell quoting did not add spaces or line breaks. |
| State disappears after restart | Database path | Confirm the restarted process uses the same working directory and GATEWAY_DB value. Check filesystem permissions and service-manager environment configuration. |
The database does not need either bearer token to preserve jobs and audit events. When sharing diagnostics, remove private URLs, internal identifiers, filesystem paths, and other sensitive context. Never attach environment files, Localtonet device tokens, authorization headers, or shell history containing expanded secrets.
Frequently asked questions
Does a Localtonet HTTP tunnel authenticate callers of the gateway?
The tunnel provides public reachability to the local IP address and port you configure. The application must authenticate and authorize every protected request. Possession of the public URL is not proof that a caller is trusted.
Why are private and link-local destinations rejected?
Allowing caller-selected requests to those destinations could expose loopback services, LAN systems, container infrastructure, or cloud metadata endpoints. The gateway therefore requires every resolved address to be globally routable and recommends an outbound network policy as a second boundary.
Why does the gateway validate redirects manually?
An approved starting URL can redirect to an unapproved hostname, prohibited port, or private address. Automatic redirect following can bypass checks applied only to the first URL. Manual processing lets the gateway reapply scheme, host, port, DNS, and address rules to every hop.
Does an allowed robots.txt path authorize retrieval?
No. Robots rules communicate crawler preferences. They do not override authentication, terms, privacy requirements, copyright obligations, access restrictions, direct instructions, or the requirement to have authorization for the automation.
What happens when an upstream server returns HTTP 429?
The worker parses a valid Retry-After value as either seconds or an HTTP date, caps the delay, adds jitter, and stores a host-level next-eligible time. If Retry-After is absent or invalid, it applies bounded exponential backoff. Five 429 responses suspend the job for review.
Can I run several Uvicorn workers with this SQLite scheduler?
This tutorial is designed for one worker-enabled process. A distributed deployment needs a shared transactional job store, distributed leases, and coordinated host-level rate limiting. Do not assume that independent processes with local state enforce one collective budget.
Does stopping the Localtonet tunnel stop outbound jobs?
No. Stopping the tunnel removes that public ingress path, but the local scheduler can continue processing previously stored jobs. Suspend the jobs, disable the worker, or stop the gateway process when outbound work must cease.
Does creating a Localtonet tunnel make it immediately available?
No. Creating a tunnel does not mean it is running. Press Start after reviewing the configuration. The endpoint remains available only while the selected Localtonet client is connected and the tunnel is running.
Publish your verified gateway with Localtonet
Build and test the application boundary first, keep automation limited to authorized destinations, then use a Localtonet HTTP tunnel to provide controlled public HTTPS reachability without inbound router port forwarding.
Get Started Free →Corrections & updates
Substantive changes approved by the Localtonet editorial team are listed transparently below.
Localtonet is a secure multi-protocol tunneling and proxy platform designed to expose localhost, devices, private services, and AI agents to the public internet supporting HTTP/HTTPS tunnels, TCP/UDP forwarding, mobile proxy infrastructure, file server publishing, latency-optimized game connectivity, and developer-ready AI agent endpoint exposure from a single unified control plane.