The overwrite guard listed the zone's first 100 records only, so a record further on went unseen. It now queries each ingress hostname by name and compares names case-insensitively, and the prune listing pages through result_info.total_pages. Query values are urlencoded. The template task validates config.yml with cloudflared before it replaces the file; the rendered content is unchanged. The API stub filters by name and pages to match. Assisted-by: Claude Code:claude-opus-5-5
185 lines
6.4 KiB
Python
185 lines
6.4 KiB
Python
"""Stub of the Cloudflare API calls of the cloudflared role, for its molecule scenario.
|
|
|
|
Listens on 127.0.0.1 on a free port, writes the port to <state-dir>/port and its pid to
|
|
<state-dir>/pid, and appends one JSON line per request (method, path, status; never a secret)
|
|
to <state-dir>/requests.log. Exits by itself after --lifetime seconds, so a cancelled run
|
|
leaves nothing running for long.
|
|
"""
|
|
|
|
import argparse
|
|
import base64
|
|
import binascii
|
|
import json
|
|
import os
|
|
import re
|
|
import threading
|
|
import uuid
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
from urllib.parse import parse_qs, urlsplit
|
|
|
|
PREFIX = "/client/v4"
|
|
TOKEN = "molecule-not-a-token"
|
|
ACCOUNT = "molecule-account"
|
|
ZONE_NAME = "example.test"
|
|
ZONE_ID = "molecule-zone"
|
|
# Tunnel id -> deleted_at (None while the tunnel exists).
|
|
TUNNELS = {
|
|
"6f1a6e2c-0000-4000-8000-000000000001": None,
|
|
"6f1a6e2c-0000-4000-8000-000000000002": "2026-01-01T00:00:00Z",
|
|
}
|
|
RECORDS = [
|
|
{"name": "taken.example.test", "type": "A", "content": "192.0.2.10"},
|
|
{
|
|
"name": "moved.example.test",
|
|
"type": "CNAME",
|
|
"content": "6f1a6e2c-0000-4000-8000-000000000009.cfargotunnel.com",
|
|
},
|
|
]
|
|
TUNNEL_PATH = re.compile(r"^/accounts/([^/]+)/cfd_tunnel(?:/([^/]+))?$")
|
|
RECORDS_PATH = re.compile(r"^/zones/([^/]+)/dns_records$")
|
|
LOCK = threading.Lock()
|
|
|
|
|
|
class Handler(BaseHTTPRequestHandler):
|
|
state_dir = "."
|
|
|
|
# Quiet: the requests go to requests.log instead of stderr.
|
|
def log_message(self, *args):
|
|
pass
|
|
|
|
def _send(self, status, result=None, result_info=None):
|
|
reply = {"success": status == 200, "errors": [], "result": result}
|
|
if result_info is not None:
|
|
reply["result_info"] = result_info
|
|
body = json.dumps(reply).encode()
|
|
self.send_response(status)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
with (
|
|
LOCK,
|
|
open(
|
|
os.path.join(self.state_dir, "requests.log"), "a", encoding="utf-8"
|
|
) as log,
|
|
):
|
|
log.write(
|
|
json.dumps(
|
|
{"method": self.command, "path": self.path, "status": status}
|
|
)
|
|
+ "\n"
|
|
)
|
|
|
|
def _route(self):
|
|
if self.headers.get("Authorization") != f"Bearer {TOKEN}":
|
|
return self._send(403)
|
|
url = urlsplit(self.path)
|
|
if not url.path.startswith(PREFIX):
|
|
return self._send(404)
|
|
path = url.path[len(PREFIX) :]
|
|
query = {key: values[0] for key, values in parse_qs(url.query).items()}
|
|
|
|
match = TUNNEL_PATH.match(path)
|
|
if match and match.group(1) == ACCOUNT:
|
|
return self._tunnel(match.group(2))
|
|
match = RECORDS_PATH.match(path)
|
|
if self.command == "GET" and match and match.group(1) == ZONE_ID:
|
|
return self._records(query)
|
|
if self.command == "GET" and path == "/zones":
|
|
zones = (
|
|
[{"id": ZONE_ID, "name": ZONE_NAME}]
|
|
if query.get("name") == ZONE_NAME
|
|
else []
|
|
)
|
|
return self._send(200, zones)
|
|
return self._send(404)
|
|
|
|
# Filters by name (case-insensitive, as DNS names are), type and content, and pages.
|
|
def _records(self, query):
|
|
records = [
|
|
r
|
|
for r in RECORDS
|
|
if ("name" not in query or r["name"].lower() == query["name"].lower())
|
|
and all(r[k] == query[k] for k in ("type", "content") if k in query)
|
|
]
|
|
per_page = int(query.get("per_page", "100"))
|
|
page = int(query.get("page", "1"))
|
|
total_pages = max(1, -(-len(records) // per_page))
|
|
chunk = records[(page - 1) * per_page : page * per_page]
|
|
info = {
|
|
"page": page,
|
|
"per_page": per_page,
|
|
"total_count": len(records),
|
|
"total_pages": total_pages,
|
|
}
|
|
return self._send(200, chunk, info)
|
|
|
|
def _tunnel(self, tunnel_id):
|
|
if tunnel_id is None and self.command == "POST":
|
|
return self._create()
|
|
if tunnel_id not in TUNNELS:
|
|
return self._send(404)
|
|
if self.command == "GET":
|
|
return self._send(200, {"id": tunnel_id, "deleted_at": TUNNELS[tunnel_id]})
|
|
if self.command == "DELETE":
|
|
TUNNELS[tunnel_id] = "2026-01-01T00:00:00Z"
|
|
return self._send(200, {"id": tunnel_id})
|
|
return self._send(405)
|
|
|
|
# Accepts only what the real API needs for a locally managed tunnel: a name, config_src
|
|
# local and a base64 secret of at least 32 bytes.
|
|
def _create(self):
|
|
try:
|
|
body = json.loads(
|
|
self.rfile.read(int(self.headers.get("Content-Length", "0")))
|
|
)
|
|
secret = base64.b64decode(body["tunnel_secret"], validate=True)
|
|
except (ValueError, KeyError, TypeError, binascii.Error):
|
|
return self._send(400)
|
|
if (
|
|
not body.get("name")
|
|
or body.get("config_src") != "local"
|
|
or len(secret) < 32
|
|
):
|
|
return self._send(400)
|
|
tunnel_id = str(uuid.uuid4())
|
|
TUNNELS[tunnel_id] = None
|
|
credentials = {
|
|
"AccountTag": ACCOUNT,
|
|
"TunnelID": tunnel_id,
|
|
"TunnelName": body["name"],
|
|
"TunnelSecret": body["tunnel_secret"],
|
|
}
|
|
return self._send(
|
|
200,
|
|
{"id": tunnel_id, "name": body["name"], "credentials_file": credentials},
|
|
)
|
|
|
|
do_GET = _route
|
|
do_POST = _route
|
|
do_DELETE = _route
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--state-dir", required=True)
|
|
parser.add_argument("--lifetime", type=int, default=1500)
|
|
args = parser.parse_args()
|
|
|
|
os.makedirs(args.state_dir, exist_ok=True)
|
|
Handler.state_dir = args.state_dir
|
|
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
|
for name, value in (("pid", os.getpid()), ("port", server.server_address[1])):
|
|
tmp = os.path.join(args.state_dir, name + ".tmp")
|
|
with open(tmp, "w", encoding="utf-8") as handle:
|
|
handle.write(f"{value}\n")
|
|
os.replace(tmp, os.path.join(args.state_dir, name))
|
|
timer = threading.Timer(args.lifetime, server.shutdown)
|
|
timer.daemon = True
|
|
timer.start()
|
|
server.serve_forever()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|