test(cloudflared): add the default molecule scenario
Runs without Cloudflare and without a real cloudflared: a stub of the Cloudflare API on the controller's loopback answers the tunnel, zone and DNS record calls through cloudflared_api_base_url, a stub binary stands in for the daemon, and the releases come from file:// URLs. Covers the converge with an update through _binary_update and its idempotence, the rendered files and the running unit, the input asserts, the deleted-tunnel and DNS guards, a stale hash and a failed checksum, the mint entry point (as child processes outside CI) and the remove path. The cloudflare_dns calls cannot reach the stub and are not run. Assisted-by: Claude Code:claude-opus-5-5
This commit is contained in:
1 parent
e308683431
commit
9a626962a5
8 files changed
+831
No files matched your search
@@ -0,0 +1,168 @@
|
||||
"""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, format, *args):
|
||||
pass
|
||||
|
||||
def _send(self, status, result=None):
|
||||
body = json.dumps(
|
||||
{"success": status == 200, "errors": [], "result": result}
|
||||
).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:
|
||||
records = [
|
||||
r
|
||||
for r in RECORDS
|
||||
if all(r.get(k) == query[k] for k in ("type", "content") if k in query)
|
||||
]
|
||||
return self._send(200, records)
|
||||
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)
|
||||
|
||||
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()
|
||||
Reference in new issue
Block a user