diff --git a/docs/reference/deployment/volcengine-cn-beijing-pg-gateway.md b/docs/reference/deployment/volcengine-cn-beijing-pg-gateway.md new file mode 100644 index 0000000000..b69390abac --- /dev/null +++ b/docs/reference/deployment/volcengine-cn-beijing-pg-gateway.md @@ -0,0 +1,312 @@ +# 火山引擎 (cn-beijing) PostgreSQL 16 与远程协同网关部署参考 + +本文档规范 LoopX 在火山引擎北京地域(`cn-beijing`)的云端协同底座部署架构、参数化模板、最小权限开通清单及双人/多机分治联通流程。 + +> [!CAUTION] +> **严格红线:严禁未经用户确认自动购买云资源或改线上配置** +> 任何脚本、Agent 或自动化流绝不允许未经用户交互确认直接调用云厂商计费/下单 API(如自动开通包年包月或按量付费 RDS/ECS)或静默篡改生产环境线上防火墙/安全组/IAM 策略。所有模板与命令均为声明式、受审阅的参数化资产,仅在用户显式授权后由用户或受控发布流程执行。 + +--- + +## 1. 架构总览 (Multi-Machine Split Architecture) + +为了实现本地高性能交互与云端廉价长任务并行的双人/多机协同,LoopX 采用对齐 `postgresql-authority-service-v0` 与 `monorepo-distribution-split-v0` 的协同底座: + +``` ++-----------------------------+ +-----------------------------+ +| Local Operator Machine | | Cloud Worker Machine | +| operator.local | | worker.cloud | +| (Operator Workstation) | | (Volcengine ECS / Ark LLM) | ++--------------+--------------+ +--------------+--------------+ + | | + | HTTPS / TLS 1.3 (Bearer Credential) | HTTPS / TLS 1.3 (Bearer Credential) + | `examples/coordination/ | `examples/coordination/ + | remote-authority-client.ts` | remote-authority-client.ts` + v v ++---------------------------------------------------------------------------+ +| Volcengine `cn-beijing` Remote Authority Gateway | +| | +| +---------------------------+ +---------------------------------+ | +| | Caddy TLS Reverse Proxy | ----> | RemoteAuthorityService (Node24) | | +| | (TLS termination, | :8443 | `loopx/control_plane/ | | +| | HSTS, IP allowlist) | | coordination/remote_authority` | | +| +---------------------------+ +----------------+----------------+ | +| | | +| VPC Internal SQL | | +| (Port 5432, No EIP) v | +| +---------------------------------+ | +| | Volcengine RDS for PostgreSQL | | +| | Version: 16 (loopx_app role) | | +| | Schema: loopx_control_plane | | +| +---------------------------------+ | +| | +| +---------------------------------------------------------------------+ | +| | Volcano Ark (`ark.cn-beijing.volces.com`) Video / LLM Model Service | | +| | - 同地域低延迟交互(由部署者按环境参数配置端点与模型 ID) | | +| | - 通过独立受限环境变量注入凭据(不依赖开发机本地配置文件) | | +| +---------------------------------------------------------------------+ | ++---------------------------------------------------------------------------+ +``` + +### 核心设计原则 +1. **数据库仅走 VPC 私网**:为 PostgreSQL 实例绑定独立的访问白名单,仅允许网关的私网 IPv4 地址访问 5432 端口。部署时核对实例的全部关联白名单,确保没有额外来源可访问。严禁为数据库绑定公网弹性 IP (EIP)。[火山引擎 PostgreSQL 白名单](https://docs.volcengine.com/docs/rds-for-pg/adding-an-ip-address-allowlist?lang=zh) +2. **最小受限角色装配 (`loopx_app`)**:网关服务使用专用的 `loopx_app` 角色连接数据库,仅具备 `SELECT, INSERT, UPDATE` 必要权限,禁止 `DROP TABLE`, `TRUNCATE`, `ALTER ROLE` 等管理员特权。 +3. **端到端 TLS 传输认证**:外部客户端经由 TLS 1.3 连接网关,凭据在网关层做安全哈希对比(`timingSafeEqual`),绝不向数据库传递或持久化明文凭据。 +4. **同地域方舟模型与受限凭据注入**:利用同在 `cn-beijing` 的火山方舟大模型/视频 API 端点(`ark.cn-beijing.volces.com`),由部署者在云端通过环境变量或密钥管理服务为 Worker 单独注入受限模型 API Key 与网关 Bearer 凭据,严禁复用或上传开发机本地私有配置文件。 + +--- + +## 2. 火山引擎 cn-beijing 资源规格清单 + +| 资源类别 | 建议规格 / 配置 | 计费类型建议 | 用途 | +|---|---|---|---| +| **VPC** | CIDR: `172.16.0.0/16`, Region: `cn-beijing` | 免费 | 隔离协同云上内网 | +| **子网 (Subnet)** | 可用区: `cn-beijing-a`, CIDR: `172.16.1.0/24` | 免费 | 数据库与网关部署网段 | +| **安全组 (Gateway)** | 入方向: 仅放通 443 (TLS) 给授权 IP;出方向: 允许内网访问 RDS | 免费 | 网关流量防护 | +| **白名单 (RDS)** | 绑定到 RDS 实例,仅列出网关私网 IPv4 的 `/32` 地址 | 随实例配置 | 限制数据库访问来源 | +| **轻量网关 ECS** | 规格: `ecs.g3i.large` (2C4G) 或 `ecs.c3i.large` (2C4G) | 按量计费 / 抢占式 | 运行 Caddy + RemoteAuthorityService | +| **RDS for PG** | 引擎: PostgreSQL 16,规格: `rds.postgres.1c2g` (1C2G) 或通用型 | 按量计费 (按需开启) | 承载协同权威状态与检查点 | +| **弹性公网 IP** | 带宽: 1-5 Mbps 按流量计费,绑定至网关 ECS | 按量计费 | 提供 HTTPS 客户端安全接入 | + +--- + +## 3. 最小权限开通清单 (Volcengine RAM Policy) + +远程 Worker 与 CI/CD 自动化部署账号仅授予最小只读查询权限。模板文件位于 `examples/coordination/volcengine/least-privilege-iam-policy.json`: + +```json +{ + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "rds_postgresql:DescribeDBInstances", + "rds_postgresql:DescribeDBInstanceDetail", + "rds_postgresql:DescribeDatabases", + "rds_postgresql:DescribeAccounts", + "vpc:DescribeVpcs", + "vpc:DescribeSubnets", + "vpc:DescribeSecurityGroups", + "ecs:DescribeInstances", + "ecs:DescribeInstanceStatus" + ], + "Resource": ["*"] + } + ] +} +``` + +> [!NOTE] +> 任何创建资源(`CreateDBInstance`、`RunInstances`)或修改安全组(`AuthorizeSecurityGroupIngress`)的操作必须由主账号管理员在控制台审批后执行,不向任何日常自动化代理开放。 + +--- + +## 4. 参数化部署模板 + +配套部署模板位于 `examples/coordination/volcengine/` 目录: +1. **Terraform 编排模板**:`main.tf` + - 锁定 `volcengine/volcengine` provider 已发布约束(`>= 0.0.186, < 0.1.0`,支持 `PostgreSQL_16`)。 + - 定义 VPC、子网、安全组、`volcengine_rds_postgresql_instance`(使用 `node_spec`、`primary_zone_id`、`secondary_zone_id` 与 `charge_info` 块)及 `rds_endpoints` / `rds_endpoint` 输出。 + - 通过 `gateway_private_ips` 提供网关实际使用的私网 IPv4 地址。模板为每个地址生成 `/32` 白名单条目并绑定到 PostgreSQL 实例。更换网关地址时同步更新白名单。 + - 所有变量均由部署者显式传入或使用安全默认值(如北京地域 `cn-beijing`、默认仅放通 VPC 内网至 443 端口),并设置 `prevent_destroy = true` 避免误删。 +2. **TLS 网关配置**:`gateway-caddy-tls.Caddyfile` + - Caddy(以独立系统用户 `caddy` 运行)使用 `/etc/ssl/loopx/cert.pem` 与 `/etc/ssl/loopx/key.pem` 完成对外 `:443` TLS 终止,并反向代理至本地 Node 权威服务(`https://127.0.0.1:8443`)。 + - 包含请求大小限制(16KB)、连接超时约束与 HSTS 安全头,并与 Node 内部回环私钥及数据库/策略配置严格隔离。 +3. **网关守护进程服务**:`remote-authority-systemd.service` + - 以 `DynamicUser=yes` 临时非 root 服务身份运行 `examples/coordination/remote-authority-service.ts`,并启用 `ProtectSystem=strict`, `PrivateTmp=true`, `NoNewPrivileges=true` 等 systemd 安全加固。 + - **凭据与数据库隔离**:仅由 systemd(root)通过 `EnvironmentFile=/etc/loopx/authority.env` 独立注入 `LOOPX_AUTHORITY_DATABASE_URL`(使用受限 `loopx_app` 角色),不与私钥混入同一传递面。 + - **最小只读凭据移交 (`LoadCredential=` / `%d/`)**:因 `DynamicUser=yes` 进程不是 `root`,直接传入 `0600 root:root` 原始文件路径会触发 `EACCES` 退出导致网关无法监听。unit 通过 `LoadCredential=` 将 `/etc/loopx/remote-policy.json`、`/etc/ssl/loopx/internal-cert.pem` 与 `/etc/ssl/loopx/internal-key.pem` 以仅当前服务临时用户只读(`0400`)方式挂载至 `%d/remote-policy.json`、`%d/authority-cert.pem`、`%d/authority-key.pem` 传给 `ExecStart`。 + +### 4.1 属主、最小权限与 Caddy 隔离契约 + +部署前必须在网关 ECS 上按以下最小权限收敛目录与密钥(切勿为规避 `EACCES` 将任何私钥放宽为 `0644` 或把 Node 凭据组权限授给 `caddy`): + +| 路径 | 属主 (`chown`) | 权限 (`chmod`) | 注入 / 读取方式 | 访问边界与隔离说明 | +|---|---|---|---|---| +| `/opt/loopx/` | `root:root` | 目录 `0755` / 文件 `0644` | Node `ExecStart` 只读运行 | 含 `examples/coordination/`、`loopx/control_plane/` 与生产依赖 `node_modules`;`ProtectSystem=strict` 下只读 | +| `/etc/systemd/system/remote-authority-systemd.service` | `root:root` | `0644` | systemd unit 安装路径 | 由 `/opt/loopx/examples/coordination/volcengine/remote-authority-systemd.service` 复制安装;须早于 `daemon-reload` 与按名启用 | +| `/etc/caddy/Caddyfile` | `root:root` | `0644` | Caddy 主配置安装路径 | 由 `/opt/loopx/examples/coordination/volcengine/gateway-caddy-tls.Caddyfile` 复制安装;与 `caddy.service` 及 `/etc/ssl/loopx/{cert,key}.pem` 配套 | +| `/etc/loopx/` | `root:root` | `0700` | 仅 systemd PID 1 遍历 | 禁止非 root 用户(含 `caddy` 与临时服务用户)列出或直接访问 | +| `/etc/loopx/authority.env` | `root:root` | `0600` | `EnvironmentFile=/etc/loopx/authority.env` | 仅存 `LOOPX_AUTHORITY_DATABASE_URL`(`loopx_app` 串);不进入 `%d/`,`caddy` 不可读 | +| `/etc/loopx/remote-policy.json` | `root:root` | `0600` | `LoadCredential=remote-policy.json:...` -> `%d/remote-policy.json` (`0400`) | 仅 Node 临时身份只读;`caddy` 不可读;原子更新文件后需 `systemctl restart remote-authority-systemd.service` 刷新 | +| `/etc/ssl/loopx/` | `root:caddy` | `0750` | 仅 `root` 与 `caddy` 组遍历 | 阻断其他本地普通用户进入证书目录 | +| `/etc/ssl/loopx/internal-cert.pem` | `root:root` | `0644` | `LoadCredential=authority-cert.pem:...` -> `%d/authority-cert.pem` (`0400`) | Node `127.0.0.1:8443` 回环公钥证书(非私钥;向部署检查端提供公钥 `--ca` 验证) | +| `/etc/ssl/loopx/internal-key.pem` | `root:root` | `0600` | `LoadCredential=authority-key.pem:...` -> `%d/authority-key.pem` (`0400`) | **仅服务内部回环私钥**;非 root 直接读取原路径必报 `EACCES`;`caddy` 无权读取 | +| `/etc/ssl/loopx/cert.pem` | `root:root` | `0644` | Caddy 只读 | 对外 `:443` TLS 公钥证书(非私钥),与客户端 `--ca` 校验对齐 | +| `/etc/ssl/loopx/key.pem` | `root:caddy` | `0640` | Caddy 直接只读(保持 Caddy 私钥读取范围) | **仅 Caddy 对外私钥**;Node 临时用户无读取权限,两层密钥隔离 | +| `/var/log/caddy/` | `caddy:caddy` | `0750` | Caddy 访问日志写入 | 独立日志目录,不包含数据库或 Bearer 凭据 | + +--- + +## 5. 多机分治与双人协同联调流程 + +### 步骤 1:本地零成本预演 (Colima / Docker) +在向火山引擎上线前,必须先在本机运行 Colima 端到端彩排套件验证: +```bash +# 模拟模式(无任何容器开销,内存数据库 + 本地 HTTPS/TLS 服务端快速预检 8 个核心切片) +./examples/coordination/colima-pg16-e2e-rehearsal.sh --simulate + +# 容器模式(启动隔离 postgres:16-alpine 容器 + 受限角色 + HTTPS/TLS 联调,缺少 Docker 直接失败退出) +./examples/coordination/colima-pg16-e2e-rehearsal.sh --rehearsal +``` + +### 步骤 2:目标库初始化、受限账号装配与创世种子灌入 +进入全新的火山引擎 RDS PostgreSQL 16 实例后,必须严格拆分**管理员(一次性初始化与角色赋权)**与**受限运行账号(`loopx_app`,seed 写入与网关运行)**两类凭据与职责,并复用 Stage 2B CLI(`loopx postgres setup` 与 `local-to-pg-seed --execute`)完成灌入与游标回读: + +1. **管理员一次性初始化与角色装配(仅使用管理员连接)**: + - **管理员职责**:安装 `loopx_control_plane` schema、行级安全(RLS)策略与目标库唯一 `store_identity`;确保受限账号 `loopx_app` 具备登录与 `CONNECT` 权限且无管理员特权(`NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT`)。管理员连接仅用于一次性初始化、升级或轮换,严禁写入网关 `EnvironmentFile` 或用于日常 seed / 网关运行。 + ```bash + # 管理员连接串仅在初始化阶段使用 + export LOOPX_POSTGRES_URL="postgresql://:@:5432/" + + # 2.1a 先执行只读 dry-run 预览(不连接或修改数据库) + loopx --format json postgres setup --runtime-role loopx_app + + # 2.1b 显式执行 schema、RLS、store_identity 安装与 loopx_app 最小表权装配 + loopx --format json postgres setup --runtime-role loopx_app --execute + ``` + 记录输出 JSON 中的 `store_identity`(格式 `postgresql:<32 位小写十六进制>`)。`setup --execute` 会在同一事务中为 `loopx_app` 授予最小表级权限(`USAGE ON SCHEMA loopx_control_plane`、`authority_store_metadata` 只读 `SELECT`、`authority_heads` 的 `SELECT, INSERT, UPDATE`、`authority_checkpoints/commits/events/receipts` 的 `SELECT, INSERT`,禁止 `DELETE`、`TRUNCATE` 与 DDL)。若 RDS 尚未预先创建可登录的 `loopx_app` 角色(`setup` 默认以 `NOLOGIN` 建角),由管理员补齐登录口令与库级连接权限: + ```sql + ALTER ROLE loopx_app LOGIN PASSWORD '' NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT; + GRANT CONNECT ON DATABASE TO loopx_app; + ``` + +2. **受限账号执行创世种子脱敏预览与灌入(使用 `loopx_app`)**: + - **受限账号职责**:`loopx_app` 仅向尚无权威状态的空目标 Goal 写入游标 `1` 的创世种子,不安装 schema、不修改角色权限、也不迁移既有历史日志。完成初始化后立即将 `LOOPX_POSTGRES_URL` 切换为受限账号连接串,并通过 `--store-identity` 绑定目标库身份: + ```bash + export LOOPX_REGISTRY="/path/to/registry.json" + export LOOPX_RUNTIME_ROOT="/path/to/operator-runtime-root" + export LOOPX_GOAL_ID="" + export LOOPX_TENANT_ID="" + export LOOPX_SEED_OUTPUT="/path/to/private/genesis-seed.json" + + # 2.2a 只读脱敏预览(自动剔除本地绝对路径、.local/ 引用、飞书 ID 与已过期租约;不连接目标 PostgreSQL) + loopx --registry "$LOOPX_REGISTRY" --runtime-root "$LOOPX_RUNTIME_ROOT" \ + --format json postgres local-to-pg-seed \ + --goal-id "$LOOPX_GOAL_ID" \ + --tenant-id "$LOOPX_TENANT_ID" \ + --output "$LOOPX_SEED_OUTPUT" + + # 2.2b 切换为受限运行账号并绑定 store_identity 执行灌入(写入游标 1) + export LOOPX_STORE_IDENTITY="" + export LOOPX_POSTGRES_URL="postgresql://loopx_app:@:5432/" + + loopx --registry "$LOOPX_REGISTRY" --runtime-root "$LOOPX_RUNTIME_ROOT" \ + --format json postgres local-to-pg-seed \ + --goal-id "$LOOPX_GOAL_ID" \ + --tenant-id "$LOOPX_TENANT_ID" \ + --store-identity "$LOOPX_STORE_IDENTITY" \ + --output "$LOOPX_SEED_OUTPUT" \ + --execute + ``` + 确认返回 JSON 中 `status` 为 `"seeded"`、`cursor` 为 `"1"`、`provider_revision` 形如 `:1`(若使用完全相同的参数与 `--output` 文件重试,将幂等读回原回执;目标 Goal 若已存在不同权威状态则拒绝覆盖)。 + +3. **目标 Goal 与游标回读校验**: + 执行步骤 3 客户端认领前,先使用受限账号 `LOOPX_POSTGRES_URL` 直接从目标库回读 Goal 与游标,确认 `status === "loaded"`、`cursor === "1"` 且 `provider_revision` 匹配: + ```bash + node --no-warnings --experimental-sqlite --experimental-strip-types \ + --input-type=module -e ' + import {Pool} from "pg"; + import {PostgreSqlAuthorityStore} from "./loopx/control_plane/coordination/postgresql_authority_store.ts"; + const pool = new Pool({connectionString: process.env.LOOPX_POSTGRES_URL}); + try { + const store = new PostgreSqlAuthorityStore({ + connect: async () => { + const client = await pool.connect(); + return { + query: (sql, args) => client.query(sql, args ? [...args] : undefined), + release: (err) => client.release(err), + }; + }, + }, { + tenant_id: process.env.LOOPX_TENANT_ID, + goal_id: process.env.LOOPX_GOAL_ID, + expected_store_identity: process.env.LOOPX_STORE_IDENTITY, + }); + const loaded = await store.loadAuthority(); + if (loaded.status !== "loaded") { + throw new Error(`Expected loaded target goal, got ${loaded.status}`); + } + console.log(JSON.stringify({ + status: loaded.status, + goal_id: loaded.head.goal_id, + cursor: loaded.cursor, + provider_revision: loaded.provider_revision, + todo_count: Array.isArray(loaded.head.todos) ? loaded.head.todos.length : 0, + })); + } finally { + await pool.end(); + } + ' + ``` + 在网关 ECS 上完成前置软件安装(`Node.js >= 22.6` 位于 `/usr/bin/node`、已带 `caddy` 系统账号与 `caddy.service` 的 Caddy 2,以及已部署并装好生产依赖的 `/opt/loopx`)并按 4.1 节收敛属主与最小权限后,先安装 unit 与 Caddy 配置,再按名启用托管服务并验证**以非 root 临时服务身份监听**与 `snapshot` 回读: + ```bash + # 1. 收敛属主与最小读取权限(先创建凭据文件、日志目录与证书,再安装配置并启用服务) + sudo install -d -o root -g root -m 0700 /etc/loopx + sudo install -d -o root -g caddy -m 0750 /etc/ssl/loopx + sudo install -d -o caddy -g caddy -m 0750 /var/log/caddy + sudo chown root:root /etc/loopx/authority.env /etc/loopx/remote-policy.json \ + /etc/ssl/loopx/internal-cert.pem /etc/ssl/loopx/internal-key.pem /etc/ssl/loopx/cert.pem + sudo chmod 0600 /etc/loopx/authority.env /etc/loopx/remote-policy.json /etc/ssl/loopx/internal-key.pem + sudo chmod 0644 /etc/ssl/loopx/internal-cert.pem /etc/ssl/loopx/cert.pem + sudo chown root:caddy /etc/ssl/loopx/key.pem + sudo chmod 0640 /etc/ssl/loopx/key.pem + + # 2. 安装 systemd unit 与 Caddy 配置(必须在 daemon-reload 与按名 enable 之前就位) + sudo install -o root -g root -m 0644 \ + /opt/loopx/examples/coordination/volcengine/remote-authority-systemd.service \ + /etc/systemd/system/remote-authority-systemd.service + sudo install -o root -g root -m 0644 \ + /opt/loopx/examples/coordination/volcengine/gateway-caddy-tls.Caddyfile \ + /etc/caddy/Caddyfile + sudo caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile + + # 3. 加载并按名启用 systemd 服务(LoadCredential 将策略与回环证书/私钥只读移交 %d/) + sudo systemctl daemon-reload + sudo systemctl enable --now remote-authority-systemd.service + sudo systemctl enable --now caddy + sudo systemctl restart caddy + + # 4. 确认服务进程以非 root 临时用户运行且成功监听 127.0.0.1:8443 + systemctl show -p ActiveState,UID,GID,ExecMainPID remote-authority-systemd.service + ps -o uid=,user=,gid=,group=,pid=,args= -p "$(systemctl show -p ExecMainPID --value remote-authority-systemd.service)" + sudo ss -tlnp | grep -E ':443|:8443' + + # 5. 导出公钥 CA 副本并以普通客户端身份完成一次合法 snapshot 回读(先直连回环端口,再经 Caddy 对外入口复验) + sudo install -m 0644 /etc/ssl/loopx/internal-cert.pem /etc/loopx-public-internal-ca.pem + LOOPX_AUTHORITY_CREDENTIAL="" \ + node --no-warnings --experimental-strip-types \ + examples/coordination/remote-authority-client.ts \ + --endpoint "https://127.0.0.1:8443" \ + --ca /etc/loopx-public-internal-ca.pem <<'EOF' + { + "schema_version": "loopx_remote_authority_request_v0", + "tenant_id": "", + "goal_id": "", + "actor_id": "", + "store_identity": "", + "operation": "snapshot" + } + EOF + ``` + 确认输出 JSON 中 `"status": "snapshot"` 且 `goal_id`、`store_identity`、`provider_revision` 与待办列表 `todos` 一致,再经 Caddy 对外地址(`--endpoint "https://" --ca ""`)发送同一 `snapshot` 查询确认源 Goal 为 `hard_lease` 模式与规范 `todo_` 任务,之后进入步骤 3。 + +### 步骤 3:多机客户端并发联调 +每个客户端仅持有所属 `principal` 的受限网关 Bearer 凭据与目标 `store_identity` / `tenant_id` / `goal_id` 参数,不接触数据库管理员凭据或彼此私钥: +- **操作员节点 (`operator.local`)**: + 通过环境变量或密钥代理注入网关凭据,经 TLS CA 校验将命令 JSON 通过标准输入提交给网关: + ```bash + LOOPX_AUTHORITY_CREDENTIAL="" \ + node --no-warnings --experimental-sqlite --experimental-strip-types \ + examples/coordination/remote-authority-client.ts \ + --endpoint "https://" \ + --ca "" < command.json + ``` +- **云端 Worker (`worker.cloud`)**: + 由部署者在云端环境独立注入以下受限凭据与参数(可通过 ECS 实例环境文件、systemd `EnvironmentFile` 或云厂商密钥托管服务挂载,权限收紧为 `0600`,不依赖任何开发机本地文件): + - `LOOPX_AUTHORITY_CREDENTIAL`:仅授权 `worker.cloud` 对应 `principal` 与目标 scope 的网关 Bearer 凭据。 + - 模型调用参数与密钥(如 `ARK_API_KEY`、`ARK_ENDPOINT=https://ark.cn-beijing.volces.com/api/v3` 与目标 `MODEL_ID`):独立签发的最小额度模型凭据,仅用于 Worker 执行分配任务。 + - `LOOPX_GATEWAY_ENDPOINT` 与 `LOOPX_GATEWAY_CA`:部署者配置的网关域名及可信 CA 路径。 + Worker 通过 `examples/coordination/remote-authority-client.ts` 获取租约并执行分配的任务,随后向网关回传 `progress` 与带验证证据的 `complete` 指令;若遇到网络超时或未知响应,须保留原请求 JSON 与 `request_id`,改用 `--recover` 只读查询回执,严禁自动重试或替换 `request_id`。 +- **租约冲突与超期接管**: + 若云端 Worker 节点因网络断连或故障未续租,租约到达 TTL 后,其他已授权节点可按服务端时钟合法接管继续推进,并在完成后由任一授权节点经 `snapshot` / `read` 回读一致终态。 diff --git a/examples/coordination/colima-pg16-e2e-rehearsal.sh b/examples/coordination/colima-pg16-e2e-rehearsal.sh new file mode 100755 index 0000000000..2781dcf0a1 --- /dev/null +++ b/examples/coordination/colima-pg16-e2e-rehearsal.sh @@ -0,0 +1,201 @@ +#!/usr/bin/env bash +# ============================================================================== +# Colima / Docker PostgreSQL 16 Dual-Actor Coordination Rehearsal Suite +# +# Provides zero-cost local rehearsal for: +# - Schema initialization & least-privilege role assembly +# - Genesis seed ingestion (loopx-quality-review canary) +# - Dual-actor (operator.local / worker.cloud) lease competition & expiration takeover over HTTPS/TLS +# - Default-deny boundary rejection +# - Verified task completion & cross-machine snapshot readback +# +# Usage: +# ./colima-pg16-e2e-rehearsal.sh --simulate # Fast in-memory PG + real TLS simulation (preflight) +# ./colima-pg16-e2e-rehearsal.sh --database-url # Rehearse against existing PostgreSQL instance +# ./colima-pg16-e2e-rehearsal.sh --rehearsal # Fail-closed rehearsal against disposable postgres:16-alpine +# ./colima-pg16-e2e-rehearsal.sh --start-colima # Ensure Colima is started, then run containerized rehearsal +# ============================================================================== + +set -euo pipefail + +SCRIPT_SOURCE="${BASH_SOURCE[0]}" +while [ -L "${SCRIPT_SOURCE}" ]; do + LINK_DIR="$(cd -P "$(dirname "${SCRIPT_SOURCE}")" && pwd)" + LINK_TARGET="$(readlink "${SCRIPT_SOURCE}")" + case "${LINK_TARGET}" in + /*) SCRIPT_SOURCE="${LINK_TARGET}" ;; + *) SCRIPT_SOURCE="${LINK_DIR}/${LINK_TARGET}" ;; + esac +done +SCRIPT_DIR="$(cd -P "$(dirname "${SCRIPT_SOURCE}")" && pwd)" +REPO_ROOT="$(cd -P "${SCRIPT_DIR}/../.." && pwd)" + +MODE="simulate" +EXPLICIT_MODE="" +EXPLICIT_FLAG="" +DATABASE_URL="${LOOPX_AUTHORITY_DATABASE_URL:-}" +START_COLIMA=false +CONTAINER_NAME="loopx-canary-pg16-rehearsal-$$-$(date +%s)" +PG_PORT="" +PORT_EXPLICIT=false +CONTAINER_STARTED=false + +set_explicit_mode() { + local target_mode="$1" + local flag="$2" + if [ -n "${EXPLICIT_MODE}" ] && { [ "${EXPLICIT_MODE}" != "${target_mode}" ] || [ "${flag}" = "--database-url" ]; }; then + echo "Error: conflicting mode flags (${EXPLICIT_FLAG} and ${flag}) are mutually exclusive." >&2 + exit 1 + fi + EXPLICIT_MODE="${target_mode}" + EXPLICIT_FLAG="${flag}" + MODE="${target_mode}" +} + +cleanup() { + if [ "${CONTAINER_STARTED}" = true ]; then + echo "[colima-rehearsal] Cleaning up disposable PostgreSQL container ${CONTAINER_NAME}..." >&2 + docker rm -f -v "${CONTAINER_NAME}" >/dev/null 2>&1 || true + fi +} +trap cleanup EXIT INT TERM + +show_help() { + cat < Run against an explicit PostgreSQL database URL. + --start-colima Start colima VM first if not running, then execute --rehearsal. + --port Local host port for disposable container (default: random ephemeral 127.0.0.1 port). + --help Show this help message. + +Environment Variables: + LOOPX_AUTHORITY_DATABASE_URL Default database connection URL if set. +EOF +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --simulate) + set_explicit_mode "simulate" "--simulate" + shift + ;; + --rehearsal) + set_explicit_mode "container" "--rehearsal" + shift + ;; + --start-colima) + START_COLIMA=true + set_explicit_mode "container" "--start-colima" + shift + ;; + --database-url) + if [ $# -lt 2 ] || [ -z "${2// }" ]; then + echo "Error: --database-url requires a non-empty PostgreSQL URL." >&2 + exit 1 + fi + set_explicit_mode "real_url" "--database-url" + DATABASE_URL="$2" + shift 2 + ;; + --port) + if [ $# -lt 2 ] || [ -z "${2// }" ]; then + echo "Error: --port requires a non-empty port number." >&2 + exit 1 + fi + PG_PORT="$2" + PORT_EXPLICIT=true + shift 2 + ;; + -h|--help) + show_help + exit 0 + ;; + *) + echo "Unknown argument: $1" >&2 + show_help + exit 1 + ;; + esac +done + +if [ "${START_COLIMA}" = true ]; then + if ! command -v colima >/dev/null 2>&1; then + echo "Error: colima CLI not found on PATH." >&2 + exit 1 + fi + if ! colima status >/dev/null 2>&1; then + echo "[colima-rehearsal] Starting Colima VM (2 CPU, 2GB memory)..." >&2 + colima start --cpu 2 --memory 2 + else + echo "[colima-rehearsal] Colima is already running." >&2 + fi +fi + +if [ "${MODE}" = "container" ]; then + if ! command -v docker >/dev/null 2>&1; then + echo "Error: docker CLI not found on PATH; --rehearsal requires Docker/Colima (use --simulate for preflight)." >&2 + exit 1 + fi + if ! docker info >/dev/null 2>&1; then + echo "Error: Docker daemon is unreachable; --rehearsal cannot fall back to simulation (use --simulate for preflight)." >&2 + exit 1 + fi + + PUBLISH_SPEC="127.0.0.1::5432" + if [ "${PORT_EXPLICIT}" = true ]; then + PUBLISH_SPEC="127.0.0.1:${PG_PORT}:5432" + fi + + echo "[colima-rehearsal] Starting ephemeral PostgreSQL 16 container: ${CONTAINER_NAME} (${PUBLISH_SPEC})..." >&2 + docker run -d \ + --name "${CONTAINER_NAME}" \ + -e POSTGRES_PASSWORD=loopx_canary_secret \ + -e POSTGRES_DB=loopx_canary \ + -p "${PUBLISH_SPEC}" \ + postgres:16-alpine >/dev/null + CONTAINER_STARTED=true + + PG_PORT="$(docker port "${CONTAINER_NAME}" 5432/tcp | head -n 1 | awk -F: '{print $NF}')" + if [ -z "${PG_PORT}" ]; then + echo "Error: Failed to resolve published host port for ${CONTAINER_NAME}." >&2 + exit 1 + fi + + # Await TCP PostgreSQL readiness (not just Unix-socket initdb startup) + echo "[colima-rehearsal] Waiting for PostgreSQL readiness on 127.0.0.1:${PG_PORT}..." >&2 + PG_READY=false + for _ in {1..40}; do + if docker exec -e PGPASSWORD=loopx_canary_secret "${CONTAINER_NAME}" \ + psql -h 127.0.0.1 -p 5432 -U postgres -d loopx_canary -c "SELECT 1" >/dev/null 2>&1; then + echo "[colima-rehearsal] PostgreSQL 16 is ready." >&2 + PG_READY=true + break + fi + sleep 0.5 + done + if [ "${PG_READY}" != true ]; then + echo "Error: PostgreSQL 16 container ${CONTAINER_NAME} failed to become ready within timeout." >&2 + exit 1 + fi + + DATABASE_URL="postgresql://postgres:loopx_canary_secret@127.0.0.1:${PG_PORT}/loopx_canary" + MODE="real_url" +fi + +cd "${REPO_ROOT}" + +if [ "${MODE}" = "real_url" ]; then + echo "[colima-rehearsal] Running dual-actor coordination rehearsal against isolated real PostgreSQL + TLS..." >&2 + node --no-warnings --experimental-sqlite --experimental-strip-types \ + "${SCRIPT_DIR}/colima-pg16-e2e-rehearsal.ts" \ + --database-url "${DATABASE_URL}" +else + echo "[colima-rehearsal] Running dual-actor coordination rehearsal in in-memory simulation + TLS mode..." >&2 + node --no-warnings --experimental-sqlite --experimental-strip-types \ + "${SCRIPT_DIR}/colima-pg16-e2e-rehearsal.ts" \ + --simulate +fi diff --git a/examples/coordination/colima-pg16-e2e-rehearsal.ts b/examples/coordination/colima-pg16-e2e-rehearsal.ts new file mode 100644 index 0000000000..93834eebd3 --- /dev/null +++ b/examples/coordination/colima-pg16-e2e-rehearsal.ts @@ -0,0 +1,1065 @@ +/** + * Colima / Docker PostgreSQL 16 Dual-Actor Coordination Rehearsal Suite + * + * Validates: + * 1. Schema DDL initialization and least-privilege restricted role assembly. + * 2. Genesis seed sanitization and ingestion via exportLocalToPgGenesisSeed. + * 3. Dual-actor lease competition between operator.local and worker.cloud over HTTPS/TLS. + * 4. Active lease conflict prevention (actor B rejected while actor A holds valid lease). + * 5. Default-deny security boundary (unauthorized goal and invalid bearer credential rejected). + * 6. Controlled-clock expired lease takeover + lease_epoch increment + stale-actor fencing. + * 7. Verified task progress, completion, and historical recover readback over HTTPS/TLS. + * 8. Cross-machine snapshot and direct restricted-role PostgreSQL authority readback. + */ + +import {execFile} from "node:child_process"; +import {createHash, randomBytes} from "node:crypto"; +import {realpathSync} from "node:fs"; +import {mkdtemp, readFile, rm, writeFile} from "node:fs/promises"; +import {tmpdir} from "node:os"; +import {join, resolve} from "node:path"; +import {fileURLToPath} from "node:url"; +import {parseArgs, promisify} from "node:util"; +import {Pool, type PoolClient, type PoolConfig} from "pg"; +import type {JsonObject} from "../../loopx/control_plane/effect_program.ts"; +import { + coordinationTodoReadModel, +} from "../../loopx/control_plane/coordination/coordination_projection.ts"; +import { + canonicalTodoDomainRecord, + TODO_DOMAIN_ITEM_SCHEMA, + TODO_DOMAIN_READ_RECORD_SCHEMA, +} from "../../loopx/control_plane/coordination/coordination_state_contract.ts"; +import { + openLocalAuthorityStore, +} from "../../loopx/control_plane/coordination/local_authority_provider.ts"; +import { + exportLocalToPgGenesisSeed, + setupPostgreSqlAuthoritySchemaAndRole, +} from "../../loopx/control_plane/coordination/postgresql_authority_seed.ts"; +import { + POSTGRESQL_SCHEMA_VERSION, + PostgreSqlAuthorityStore, + type PostgreSqlAuthorityConnection, + type PostgreSqlAuthorityDatabase, +} from "../../loopx/control_plane/coordination/postgresql_authority_store.ts"; +import { + decodeRemoteAuthorityRequest, + type RemoteAuthorityRequest, +} from "../../loopx/control_plane/coordination/remote_authority_contract.ts"; +import { + callRemoteAuthority, + createRemoteAuthorityServer, +} from "../../loopx/control_plane/coordination/remote_authority_http.ts"; +import { + fileRemoteAuthorityAdmission, + REMOTE_AUTHORITY_POLICY, +} from "../../loopx/control_plane/coordination/remote_authority_policy.ts"; +import { + RemoteAuthorityService, +} from "../../loopx/control_plane/coordination/remote_authority_service.ts"; +import { + materializeTodoRecordForSchema, +} from "../../loopx/control_plane/coordination/todo_presentation.ts"; + +export interface RehearsalStepResult { + step: string; + ok: boolean; + duration_ms: number; + detail: Record; +} + +export interface RehearsalReport { + schema_version: "colima_pg16_coordination_rehearsal_report_v0"; + ok: boolean; + mode: "real_pg" | "simulation"; + execution_boundary: + | "isolated_real_pg16_tls" + | "isolated_real_postgresql_tls" + | "in_memory_simulated_pg_tls"; + transport: "https_tls"; + clock_mode: "controlled_service_clock"; + runtime_role_verified: boolean; + server_version: string | null; + server_version_num: number | null; + server_major_version: number | null; + pg16_qualified: boolean; + tenant_id: string; + goal_id: string; + store_identity: string; + total_duration_ms: number; + actors: { + actor_a: string; + actor_b: string; + }; + steps: RehearsalStepResult[]; + error?: string; +} + +export interface PostgreSqlServerVersionInfo { + server_version: string | null; + server_version_num: number | null; + server_major_version: number | null; +} + +/** + * Parses PostgreSQL `SHOW server_version` and `SHOW server_version_num` values + * into normalized version fields before any database mutation runs. + */ +export function parsePostgreSqlServerVersion( + serverVersionRaw: unknown, + serverVersionNumRaw?: unknown, +): PostgreSqlServerVersionInfo { + const serverVersion = + typeof serverVersionRaw === "string" && serverVersionRaw.trim().length > 0 + ? serverVersionRaw.trim() + : null; + + if (serverVersionNumRaw !== undefined && serverVersionNumRaw !== null) { + const rawNum = String(serverVersionNumRaw).trim(); + if (/^\d+$/.test(rawNum)) { + const parsedNum = Number(rawNum); + if (Number.isSafeInteger(parsedNum) && parsedNum > 0) { + return { + server_version: serverVersion, + server_version_num: parsedNum, + server_major_version: Math.floor(parsedNum / 10_000), + }; + } + } + } + + if (serverVersion !== null) { + const match = serverVersion.match(/^(\d+)(?:\.(\d+))?/); + if (match) { + const major = Number(match[1]); + const minor = match[2] ? Number(match[2]) : 0; + if (Number.isSafeInteger(major) && major > 0 && Number.isSafeInteger(minor) && minor >= 0) { + return { + server_version: serverVersion, + server_version_num: major * 10_000 + minor, + server_major_version: major, + }; + } + } + } + + return { + server_version: serverVersion, + server_version_num: null, + server_major_version: null, + }; +} + +export interface RehearsalOptions { + databaseUrl?: string; + simulate?: boolean; + verbose?: boolean; + leaseTtlSeconds?: number; +} + +function asJsonObject(value: unknown): JsonObject | undefined { + return value !== null && typeof value === "object" && !Array.isArray(value) + ? (value as JsonObject) + : undefined; +} + +function databaseFromPool(pool: Pool): PostgreSqlAuthorityDatabase { + return { + connect: async () => { + const client: PoolClient = await pool.connect(); + const connection: PostgreSqlAuthorityConnection = { + query: async (text, values) => + await client.query(text, values ? [...values] : undefined), + release: (error) => client.release(error), + }; + return connection; + }, + }; +} + +export class ColimaPgCoordinationRehearsal { + private readonly tenantId = "tenant-canary"; + private readonly goalId = "loopx-quality-review"; + private readonly actorA = "operator.local"; + private readonly actorB = "worker.cloud"; + private readonly tokenA = `rehearsal-local-${"a".repeat(32)}`; + private readonly tokenB = `rehearsal-cloud-${"b".repeat(32)}`; + private readonly invalidToken = `invalid-rehearsal-${"x".repeat(32)}`; + private readonly todoId = "todo_canary_001"; + private readonly options: RehearsalOptions; + private serviceClock: Date; + + constructor(options: RehearsalOptions = {}) { + this.options = options; + this.serviceClock = new Date(); + } + + async run(): Promise { + const startTime = Date.now(); + const steps: RehearsalStepResult[] = []; + const storeIdentity = `postgresql:${randomBytes(16).toString("hex").toLowerCase()}`; + const explicitEmptyUrl = + this.options.databaseUrl !== undefined && this.options.databaseUrl.trim().length === 0; + const isRealPg = Boolean(this.options.databaseUrl?.trim() && !this.options.simulate); + const mode: RehearsalReport["mode"] = isRealPg || explicitEmptyUrl ? "real_pg" : "simulation"; + let executionBoundary: RehearsalReport["execution_boundary"] = mode === "real_pg" + ? "isolated_real_postgresql_tls" + : "in_memory_simulated_pg_tls"; + let serverVersion: string | null = null; + let serverVersionNum: number | null = null; + let serverMajorVersion: number | null = null; + + const disconnects = new Map>>(); + const trackedPool = (config: PoolConfig): Pool => { + const created = new Pool(config); + const pending = new Set>(); + disconnects.set(created, pending); + created.on("connect", client => { + const closed = new Promise(resolve => client.once("end", resolve)); + pending.add(closed); + void closed.then(() => pending.delete(closed)); + }); + return created; + }; + const closePool = async (target?: Pool | null): Promise => { + if (!target) return; + await target.end(); + await Promise.all(disconnects.get(target) ?? []); + }; + + const tempRoots: string[] = []; + let adminPool: Pool | null = null; + let setupPool: Pool | null = null; + let runtimePool: Pool | null = null; + let databaseCreated = false; + let roleCreated = false; + let dbName = ""; + let roleName = ""; + let runtimeRoleVerified = false; + let listener: ReturnType | null = null; + + try { + if (explicitEmptyUrl && !this.options.simulate) { + throw new Error("databaseUrl must be a non-empty PostgreSQL connection URL"); + } + + const suffix = randomBytes(8).toString("hex"); + dbName = `rehearsal_${suffix}`; + roleName = `loopx_app_${suffix}`; + const rolePassword = randomBytes(24).toString("hex"); + + let setupDatabase: PostgreSqlAuthorityDatabase; + let runtimeDatabase: PostgreSqlAuthorityDatabase; + + if (isRealPg) { + const baseUrl = this.options.databaseUrl!; + adminPool = trackedPool({ + connectionString: baseUrl, + max: 2, + connectionTimeoutMillis: 5000, + statement_timeout: 10000, + }); + // Inspect server version before any CREATE DATABASE / role / schema mutation. + const versionRes = await adminPool.query("SHOW server_version"); + const versionNumRes = await adminPool.query("SHOW server_version_num"); + const parsedVersion = parsePostgreSqlServerVersion( + asJsonObject(versionRes.rows[0])?.server_version, + asJsonObject(versionNumRes.rows[0])?.server_version_num, + ); + serverVersion = parsedVersion.server_version; + serverVersionNum = parsedVersion.server_version_num; + serverMajorVersion = parsedVersion.server_major_version; + if (serverMajorVersion !== 16) { + throw new Error( + `PostgreSQL 16 is required for PG16 qualification rehearsal; connected server reports ${ + serverVersion ?? "unknown" + } (server_version_num=${serverVersionNum ?? "unknown"}). Refusing before database setup.`, + ); + } + executionBoundary = "isolated_real_pg16_tls"; + + await adminPool.query(`CREATE DATABASE ${dbName}`); + databaseCreated = true; + + const dbUrl = new URL(baseUrl); + dbUrl.pathname = `/${dbName}`; + setupPool = trackedPool({ + connectionString: dbUrl.href, + max: 8, + connectionTimeoutMillis: 5000, + statement_timeout: 10000, + }); + await setupPool.query( + `CREATE ROLE ${roleName} LOGIN PASSWORD '${rolePassword}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT`, + ); + roleCreated = true; + await setupPool.query(`GRANT CONNECT ON DATABASE ${dbName} TO ${roleName}`); + setupDatabase = databaseFromPool(setupPool); + + const runtimeUrl = new URL(dbUrl); + runtimeUrl.username = roleName; + runtimeUrl.password = rolePassword; + runtimePool = trackedPool({ + connectionString: runtimeUrl.href, + max: 8, + connectionTimeoutMillis: 5000, + statement_timeout: 10000, + }); + runtimeDatabase = databaseFromPool(runtimePool); + } else { + setupDatabase = this.createSimulatedDatabase(storeIdentity); + runtimeDatabase = setupDatabase; + } + + // Step 1: Schema initialization and restricted role assembly (admin/setup connection only) + const s1Start = Date.now(); + const setupResult = await setupPostgreSqlAuthoritySchemaAndRole({ + database: setupDatabase, + storeIdentity, + runtimeRole: roleName, + }); + const s1Ok = setupResult.status === "installed" && setupResult.runtime_role === roleName; + steps.push({ + step: "schema_initialization_and_role_assembly", + ok: s1Ok, + duration_ms: Date.now() - s1Start, + detail: { + status: setupResult.status, + store_identity: setupResult.store_identity, + runtime_role: setupResult.runtime_role, + mode, + }, + }); + if (!s1Ok) { + throw new Error(`Schema setup failed: ${setupResult.reason ?? "unknown"}`); + } + + // Step 2: Genesis seed sanitization & ingestion via real exportLocalToPgGenesisSeed + const s2Start = Date.now(); + const seedRuntimeRoot = await mkdtemp(join(tmpdir(), "loopx-pg-rehearsal-seed-")); + tempRoots.push(seedRuntimeRoot); + const localStore = await openLocalAuthorityStore(seedRuntimeRoot, this.goalId); + const todoDomain = canonicalTodoDomainRecord({ + schema_version: TODO_DOMAIN_ITEM_SCHEMA, + todo_id: this.todoId, + role: "agent", + status: "open", + done: false, + archive_state: "active", + text: "[Canary] Verify cross-machine PG lease coordination", + priority: "P1", + task_class: "advancement_task", + required_write_scopes: [`${this.todoId}/**`], + }, "canary rehearsal todo domain record"); + const canaryTodo = materializeTodoRecordForSchema( + todoDomain, + TODO_DOMAIN_READ_RECORD_SCHEMA, + "canary rehearsal todo", + ); + const localInit = await localStore.commitAuthority({ + operation_id: `local-seed-prep-${randomBytes(6).toString("hex")}`, + expected_provider_revision: null, + next_projection: { + goal_id: this.goalId, + handoff_mode: "hard_lease", + todos: [canaryTodo], + leases: [], + todo_read_model: coordinationTodoReadModel([canaryTodo], TODO_DOMAIN_READ_RECORD_SCHEMA), + }, + events: [], + receipts: [], + }); + if (localInit.status !== "applied") { + throw new Error(`Local synthetic seed store initialization failed: ${JSON.stringify(localInit)}`); + } + const seedResult = await exportLocalToPgGenesisSeed({ + runtimeRoot: seedRuntimeRoot, + goalId: this.goalId, + tenantId: this.tenantId, + targetDatabase: setupDatabase, + storeIdentity, + execute: true, + }); + const s2Ok = seedResult.status === "seeded" && seedResult.cursor === "1"; + steps.push({ + step: "genesis_seed_ingestion", + ok: s2Ok, + duration_ms: Date.now() - s2Start, + detail: { + status: seedResult.status, + provider_revision: seedResult.provider_revision, + cursor: seedResult.cursor, + seed_digest: seedResult.seed_digest, + todos_sanitized: seedResult.sanitization_report?.todos_sanitized ?? 0, + }, + }); + if (!s2Ok) { + throw new Error(`Genesis seed ingestion failed: ${JSON.stringify(seedResult)}`); + } + + // Close setup/admin provisioning pool before starting runtime service. + if (setupPool) { + await closePool(setupPool); + setupPool = null; + } + + if (isRealPg && runtimePool) { + const roleCheck = await runtimePool.query( + `SELECT current_user AS current_user, r.rolsuper, r.rolbypassrls + FROM pg_roles AS r + WHERE r.rolname = current_user`, + ); + const row = asJsonObject(roleCheck.rows[0]); + if (!row || row.current_user !== roleName || row.rolsuper !== false || row.rolbypassrls !== false) { + throw new Error(`Runtime connection is not using least-privilege role ${roleName}: ${JSON.stringify(row)}`); + } + let appendOnlyDenied = false; + try { + await runtimePool.query("DELETE FROM loopx_control_plane.authority_commits"); + } catch (err) { + const pgErr = err as {code?: string}; + if (pgErr.code === "42501") { + appendOnlyDenied = true; + } + } + if (!appendOnlyDenied) { + throw new Error("Restricted runtime role unexpectedly allowed DELETE on authority_commits"); + } + runtimeRoleVerified = true; + } + + // Prepare self-signed localhost TLS certificate & policy file for HTTPS client/server transport + const tlsRoot = await mkdtemp(join(tmpdir(), "loopx-pg-rehearsal-tls-")); + tempRoots.push(tlsRoot); + const keyPath = join(tlsRoot, "key.pem"); + const certPath = join(tlsRoot, "cert.pem"); + await promisify(execFile)("openssl", [ + "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "1", + "-subj", "/CN=localhost", + "-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1", + "-keyout", keyPath, + "-out", certPath, + ]); + const cert = await readFile(certPath); + const key = await readFile(keyPath); + + const policyPath = join(tlsRoot, "policy.json"); + await writeFile(policyPath, JSON.stringify({ + schema_version: REMOTE_AUTHORITY_POLICY, + scopes: [ + { + tenant_id: this.tenantId, + goal_id: this.goalId, + store_identity: storeIdentity, + registered_agents: [this.actorA, this.actorB], + }, + ], + principals: [ + { + principal_id: `principal-${this.actorA}`, + credential_sha256: createHash("sha256").update(this.tokenA).digest("hex"), + grants: [ + { + tenant_id: this.tenantId, + goal_id: this.goalId, + actor_id: this.actorA, + operations: [ + "read", "claim", "progress", "renew", "release", + "complete", "block", "defer", "todo_add", "snapshot", + ], + }, + ], + }, + { + principal_id: `principal-${this.actorB}`, + credential_sha256: createHash("sha256").update(this.tokenB).digest("hex"), + grants: [ + { + tenant_id: this.tenantId, + goal_id: this.goalId, + actor_id: this.actorB, + operations: [ + "read", "claim", "progress", "renew", "release", + "complete", "block", "defer", "todo_add", "snapshot", + ], + }, + ], + }, + ], + }), {mode: 0o600}); + + const service = new RemoteAuthorityService({ + database: runtimeDatabase, + admit: fileRemoteAuthorityAdmission(policyPath), + now: () => this.serviceClock, + }); + listener = createRemoteAuthorityServer(service, {cert, key}); + const port = await listener.listen("127.0.0.1", 0); + const endpoint = `https://127.0.0.1:${port}`; + const callTls = (credential: string, request: RemoteAuthorityRequest, callMode: "execute" | "recover" = "execute") => + callRemoteAuthority(endpoint, credential, request, {ca: cert, mode: callMode}); + + // Step 3: Actor A claims lease over HTTPS/TLS + const s3Start = Date.now(); + const claimAId = `claim-a-${randomBytes(6).toString("hex")}`; + const claimAReq = decodeRemoteAuthorityRequest({ + schema_version: "loopx_remote_authority_request_v0", + tenant_id: this.tenantId, + goal_id: this.goalId, + actor_id: this.actorA, + store_identity: storeIdentity, + operation: "claim", + request_id: claimAId, + todo_id: this.todoId, + }); + const claimARes = await callTls(this.tokenA, claimAReq); + const claimAResult = asJsonObject(claimARes.result); + const claimALease = asJsonObject(claimAResult?.lease); + const expiresAt = typeof claimALease?.expires_at === "string" ? claimALease.expires_at : ""; + const epochA = typeof claimALease?.lease_epoch === "number" ? claimALease.lease_epoch : Number.NaN; + const s3Ok = claimARes.status === "result" && + claimAResult?.status === "applied" && + claimAResult?.claimed_by === this.actorA && + Boolean(expiresAt) && + Number.isFinite(epochA); + steps.push({ + step: "actor_a_lease_claim", + ok: s3Ok, + duration_ms: Date.now() - s3Start, + detail: { + status: claimARes.status, + result_status: claimAResult?.status, + claimed_by: claimAResult?.claimed_by, + lease_epoch: epochA, + expires_at: expiresAt, + transport: "https_tls", + }, + }); + if (!s3Ok) { + throw new Error(`Actor A claim failed: ${JSON.stringify(claimARes)}`); + } + + // Step 4: Actor B attempts to claim while lease is active (must reject conflict) + const s4Start = Date.now(); + const claimBConflictReq = decodeRemoteAuthorityRequest({ + schema_version: "loopx_remote_authority_request_v0", + tenant_id: this.tenantId, + goal_id: this.goalId, + actor_id: this.actorB, + store_identity: storeIdentity, + operation: "claim", + request_id: `claim-b-conflict-${randomBytes(6).toString("hex")}`, + todo_id: this.todoId, + }); + const claimBConflictRes = await callTls(this.tokenB, claimBConflictReq); + const claimBResult = asJsonObject(claimBConflictRes.result); + const s4Ok = claimBConflictRes.status === "result" && + (claimBResult?.status === "rejected" || claimBResult?.status === "failed"); + steps.push({ + step: "active_lease_conflict_rejection", + ok: s4Ok, + duration_ms: Date.now() - s4Start, + detail: { + status: claimBConflictRes.status, + result_status: claimBResult?.status, + reason_code: claimBResult?.reason_code, + }, + }); + + // Step 5: Default-deny security boundary enforcement over HTTPS/TLS + const s5Start = Date.now(); + const unauthGoalReq = decodeRemoteAuthorityRequest({ + schema_version: "loopx_remote_authority_request_v0", + tenant_id: this.tenantId, + goal_id: "ungranted-canary-goal", + actor_id: this.actorB, + store_identity: storeIdentity, + operation: "read", + todo_id: this.todoId, + }); + const unauthGoalRes = await callTls(this.tokenB, unauthGoalReq); + const unauthCredRes = await callTls(this.invalidToken, claimAReq); + + const s5Ok = unauthGoalRes.status === "rejected" && + unauthCredRes.status === "rejected" && + unauthCredRes.reason_code === "principal_unauthenticated"; + steps.push({ + step: "default_deny_boundary_enforcement", + ok: s5Ok, + duration_ms: Date.now() - s5Start, + detail: { + unauthorized_goal_status: unauthGoalRes.status, + unauthorized_goal_reason: unauthGoalRes.reason_code, + unauthorized_cred_status: unauthCredRes.status, + unauthorized_cred_reason: unauthCredRes.reason_code, + }, + }); + + // Step 6: Advance controlled service clock past observed expires_at -> Actor B takeover + stale Actor A fencing + const s6Start = Date.now(); + const expiresAtMs = Date.parse(expiresAt); + if (!Number.isFinite(expiresAtMs)) { + throw new Error(`Invalid observed expires_at timestamp: ${expiresAt}`); + } + this.serviceClock = new Date(expiresAtMs + 1_000); + const advancedClockIso = this.serviceClock.toISOString(); + + const takeoverId = `claim-b-takeover-${randomBytes(6).toString("hex")}`; + const takeoverReq = decodeRemoteAuthorityRequest({ + schema_version: "loopx_remote_authority_request_v0", + tenant_id: this.tenantId, + goal_id: this.goalId, + actor_id: this.actorB, + store_identity: storeIdentity, + operation: "claim", + request_id: takeoverId, + todo_id: this.todoId, + }); + const takeoverRes = await callTls(this.tokenB, takeoverReq); + const takeoverResult = asJsonObject(takeoverRes.result); + const takeoverLease = asJsonObject(takeoverResult?.lease); + const newEpoch = typeof takeoverLease?.lease_epoch === "number" + ? takeoverLease.lease_epoch + : Number.NaN; + + const staleProgressReq = decodeRemoteAuthorityRequest({ + schema_version: "loopx_remote_authority_request_v0", + tenant_id: this.tenantId, + goal_id: this.goalId, + actor_id: this.actorA, + store_identity: storeIdentity, + operation: "progress", + request_id: `stale-prog-a-${randomBytes(6).toString("hex")}`, + claim_request_id: claimAId, + todo_id: this.todoId, + note: "Stale actor A progress must be rejected after takeover", + }); + const staleProgressRes = await callTls(this.tokenA, staleProgressReq); + const staleProgressResult = asJsonObject(staleProgressRes.result); + const staleActorFenced = staleProgressRes.status === "result" && + (staleProgressResult?.status === "failed" || staleProgressResult?.status === "rejected"); + + const s6Ok = takeoverRes.status === "result" && + takeoverResult?.status === "applied" && + takeoverResult?.claimed_by === this.actorB && + newEpoch === epochA + 1 && + staleActorFenced; + steps.push({ + step: "lease_expiration_takeover", + ok: s6Ok, + duration_ms: Date.now() - s6Start, + detail: { + status: takeoverRes.status, + result_status: takeoverResult?.status, + claimed_by: takeoverResult?.claimed_by, + observed_expires_at: expiresAt, + advanced_service_clock: advancedClockIso, + previous_lease_epoch: epochA, + new_lease_epoch: newEpoch, + stale_actor_fenced: staleActorFenced, + stale_actor_result_status: staleProgressResult?.status, + stale_actor_reason_code: staleProgressResult?.reason_code, + }, + }); + + // Step 7: Actor B reports progress, completes task, and verifies recover receipt over HTTPS/TLS + const s7Start = Date.now(); + const progressReq = decodeRemoteAuthorityRequest({ + schema_version: "loopx_remote_authority_request_v0", + tenant_id: this.tenantId, + goal_id: this.goalId, + actor_id: this.actorB, + store_identity: storeIdentity, + operation: "progress", + request_id: `prog-b-${randomBytes(6).toString("hex")}`, + claim_request_id: takeoverId, + todo_id: this.todoId, + note: "Colima PG16 dual-actor TLS rehearsal in progress", + }); + const progressRes = await callTls(this.tokenB, progressReq); + const progressResult = asJsonObject(progressRes.result); + + const completeReq = decodeRemoteAuthorityRequest({ + schema_version: "loopx_remote_authority_request_v0", + tenant_id: this.tenantId, + goal_id: this.goalId, + actor_id: this.actorB, + store_identity: storeIdentity, + operation: "complete", + request_id: `comp-b-${randomBytes(6).toString("hex")}`, + claim_request_id: takeoverId, + todo_id: this.todoId, + evidence: "canary-rehearsal:pg16-tls-dual-actor-pass", + note: "Verified dual-actor TLS lease coordination and task completion", + no_followup: true, + }); + const completeRes = await callTls(this.tokenB, completeReq); + const compResult = asJsonObject(completeRes.result); + const recoverRes = await callTls(this.tokenB, completeReq, "recover"); + + const s7Ok = progressRes.status === "result" && + progressResult?.status === "applied" && + completeRes.status === "result" && + compResult?.status === "applied" && + compResult?.completed === true && + recoverRes.status === "found" && + recoverRes.historical_only === true; + steps.push({ + step: "actor_b_task_completion", + ok: s7Ok, + duration_ms: Date.now() - s7Start, + detail: { + progress_status: progressRes.status, + progress_result_status: progressResult?.status, + complete_status: completeRes.status, + result_status: compResult?.status, + completed: compResult?.completed, + recover_status: recoverRes.status, + historical_only: recoverRes.historical_only, + }, + }); + + // Step 8: Cross-machine snapshot, read, and direct restricted-role PostgreSQL authority readback + const s8Start = Date.now(); + const snapshotReq = decodeRemoteAuthorityRequest({ + schema_version: "loopx_remote_authority_request_v0", + tenant_id: this.tenantId, + goal_id: this.goalId, + actor_id: this.actorA, + store_identity: storeIdentity, + operation: "snapshot", + }); + const snapshotRes = await callTls(this.tokenA, snapshotReq); + const readReq = decodeRemoteAuthorityRequest({ + schema_version: "loopx_remote_authority_request_v0", + tenant_id: this.tenantId, + goal_id: this.goalId, + actor_id: this.actorA, + store_identity: storeIdentity, + operation: "read", + todo_id: this.todoId, + }); + const readRes = await callTls(this.tokenA, readReq); + const readTodo = asJsonObject(readRes.todo); + const directHead = await new PostgreSqlAuthorityStore(runtimeDatabase, { + tenant_id: this.tenantId, + goal_id: this.goalId, + expected_store_identity: storeIdentity, + }).loadAuthority(); + const todos = Array.isArray(snapshotRes.todos) ? (snapshotRes.todos as JsonObject[]) : []; + const s8Ok = snapshotRes.status === "snapshot" && + typeof snapshotRes.receipt_sha256 === "string" && + snapshotRes.receipt_sha256.length === 64 && + todos.some(t => t.todo_id === this.todoId && t.status === "done") && + readRes.status === "found" && + readTodo?.status === "done" && + directHead.status === "loaded" && + directHead.cursor === "5"; + steps.push({ + step: "cross_machine_snapshot_readback", + ok: s8Ok, + duration_ms: Date.now() - s8Start, + detail: { + status: snapshotRes.status, + receipt_sha256: snapshotRes.receipt_sha256, + todo_count: todos.length, + read_status: readRes.status, + direct_cursor: directHead.status === "loaded" ? directHead.cursor : null, + }, + }); + + const allOk = steps.every(s => s.ok) && (!isRealPg || (runtimeRoleVerified && serverMajorVersion === 16)); + return { + schema_version: "colima_pg16_coordination_rehearsal_report_v0", + ok: allOk, + mode, + execution_boundary: executionBoundary, + transport: "https_tls", + clock_mode: "controlled_service_clock", + runtime_role_verified: runtimeRoleVerified, + server_version: serverVersion, + server_version_num: serverVersionNum, + server_major_version: serverMajorVersion, + pg16_qualified: isRealPg && allOk && serverMajorVersion === 16, + tenant_id: this.tenantId, + goal_id: this.goalId, + store_identity: storeIdentity, + total_duration_ms: Date.now() - startTime, + actors: { + actor_a: this.actorA, + actor_b: this.actorB, + }, + steps, + }; + } catch (error) { + return { + schema_version: "colima_pg16_coordination_rehearsal_report_v0", + ok: false, + mode, + execution_boundary: executionBoundary, + transport: "https_tls", + clock_mode: "controlled_service_clock", + runtime_role_verified: runtimeRoleVerified, + server_version: serverVersion, + server_version_num: serverVersionNum, + server_major_version: serverMajorVersion, + pg16_qualified: false, + tenant_id: this.tenantId, + goal_id: this.goalId, + store_identity: storeIdentity, + total_duration_ms: Date.now() - startTime, + actors: { + actor_a: this.actorA, + actor_b: this.actorB, + }, + steps, + error: error instanceof Error ? error.message : String(error), + }; + } finally { + if (listener) { + await listener.close(); + } + await closePool(runtimePool); + await closePool(setupPool); + if (adminPool) { + try { + if (databaseCreated) await adminPool.query(`DROP DATABASE IF EXISTS ${dbName}`); + if (roleCreated) await adminPool.query(`DROP ROLE IF EXISTS ${roleName}`); + } finally { + await closePool(adminPool); + } + } + for (const dir of tempRoots) { + await rm(dir, {recursive: true, force: true}); + } + } + } + + private createSimulatedDatabase(storeIdentity: string): PostgreSqlAuthorityDatabase { + interface SimulatedCommit { + tenant_id: string; + goal_id: string; + cursor: number; + provider_revision: string; + operation_id: string; + } + interface SimulatedReceipt { + tenant_id: string; + goal_id: string; + cursor: number; + receipt_index: number; + receipt: unknown; + } + + const heads = new Map(); + const commits: SimulatedCommit[] = []; + const receipts: SimulatedReceipt[] = []; + + return { + connect: async () => { + let activeTenantId = "default"; + return { + query: async (sql: string, args?: readonly unknown[]) => { + const s = sql.trim(); + if ( + s.startsWith("BEGIN") || s.startsWith("COMMIT") || s.startsWith("ROLLBACK") || + s.startsWith("CREATE") || s.startsWith("ALTER") || s.startsWith("GRANT") || + s.startsWith("DO") || s.startsWith("DROP POLICY") + ) { + return {rows: [], rowCount: 0}; + } + if (s.includes("set_config")) { + activeTenantId = String(args?.[0] ?? "default"); + return {rows: [{tenant_id: activeTenantId}], rowCount: 1}; + } + if (s.includes("pg_advisory_")) { + return {rows: [], rowCount: 1}; + } + if (s.includes("INSERT INTO loopx_control_plane.authority_store_metadata")) { + return {rows: [], rowCount: 1}; + } + if (s.includes("FROM loopx_control_plane.authority_store_metadata")) { + return { + rows: [{schema_version: POSTGRESQL_SCHEMA_VERSION, store_identity: storeIdentity}], + rowCount: 1, + }; + } + if (s.includes("INSERT INTO loopx_control_plane.authority_heads")) { + const tenant = String(args?.[0]); + const goal = String(args?.[1]); + const key = `${tenant}:${goal}`; + if (!heads.has(key)) { + heads.set(key, {tenant_id: tenant, goal_id: goal, provider_revision: 0, cursor: 0, head: null}); + } + return {rows: [], rowCount: 1}; + } + if (s.includes("UPDATE loopx_control_plane.authority_heads")) { + const tenant = String(args?.[0]); + const goal = String(args?.[1]); + const rev = Number(args?.[2]); + const cursor = Number(args?.[3]); + const headObj = args?.[4] + ? (typeof args[4] === "string" ? JSON.parse(args[4]) : args[4]) as JsonObject + : null; + heads.set(`${tenant}:${goal}`, { + tenant_id: tenant, + goal_id: goal, + provider_revision: rev, + cursor, + head: headObj, + }); + return {rows: [], rowCount: 1}; + } + if (s.includes("FROM loopx_control_plane.authority_heads")) { + const tenant = String(args?.[0]); + const goal = String(args?.[1]); + const head = heads.get(`${tenant}:${goal}`); + if (!head || head.head === null) { + return { + rows: head ? [{provider_revision: "0", cursor: "0", head: null}] : [], + rowCount: head ? 1 : 0, + }; + } + return { + rows: [{ + provider_revision: String(head.provider_revision), + cursor: String(head.cursor), + head: head.head, + }], + rowCount: 1, + }; + } + if (s.includes("INSERT INTO loopx_control_plane.authority_checkpoints")) { + return {rows: [], rowCount: 1}; + } + if (s.includes("INSERT INTO loopx_control_plane.authority_commits")) { + commits.push({ + tenant_id: String(args?.[0]), + goal_id: String(args?.[1]), + cursor: Number(args?.[2]), + provider_revision: String(args?.[3]), + operation_id: String(args?.[4]), + }); + return {rows: [], rowCount: 1}; + } + if (s.includes("INSERT INTO loopx_control_plane.authority_receipts")) { + receipts.push({ + tenant_id: String(args?.[0]), + goal_id: String(args?.[1]), + cursor: Number(args?.[2]), + receipt_index: Number(args?.[3]), + receipt: args?.[4] ? (typeof args[4] === "string" ? JSON.parse(args[4]) : args[4]) : {}, + }); + return {rows: [], rowCount: 1}; + } + if (s.includes("INSERT INTO loopx_control_plane.authority_events")) { + return {rows: [], rowCount: 1}; + } + if (s.includes("FROM loopx_control_plane.authority_commits AS commit") && s.includes("commit.operation_id =")) { + const tenant = String(args?.[0]); + const goal = String(args?.[1]); + const opId = String(args?.[2]); + const match = commits.find(c => c.tenant_id === tenant && c.goal_id === goal && c.operation_id === opId); + if (!match) return {rows: [], rowCount: 0}; + const matchedReceipts = receipts + .filter(r => r.tenant_id === tenant && r.goal_id === goal && r.cursor === match.cursor) + .sort((a, b) => a.receipt_index - b.receipt_index) + .map(r => r.receipt); + return { + rows: [{ + cursor: String(match.cursor), + provider_revision: match.provider_revision, + operation_id: match.operation_id, + receipts: matchedReceipts, + }], + rowCount: 1, + }; + } + if (s.includes("FROM loopx_control_plane.authority_commits") && s.includes("operation_id =")) { + const tenant = String(args?.[0]); + const goal = String(args?.[1]); + const opId = String(args?.[2]); + const match = commits.find(c => c.tenant_id === tenant && c.goal_id === goal && c.operation_id === opId); + if (!match) return {rows: [], rowCount: 0}; + return { + rows: [{ + cursor: String(match.cursor), + provider_revision: match.provider_revision, + }], + rowCount: 1, + }; + } + return {rows: [], rowCount: 0}; + }, + release: () => {}, + }; + }, + }; + } +} + +function isDirectEntry(): boolean { + const entry = process.argv[1]; + if (!entry) { + return false; + } + try { + return ( + realpathSync(resolve(entry)) === + realpathSync(fileURLToPath(import.meta.url)) + ); + } catch (error: unknown) { + const code = + typeof error === "object" && error !== null && "code" in error + ? (error as {code?: unknown}).code + : undefined; + if (code === "ENOENT" || code === "ENOTDIR") { + return false; + } + throw error; + } +} + +// CLI entrypoint +if (isDirectEntry()) { + const {values} = parseArgs({ + options: { + "database-url": {type: "string"}, + simulate: {type: "boolean", default: false}, + verbose: {type: "boolean", default: false}, + "lease-ttl": {type: "string", default: "2"}, + }, + }); + + if (values.simulate && values["database-url"] !== undefined) { + process.stderr.write("Error: --simulate and --database-url are mutually exclusive.\n"); + process.exit(1); + } + if (values["database-url"] !== undefined && values["database-url"].trim().length === 0) { + process.stderr.write("Error: --database-url must be a non-empty PostgreSQL connection URL.\n"); + process.exit(1); + } + + const effectiveUrl = values.simulate + ? undefined + : (values["database-url"] ?? process.env.LOOPX_AUTHORITY_DATABASE_URL); + const rehearsal = new ColimaPgCoordinationRehearsal({ + databaseUrl: effectiveUrl, + simulate: values.simulate || !effectiveUrl?.trim(), + verbose: values.verbose, + leaseTtlSeconds: Number(values["lease-ttl"] || "2"), + }); + + const report = await rehearsal.run(); + process.stdout.write(`${JSON.stringify(report, null, 2)}\n`); + if (!report.ok) { + process.exit(1); + } +} diff --git a/examples/coordination/volcengine/gateway-caddy-tls.Caddyfile b/examples/coordination/volcengine/gateway-caddy-tls.Caddyfile new file mode 100644 index 0000000000..04ed8f0afa --- /dev/null +++ b/examples/coordination/volcengine/gateway-caddy-tls.Caddyfile @@ -0,0 +1,51 @@ +# ============================================================================== +# LoopX Remote Authority TLS Gateway - Caddy Configuration +# Reverse proxy terminating HTTPS and forwarding to local Node authority service +# ============================================================================== + +{ + admin off + auto_https disable_redirects + log { + output file /var/log/caddy/loopx_authority_access.log { + roll_size 50MiB + roll_keep 5 + } + format json + } +} + +:443, gateway.loopx.internal { + tls /etc/ssl/loopx/cert.pem /etc/ssl/loopx/key.pem { + protocols tls1.3 + } + + # Security headers + header { + Strict-Transport-Security "max-age=31536000; includeSubDomains" + X-Content-Type-Options "nosniff" + X-Frame-Options "DENY" + Referrer-Policy "strict-origin-when-cross-origin" + Cache-Control "no-store, no-cache, must-revalidate" + } + + # Limit request body to prevent memory pressure on authority service (16KB) + request_body { + max_size 16384 + } + + # Reverse proxy to loopx remote-authority-service + reverse_proxy 127.0.0.1:8443 { + transport http { + tls_insecure_skip_verify + dial_timeout 3s + response_header_timeout 15s + } + + # Pass client identification + header_up Host {host} + header_up X-Real-IP {remote_host} + header_up X-Forwarded-For {remote_host} + header_up X-Forwarded-Proto https + } +} diff --git a/examples/coordination/volcengine/least-privilege-iam-policy.json b/examples/coordination/volcengine/least-privilege-iam-policy.json new file mode 100644 index 0000000000..d54622be83 --- /dev/null +++ b/examples/coordination/volcengine/least-privilege-iam-policy.json @@ -0,0 +1,19 @@ +{ + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "rds_postgresql:DescribeDBInstances", + "rds_postgresql:DescribeDBInstanceDetail", + "rds_postgresql:DescribeDatabases", + "rds_postgresql:DescribeAccounts", + "vpc:DescribeVpcs", + "vpc:DescribeSubnets", + "vpc:DescribeSecurityGroups", + "ecs:DescribeInstances", + "ecs:DescribeInstanceStatus" + ], + "Resource": ["*"] + } + ] +} diff --git a/examples/coordination/volcengine/main.tf b/examples/coordination/volcengine/main.tf new file mode 100644 index 0000000000..b64751b23a --- /dev/null +++ b/examples/coordination/volcengine/main.tf @@ -0,0 +1,174 @@ +# ============================================================================== +# LoopX Volcengine cn-beijing Coordination & Gateway Infrastructure Template +# +# WARNING: STRICT HUMAN CONFIRMATION REQUIRED +# Do NOT run `terraform apply` automatically without explicit user authorization. +# ============================================================================== + +terraform { + required_version = ">= 1.5.0" + required_providers { + volcengine = { + source = "volcengine/volcengine" + version = ">= 0.0.186, < 0.1.0" + } + } +} + +variable "region" { + type = string + default = "cn-beijing" + description = "Volcengine region for coordination infrastructure" +} + +variable "availability_zone" { + type = string + default = "cn-beijing-a" + description = "Primary Volcengine availability zone" +} + +variable "secondary_availability_zone" { + type = string + default = "" + description = "Secondary Volcengine availability zone for RDS PostgreSQL (defaults to availability_zone)" +} + +variable "vpc_cidr" { + type = string + default = "172.16.0.0/16" + description = "VPC CIDR block" +} + +variable "subnet_cidr" { + type = string + default = "172.16.1.0/24" + description = "Subnet CIDR block for coordination services" +} + +variable "db_node_spec" { + type = string + default = "rds.postgres.1c2g" + description = "RDS for PostgreSQL 16 node specification (1C 2GB)" +} + +variable "db_storage_gb" { + type = number + default = 20 + description = "Allocated storage size in GB (range [20, 3000], step 10)" + validation { + condition = var.db_storage_gb >= 20 && var.db_storage_gb <= 3000 && var.db_storage_gb % 10 == 0 + error_message = "db_storage_gb must be between 20 and 3000 GB in steps of 10." + } +} + +variable "operator_allowlist_ips" { + type = list(string) + default = [] + description = "List of authorized operator IP CIDRs allowed to connect to Gateway port 443" +} + +variable "gateway_private_ips" { + type = set(string) + description = "Private IPv4 addresses of the gateways that connect to RDS" + validation { + condition = length(var.gateway_private_ips) > 0 && alltrue([ + for ip in var.gateway_private_ips : can(cidrnetmask("${ip}/32")) + ]) + error_message = "Provide at least one gateway private IPv4 address without a CIDR prefix." + } +} + +provider "volcengine" { + region = var.region +} + +# 1. Virtual Private Cloud (VPC) +resource "volcengine_vpc" "coordination_vpc" { + vpc_name = "loopx-coordination-vpc-beijing" + cidr_block = var.vpc_cidr + lifecycle { + prevent_destroy = true + } +} + +# 2. Isolated Subnet +resource "volcengine_subnet" "coordination_subnet" { + subnet_name = "loopx-coordination-subnet-a" + vpc_id = volcengine_vpc.coordination_vpc.id + cidr_block = var.subnet_cidr + zone_id = var.availability_zone + lifecycle { + prevent_destroy = true + } +} + +# 3. Security Group for Remote Authority Gateway (ECS) +resource "volcengine_security_group" "gateway_sg" { + security_group_name = "loopx-gateway-sg" + vpc_id = volcengine_vpc.coordination_vpc.id + description = "Security group for LoopX Remote Authority TLS Gateway" +} + +# Ingress: Allow TLS 443 from authorized operator CIDRs only +resource "volcengine_security_group_rule" "gateway_ingress_https" { + count = length(var.operator_allowlist_ips) > 0 ? length(var.operator_allowlist_ips) : 1 + security_group_id = volcengine_security_group.gateway_sg.id + direction = "ingress" + protocol = "tcp" + port_start = 443 + port_end = 443 + cidr_ip = length(var.operator_allowlist_ips) > 0 ? var.operator_allowlist_ips[count.index] : var.vpc_cidr + description = "Allow inbound TLS 443" +} + +# 4. RDS for PostgreSQL 16 Instance +resource "volcengine_rds_postgresql_instance" "coordination_db" { + db_engine_version = "PostgreSQL_16" + instance_name = "loopx-coordination-rds-pg16" + node_spec = var.db_node_spec + primary_zone_id = var.availability_zone + secondary_zone_id = var.secondary_availability_zone != "" ? var.secondary_availability_zone : var.availability_zone + storage_space = var.db_storage_gb + subnet_id = volcengine_subnet.coordination_subnet.id + + charge_info { + charge_type = "PostPaid" # Pay-as-you-go + } + + lifecycle { + prevent_destroy = true + ignore_changes = [charge_info] + } +} + +# 5. Database access from the configured gateway addresses +resource "volcengine_rds_postgresql_allowlist" "gateway_access" { + allow_list_name = "loopx-gateway-access" + allow_list_type = "IPv4" + allow_list = [for ip in var.gateway_private_ips : "${ip}/32"] +} + +resource "volcengine_rds_postgresql_allowlist_associate" "gateway_access" { + instance_id = volcengine_rds_postgresql_instance.coordination_db.id + allow_list_id = volcengine_rds_postgresql_allowlist.gateway_access.id +} + +output "vpc_id" { + value = volcengine_vpc.coordination_vpc.id + description = "Coordination VPC ID" +} + +output "subnet_id" { + value = volcengine_subnet.coordination_subnet.id + description = "Coordination Subnet ID" +} + +output "rds_endpoints" { + value = volcengine_rds_postgresql_instance.coordination_db.endpoints + description = "PostgreSQL endpoint records exported by the Volcengine RDS instance" +} + +output "rds_endpoint" { + value = try(volcengine_rds_postgresql_instance.coordination_db.endpoints[0].address[0].domain, "") + description = "Primary internal PostgreSQL domain endpoint for RemoteAuthorityService connection" +} diff --git a/examples/coordination/volcengine/remote-authority-systemd.service b/examples/coordination/volcengine/remote-authority-systemd.service new file mode 100644 index 0000000000..daea66023c --- /dev/null +++ b/examples/coordination/volcengine/remote-authority-systemd.service @@ -0,0 +1,39 @@ +[Unit] +Description=LoopX Remote Authority Coordination Service (Volcengine cn-beijing) +Documentation=https://github.com/loopx-project/loopx +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +WorkingDirectory=/opt/loopx +Environment=NODE_ENV=production +# Supply LOOPX_AUTHORITY_DATABASE_URL via a 0600 root-owned env file: +# LOOPX_AUTHORITY_DATABASE_URL=postgresql://loopx_app:@:5432/ +EnvironmentFile=/etc/loopx/authority.env +# Hand off policy and loopback TLS cert/key (0600 root:root on disk) read-only to the transient service user via %d/. +# Keep Caddy's edge TLS private key (/etc/ssl/loopx/key.pem) isolated to the caddy service. +LoadCredential=remote-policy.json:/etc/loopx/remote-policy.json +LoadCredential=authority-cert.pem:/etc/ssl/loopx/internal-cert.pem +LoadCredential=authority-key.pem:/etc/ssl/loopx/internal-key.pem +ExecStart=/usr/bin/node --no-warnings --experimental-strip-types examples/coordination/remote-authority-service.ts --policy %d/remote-policy.json --cert %d/authority-cert.pem --key %d/authority-key.pem --port 8443 --host 127.0.0.1 +Restart=on-failure +RestartSec=5s + +# Security Hardening +DynamicUser=yes +User=loopx-authority +Group=loopx-authority +NoNewPrivileges=true +ProtectSystem=strict +ProtectHome=true +PrivateTmp=true +PrivateDevices=true +ProtectKernelTunables=true +ProtectControlGroups=true +RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX +CapabilityBoundingSet=CAP_NET_BIND_SERVICE +LimitNOFILE=65536 + +[Install] +WantedBy=multi-user.target diff --git a/tests/control_plane_ts/coordination_colima_rehearsal.test.ts b/tests/control_plane_ts/coordination_colima_rehearsal.test.ts new file mode 100644 index 0000000000..a37935003f --- /dev/null +++ b/tests/control_plane_ts/coordination_colima_rehearsal.test.ts @@ -0,0 +1,401 @@ +import assert from "node:assert/strict"; +import {execFile} from "node:child_process"; +import net from "node:net"; +import {dirname, resolve} from "node:path"; +import test from "node:test"; +import {fileURLToPath} from "node:url"; +import {promisify} from "node:util"; +import { + ColimaPgCoordinationRehearsal, + parsePostgreSqlServerVersion, + type RehearsalReport, +} from "../../examples/coordination/colima-pg16-e2e-rehearsal.ts"; + +const execFileAsync = promisify(execFile); +const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); + +function pgFrame(type: string, body: Buffer): Buffer { + const header = Buffer.allocUnsafe(5); + header.write(type, 0, 1, "ascii"); + header.writeInt32BE(4 + body.length, 1); + return Buffer.concat([header, body]); +} + +function pgCString(value: string): Buffer { + return Buffer.from(`${value}\0`, "utf8"); +} + +function pgRowDescription(columnName: string): Buffer { + const count = Buffer.allocUnsafe(2); + count.writeInt16BE(1, 0); + const meta = Buffer.allocUnsafe(18); + meta.writeInt32BE(0, 0); // table oid + meta.writeInt16BE(0, 4); // attr num + meta.writeInt32BE(25, 6); // TEXTOID + meta.writeInt16BE(-1, 10); // type len + meta.writeInt32BE(-1, 12); // type mod + meta.writeInt16BE(0, 16); // text format + return pgFrame("T", Buffer.concat([count, pgCString(columnName), meta])); +} + +function pgDataRow(value: string): Buffer { + const valBuf = Buffer.from(value, "utf8"); + const count = Buffer.allocUnsafe(2); + count.writeInt16BE(1, 0); + const len = Buffer.allocUnsafe(4); + len.writeInt32BE(valBuf.length, 0); + return pgFrame("D", Buffer.concat([count, len, valBuf])); +} + +function pgErrorResponse(message: string): Buffer { + return pgFrame( + "E", + Buffer.concat([ + Buffer.from("S", "ascii"), pgCString("ERROR"), + Buffer.from("C", "ascii"), pgCString("42000"), + Buffer.from("M", "ascii"), pgCString(message), + Buffer.from([0]), + ]), + ); +} + +async function startFakePgVersionServer( + serverVersion: string, + serverVersionNum: string, +): Promise<{port: number; queries: string[]; close: () => Promise}> { + const queries: string[] = []; + const sockets = new Set(); + const server = net.createServer(socket => { + sockets.add(socket); + socket.on("close", () => sockets.delete(socket)); + let buffer = Buffer.alloc(0); + let startupDone = false; + + socket.on("data", chunk => { + buffer = Buffer.concat([buffer, chunk]); + while (buffer.length > 0) { + if (!startupDone) { + if (buffer.length < 8) return; + const msgLen = buffer.readInt32BE(0); + if (buffer.length < msgLen) return; + const code = buffer.readInt32BE(4); + buffer = buffer.subarray(msgLen); + if (code === 80877103) { + // SSLRequest -> decline TLS so driver proceeds with plaintext v3 startup + socket.write(Buffer.from("N", "ascii")); + continue; + } + startupDone = true; + const authOk = Buffer.alloc(4); + authOk.writeInt32BE(0, 0); + const paramBody = Buffer.concat([pgCString("server_version"), pgCString(serverVersion)]); + const backendKey = Buffer.alloc(8); + backendKey.writeInt32BE(1001, 0); + backendKey.writeInt32BE(2002, 4); + socket.write(Buffer.concat([ + pgFrame("R", authOk), + pgFrame("S", paramBody), + pgFrame("K", backendKey), + pgFrame("Z", Buffer.from("I", "ascii")), + ])); + continue; + } + + if (buffer.length < 5) return; + const msgType = String.fromCharCode(buffer[0]!); + const msgLen = buffer.readInt32BE(1); + if (buffer.length < 1 + msgLen) return; + const payload = buffer.subarray(5, 1 + msgLen); + buffer = buffer.subarray(1 + msgLen); + + if (msgType === "X") { + socket.end(); + return; + } + if (msgType === "Q") { + const sql = payload.toString("utf8").replace(/\0+$/, "").trim(); + queries.push(sql); + const normalized = sql.toLowerCase(); + if (normalized === "show server_version") { + socket.write(Buffer.concat([ + pgRowDescription("server_version"), + pgDataRow(serverVersion), + pgFrame("C", pgCString("SHOW")), + pgFrame("Z", Buffer.from("I", "ascii")), + ])); + } else if (normalized === "show server_version_num") { + socket.write(Buffer.concat([ + pgRowDescription("server_version_num"), + pgDataRow(serverVersionNum), + pgFrame("C", pgCString("SHOW")), + pgFrame("Z", Buffer.from("I", "ascii")), + ])); + } else { + socket.write(Buffer.concat([ + pgErrorResponse(`Unexpected write/query before version gate: ${sql}`), + pgFrame("Z", Buffer.from("I", "ascii")), + ])); + } + } + } + }); + }); + + await new Promise(resolveListen => server.listen(0, "127.0.0.1", resolveListen)); + const address = server.address(); + assert.ok(address && typeof address !== "string"); + + return { + port: address.port, + queries, + close: async () => { + for (const s of sockets) s.destroy(); + await new Promise((res, rej) => server.close(err => (err ? rej(err) : res()))); + }, + }; +} + +function assertAllRehearsalSteps( + report: RehearsalReport, + expectedMode: RehearsalReport["mode"], + expectedBoundary: RehearsalReport["execution_boundary"], +): void { + assert.equal(report.schema_version, "colima_pg16_coordination_rehearsal_report_v0"); + assert.equal(report.ok, true, `Rehearsal failed with error: ${report.error ?? JSON.stringify(report.steps)}`); + assert.equal(report.mode, expectedMode); + assert.equal(report.execution_boundary, expectedBoundary); + assert.equal(report.transport, "https_tls"); + assert.equal(report.clock_mode, "controlled_service_clock"); + assert.equal(report.runtime_role_verified, expectedMode === "real_pg"); + if (expectedMode === "real_pg") { + assert.equal(typeof report.server_version, "string"); + assert.equal(report.server_major_version, 16); + assert.ok( + typeof report.server_version_num === "number" && + report.server_version_num >= 160_000 && + report.server_version_num < 170_000, + ); + assert.equal(report.pg16_qualified, true); + } else { + assert.equal(report.server_version, null); + assert.equal(report.server_version_num, null); + assert.equal(report.server_major_version, null); + assert.equal(report.pg16_qualified, false); + } + assert.equal(report.tenant_id, "tenant-canary"); + assert.equal(report.goal_id, "loopx-quality-review"); + assert.equal(report.actors.actor_a, "operator.local"); + assert.equal(report.actors.actor_b, "worker.cloud"); + assert.equal(report.steps.length, 8); + + const stepsByName = new Map(report.steps.map(s => [s.step, s])); + + // Step 1: Schema initialization + const step1 = stepsByName.get("schema_initialization_and_role_assembly"); + assert.ok(step1); + assert.equal(step1.ok, true); + assert.equal(step1.detail.status, "installed"); + assert.match(String(step1.detail.runtime_role), /^loopx_app_[0-9a-f]+$/); + + // Step 2: Genesis seed ingestion + const step2 = stepsByName.get("genesis_seed_ingestion"); + assert.ok(step2); + assert.equal(step2.ok, true); + assert.equal(step2.detail.status, "seeded"); + assert.equal(step2.detail.cursor, "1"); + + // Step 3: Actor A lease claim over HTTPS/TLS + const step3 = stepsByName.get("actor_a_lease_claim"); + assert.ok(step3); + assert.equal(step3.ok, true); + assert.equal(step3.detail.result_status, "applied"); + assert.equal(step3.detail.claimed_by, "operator.local"); + assert.equal(step3.detail.transport, "https_tls"); + + // Step 4: Active lease conflict rejection + const step4 = stepsByName.get("active_lease_conflict_rejection"); + assert.ok(step4); + assert.equal(step4.ok, true); + assert.equal(step4.detail.status, "result"); + assert.ok(step4.detail.result_status === "rejected" || step4.detail.result_status === "failed"); + + // Step 5: Default-deny boundary enforcement + const step5 = stepsByName.get("default_deny_boundary_enforcement"); + assert.ok(step5); + assert.equal(step5.ok, true); + assert.equal(step5.detail.unauthorized_goal_status, "rejected"); + assert.equal(step5.detail.unauthorized_cred_status, "rejected"); + assert.equal(step5.detail.unauthorized_cred_reason, "principal_unauthenticated"); + + // Step 6: Lease expiration takeover & stale-actor fencing + const step6 = stepsByName.get("lease_expiration_takeover"); + assert.ok(step6); + assert.equal(step6.ok, true); + assert.equal(step6.detail.result_status, "applied"); + assert.equal(step6.detail.claimed_by, "worker.cloud"); + assert.equal(step6.detail.previous_lease_epoch, 1); + assert.equal(step6.detail.new_lease_epoch, 2); + assert.equal(step6.detail.stale_actor_fenced, true); + // Prove takeover is driven from observed expires_at via controlled service clock rather than wall-clock sleep. + const observedExpiresMs = Date.parse(String(step3.detail.expires_at)); + const advancedClockMs = Date.parse(String(step6.detail.advanced_service_clock)); + assert.ok(Number.isFinite(observedExpiresMs)); + assert.ok(Number.isFinite(advancedClockMs)); + assert.ok(observedExpiresMs - Date.now() > 60_000, "canonical lease expires ~2700s in the future"); + assert.equal(step6.detail.observed_expires_at, step3.detail.expires_at); + assert.equal(advancedClockMs, observedExpiresMs + 1_000); + + // Step 7: Actor B task completion + historical recovery readback + const step7 = stepsByName.get("actor_b_task_completion"); + assert.ok(step7); + assert.equal(step7.ok, true); + assert.equal(step7.detail.result_status, "applied"); + assert.equal(step7.detail.completed, true); + assert.equal(step7.detail.recover_status, "found"); + assert.equal(step7.detail.historical_only, true); + + // Step 8: Cross-machine snapshot & direct authority readback + const step8 = stepsByName.get("cross_machine_snapshot_readback"); + assert.ok(step8); + assert.equal(step8.ok, true); + assert.equal(step8.detail.status, "snapshot"); + assert.equal(typeof step8.detail.receipt_sha256, "string"); + assert.equal((step8.detail.receipt_sha256 as string).length, 64); + assert.equal(step8.detail.todo_count, 1); + assert.equal(step8.detail.read_status, "found"); + assert.equal(step8.detail.direct_cursor, "5"); +} + +test("Colima/PG16 coordination rehearsal completes all 8 HTTPS/TLS steps in simulation mode", async () => { + const rehearsal = new ColimaPgCoordinationRehearsal({ + simulate: true, + leaseTtlSeconds: 1, + }); + const report = await rehearsal.run(); + assertAllRehearsalSteps(report, "simulation", "in_memory_simulated_pg_tls"); +}); + +test( + "Colima/PG16 coordination rehearsal qualifies all 8 steps against real PostgreSQL with restricted role and TLS", + {skip: !process.env.LOOPX_TEST_POSTGRES_URL}, + async () => { + const rehearsal = new ColimaPgCoordinationRehearsal({ + databaseUrl: process.env.LOOPX_TEST_POSTGRES_URL, + simulate: false, + }); + const report = await rehearsal.run(); + assertAllRehearsalSteps(report, "real_pg", "isolated_real_pg16_tls"); + }, +); + +test("parsePostgreSqlServerVersion extracts major version from server_version and server_version_num", () => { + assert.deepEqual(parsePostgreSqlServerVersion("15.20", "150020"), { + server_version: "15.20", + server_version_num: 150020, + server_major_version: 15, + }); + assert.deepEqual(parsePostgreSqlServerVersion("16.4 (Debian 16.4-1.pgdg120+1)", "160004"), { + server_version: "16.4 (Debian 16.4-1.pgdg120+1)", + server_version_num: 160004, + server_major_version: 16, + }); + assert.deepEqual(parsePostgreSqlServerVersion("17.2", undefined), { + server_version: "17.2", + server_version_num: 170002, + server_major_version: 17, + }); + assert.deepEqual(parsePostgreSqlServerVersion("invalid", "unknown"), { + server_version: "invalid", + server_version_num: null, + server_major_version: null, + }); +}); + +test("Colima/PG16 coordination rehearsal refuses PostgreSQL 15.20 before any DB write via TS and shell", async () => { + const server = await startFakePgVersionServer("15.20", "150020"); + try { + const url = `postgresql://postgres:secret@127.0.0.1:${server.port}/postgres`; + + // 1) Programmatic API check + const report = await new ColimaPgCoordinationRehearsal({ + databaseUrl: url, + simulate: false, + }).run(); + assert.equal(report.ok, false); + assert.equal(report.mode, "real_pg"); + assert.equal(report.execution_boundary, "isolated_real_postgresql_tls"); + assert.equal(report.server_version, "15.20"); + assert.equal(report.server_version_num, 150020); + assert.equal(report.server_major_version, 15); + assert.equal(report.pg16_qualified, false); + assert.equal(report.runtime_role_verified, false); + assert.equal(report.steps.length, 0); + assert.match(report.error ?? "", /PostgreSQL 16 is required.*15\.20/); + assert.deepEqual(server.queries, ["SHOW server_version", "SHOW server_version_num"]); + + // 2) Same shell --database-url entrypoint check + server.queries.length = 0; + let shellStdout = ""; + let exitCode: unknown = 0; + try { + await execFileAsync( + resolve(REPO_ROOT, "examples/coordination/colima-pg16-e2e-rehearsal.sh"), + ["--database-url", url], + {cwd: REPO_ROOT}, + ); + } catch (err) { + const execErr = err as {code?: unknown; stdout?: string}; + exitCode = execErr.code; + shellStdout = execErr.stdout ?? ""; + } + assert.equal(exitCode, 1); + const shellReport = JSON.parse(shellStdout) as RehearsalReport; + assert.equal(shellReport.ok, false); + assert.equal(shellReport.execution_boundary, "isolated_real_postgresql_tls"); + assert.equal(shellReport.server_version, "15.20"); + assert.equal(shellReport.server_version_num, 150020); + assert.equal(shellReport.server_major_version, 15); + assert.equal(shellReport.pg16_qualified, false); + assert.equal(shellReport.steps.length, 0); + assert.deepEqual(server.queries, ["SHOW server_version", "SHOW server_version_num"]); + } finally { + await server.close(); + } +}); + +test("Colima/PG16 coordination rehearsal refuses PostgreSQL 17.2 before any DB write", async () => { + const server = await startFakePgVersionServer("17.2", "170002"); + try { + const report = await new ColimaPgCoordinationRehearsal({ + databaseUrl: `postgresql://postgres:secret@127.0.0.1:${server.port}/postgres`, + simulate: false, + }).run(); + assert.equal(report.ok, false); + assert.equal(report.execution_boundary, "isolated_real_postgresql_tls"); + assert.equal(report.server_version, "17.2"); + assert.equal(report.server_version_num, 170002); + assert.equal(report.server_major_version, 17); + assert.equal(report.pg16_qualified, false); + assert.equal(report.steps.length, 0); + assert.deepEqual(server.queries, ["SHOW server_version", "SHOW server_version_num"]); + } finally { + await server.close(); + } +}); + +test( + "Colima/PG16 coordination rehearsal refuses live non-16 PostgreSQL server without marking PG16", + {skip: !process.env.LOOPX_TEST_POSTGRES_NON16_URL}, + async () => { + const report = await new ColimaPgCoordinationRehearsal({ + databaseUrl: process.env.LOOPX_TEST_POSTGRES_NON16_URL, + simulate: false, + }).run(); + assert.equal(report.ok, false); + assert.equal(report.mode, "real_pg"); + assert.equal(report.execution_boundary, "isolated_real_postgresql_tls"); + assert.equal(report.pg16_qualified, false); + assert.notEqual(report.server_major_version, 16); + assert.equal(report.steps.length, 0); + }, +); diff --git a/tests/test_colima_pg_rehearsal.py b/tests/test_colima_pg_rehearsal.py new file mode 100644 index 0000000000..9babffecf9 --- /dev/null +++ b/tests/test_colima_pg_rehearsal.py @@ -0,0 +1,925 @@ +"""Verification test suite for Colima / Docker PostgreSQL 16 dual-actor rehearsal + +and Volcengine cn-beijing deployment templates. +""" + +from __future__ import annotations + +import json +import os +import socket +import struct +import subprocess +import tarfile +import tempfile +import threading +import time +import uuid +from pathlib import Path +from typing import IO + +import pytest + +REPO_ROOT = Path(__file__).resolve().parent.parent + + +def test_rehearsal_shell_script_help() -> None: + """Verify that the shell wrapper outputs help information cleanly.""" + script_path = REPO_ROOT / "examples" / "coordination" / "colima-pg16-e2e-rehearsal.sh" + assert script_path.exists() + assert script_path.is_file() + + result = subprocess.run( + [str(script_path), "--help"], + capture_output=True, + text=True, + check=True, + ) + assert "--simulate" in result.stdout + assert "--rehearsal" in result.stdout + assert "--database-url" in result.stdout + assert "--start-colima" in result.stdout + + +def test_rehearsal_explicit_mode_fails_closed_without_docker() -> None: + """Explicit --rehearsal must fail closed rather than silently downgrading to --simulate.""" + script_path = REPO_ROOT / "examples" / "coordination" / "colima-pg16-e2e-rehearsal.sh" + env = {**os.environ, "DOCKER_HOST": "unix:///nonexistent/loopx-no-docker.sock"} + result = subprocess.run( + [str(script_path), "--rehearsal"], + capture_output=True, + text=True, + env=env, + cwd=REPO_ROOT, + ) + assert result.returncode != 0 + assert "simulation" not in result.stdout.lower() + + +def test_rehearsal_simulation_e2e() -> None: + """Verify that rehearsal runs end-to-end in simulation mode with ok: true.""" + script_path = REPO_ROOT / "examples" / "coordination" / "colima-pg16-e2e-rehearsal.sh" + result = subprocess.run( + [str(script_path), "--simulate"], + capture_output=True, + text=True, + check=True, + cwd=REPO_ROOT, + ) + data = json.loads(result.stdout) + + assert data["schema_version"] == "colima_pg16_coordination_rehearsal_report_v0" + assert data["ok"] is True + assert data["mode"] == "simulation" + assert data["execution_boundary"] == "in_memory_simulated_pg_tls" + assert data["transport"] == "https_tls" + assert data["clock_mode"] == "controlled_service_clock" + assert data["runtime_role_verified"] is False + assert data["server_version"] is None + assert data["server_version_num"] is None + assert data["server_major_version"] is None + assert data["pg16_qualified"] is False + assert data["tenant_id"] == "tenant-canary" + assert data["goal_id"] == "loopx-quality-review" + assert data["actors"]["actor_a"] == "operator.local" + assert data["actors"]["actor_b"] == "worker.cloud" + + expected_steps = [ + "schema_initialization_and_role_assembly", + "genesis_seed_ingestion", + "actor_a_lease_claim", + "active_lease_conflict_rejection", + "default_deny_boundary_enforcement", + "lease_expiration_takeover", + "actor_b_task_completion", + "cross_machine_snapshot_readback", + ] + step_names = [s["step"] for s in data["steps"]] + assert step_names == expected_steps + + for step in data["steps"]: + assert step["ok"] is True, f"Step {step['step']} failed: {step['detail']}" + + +def test_rehearsal_ts_cli_direct() -> None: + """Verify that the TypeScript harness can be directly invoked via node.""" + ts_path = REPO_ROOT / "examples" / "coordination" / "colima-pg16-e2e-rehearsal.ts" + result = subprocess.run( + [ + "node", + "--no-warnings", + "--experimental-sqlite", + "--experimental-strip-types", + str(ts_path), + "--simulate", + ], + capture_output=True, + text=True, + check=True, + cwd=REPO_ROOT, + ) + data = json.loads(result.stdout) + assert data["ok"] is True + assert data["transport"] == "https_tls" + assert len(data["steps"]) == 8 + + +def test_rehearsal_rejects_empty_database_url_and_conflicting_flags() -> None: + """Explicit --database-url '' or conflicting flags must fail closed without simulation fallback.""" + script_path = REPO_ROOT / "examples" / "coordination" / "colima-pg16-e2e-rehearsal.sh" + ts_path = REPO_ROOT / "examples" / "coordination" / "colima-pg16-e2e-rehearsal.ts" + + shell_empty = subprocess.run( + [str(script_path), "--database-url", ""], + capture_output=True, + text=True, + cwd=REPO_ROOT, + ) + assert shell_empty.returncode != 0 + assert "simulation" not in shell_empty.stdout.lower() + + ts_empty = subprocess.run( + [ + "node", + "--no-warnings", + "--experimental-sqlite", + "--experimental-strip-types", + str(ts_path), + "--database-url", + "", + ], + capture_output=True, + text=True, + cwd=REPO_ROOT, + ) + assert ts_empty.returncode != 0 + assert "simulation" not in ts_empty.stdout.lower() + + ts_conflict = subprocess.run( + [ + "node", + "--no-warnings", + "--experimental-sqlite", + "--experimental-strip-types", + str(ts_path), + "--simulate", + "--database-url", + "postgresql://postgres:secret@127.0.0.1:5432/postgres", + ], + capture_output=True, + text=True, + cwd=REPO_ROOT, + ) + assert ts_conflict.returncode != 0 + assert "simulation" not in ts_conflict.stdout.lower() + + +def test_rehearsal_shell_rejects_conflicting_modes_both_orders_without_side_effects( + tmp_path: Path, +) -> None: + """Conflicting shell mode flags fail closed in all orders before Docker, Node, or PG I/O.""" + script_path = REPO_ROOT / "examples" / "coordination" / "colima-pg16-e2e-rehearsal.sh" + shim_dir = tmp_path / "shims" + shim_dir.mkdir() + side_effect_log = tmp_path / "invocations.log" + for tool in ("docker", "colima", "node"): + shim = shim_dir / tool + shim.write_text( + "#!/usr/bin/env bash\n" + f'printf "%s %s\\n" "{tool}" "$*" >> "{side_effect_log}"\n' + "exit 99\n", + encoding="utf-8", + ) + shim.chmod(0o755) + + # Bind a listening TCP socket to assert zero PostgreSQL connections or DDL occur. + connections = 0 + server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server.bind(("127.0.0.1", 0)) + server.listen(4) + port = server.getsockname()[1] + stop_event = threading.Event() + + def accept_loop() -> None: + nonlocal connections + server.settimeout(0.1) + while not stop_event.is_set(): + try: + conn, _ = server.accept() + except TimeoutError: + continue + except OSError: + break + connections += 1 + conn.close() + + listener = threading.Thread(target=accept_loop, daemon=True) + listener.start() + try: + db_url = f"postgresql://postgres:secret@127.0.0.1:{port}/postgres" + env = { + **os.environ, + "PATH": f"{shim_dir}:{os.environ.get('PATH', '')}", + } + conflict_cases = [ + ["--simulate", "--database-url", db_url], + ["--database-url", db_url, "--simulate"], + ["--simulate", "--rehearsal"], + ["--rehearsal", "--simulate"], + ["--simulate", "--start-colima"], + ["--start-colima", "--simulate"], + ["--rehearsal", "--database-url", db_url], + ["--database-url", db_url, "--rehearsal"], + ["--start-colima", "--database-url", db_url], + ["--database-url", db_url, "--start-colima"], + ["--database-url", db_url, "--database-url", db_url], + ] + for args in conflict_cases: + res = subprocess.run( + [str(script_path), *args], + capture_output=True, + text=True, + env=env, + cwd=REPO_ROOT, + ) + assert res.returncode == 1, f"{args}: rc={res.returncode}, stderr={res.stderr}" + assert res.stdout == "", f"{args}: unexpected stdout {res.stdout!r}" + assert "mutually exclusive" in res.stderr.lower(), res.stderr + assert not side_effect_log.exists(), side_effect_log.read_text(encoding="utf-8") + assert connections == 0 + finally: + stop_event.set() + server.close() + listener.join(timeout=2) + + +def _pg_frame(msg_type: bytes, body: bytes) -> bytes: + return msg_type + struct.pack("!I", 4 + len(body)) + body + + +def test_rehearsal_refuses_pg15_before_writes_via_shell_entrypoint() -> None: + """Connecting --database-url to PostgreSQL 15.20 must fail before any write and never emit PG16 boundary.""" + queries: list[str] = [] + server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server.bind(("127.0.0.1", 0)) + server.listen(4) + port = server.getsockname()[1] + stop_event = threading.Event() + + def serve() -> None: + server.settimeout(0.2) + while not stop_event.is_set(): + try: + conn, _ = server.accept() + except TimeoutError: + continue + except OSError: + break + with conn: + buf = b"" + startup_done = False + while not stop_event.is_set(): + chunk = conn.recv(4096) + if not chunk: + break + buf += chunk + while buf: + if not startup_done: + if len(buf) < 8: + break + msg_len = struct.unpack("!I", buf[:4])[0] + if len(buf) < msg_len: + break + code = struct.unpack("!I", buf[4:8])[0] + buf = buf[msg_len:] + if code == 80877103: + conn.sendall(b"N") + continue + startup_done = True + conn.sendall( + _pg_frame(b"R", struct.pack("!I", 0)) + + _pg_frame(b"S", b"server_version\x0015.20\x00") + + _pg_frame(b"K", struct.pack("!II", 1, 2)) + + _pg_frame(b"Z", b"I") + ) + continue + if len(buf) < 5: + break + msg_type = buf[:1] + msg_len = struct.unpack("!I", buf[1:5])[0] + if len(buf) < 1 + msg_len: + break + payload = buf[5 : 1 + msg_len] + buf = buf[1 + msg_len :] + if msg_type == b"X": + return + if msg_type == b"Q": + sql = payload.rstrip(b"\x00").decode("utf-8").strip() + queries.append(sql) + if sql.lower() == "show server_version": + col = b"server_version\x00" + val = b"15.20" + elif sql.lower() == "show server_version_num": + col = b"server_version_num\x00" + val = b"150020" + else: + err = b"SERROR\x00C42000\x00Munexpected write\x00\x00" + conn.sendall(_pg_frame(b"E", err) + _pg_frame(b"Z", b"I")) + continue + row_desc = _pg_frame( + b"T", + struct.pack("!H", 1) + col + struct.pack("!IhIhih", 0, 0, 25, -1, -1, 0), + ) + data_row = _pg_frame(b"D", struct.pack("!HI", 1, len(val)) + val) + cmd_complete = _pg_frame(b"C", b"SHOW\x00") + ready = _pg_frame(b"Z", b"I") + conn.sendall(row_desc + data_row + cmd_complete + ready) + + thread = threading.Thread(target=serve, daemon=True) + thread.start() + try: + script_path = REPO_ROOT / "examples" / "coordination" / "colima-pg16-e2e-rehearsal.sh" + result = subprocess.run( + [str(script_path), "--database-url", f"postgresql://postgres:secret@127.0.0.1:{port}/postgres"], + capture_output=True, + text=True, + cwd=REPO_ROOT, + ) + assert result.returncode == 1 + data = json.loads(result.stdout) + assert data["ok"] is False + assert data["mode"] == "real_pg" + assert data["execution_boundary"] == "isolated_real_postgresql_tls" + assert data["server_version"] == "15.20" + assert data["server_version_num"] == 150020 + assert data["server_major_version"] == 15 + assert data["pg16_qualified"] is False + assert data["runtime_role_verified"] is False + assert data["steps"] == [] + assert "15.20" in data.get("error", "") + assert queries == ["SHOW server_version", "SHOW server_version_num"] + finally: + stop_event.set() + server.close() + thread.join(timeout=2) + + +def test_volcengine_deployment_artifacts() -> None: + """Verify presence and validity of all Volcengine cn-beijing deployment assets.""" + doc_path = ( + REPO_ROOT + / "docs" + / "reference" + / "deployment" + / "volcengine-cn-beijing-pg-gateway.md" + ) + assert doc_path.exists(), "Deployment reference document missing" + doc_content = doc_path.read_text(encoding="utf-8") + assert "严禁未经用户确认自动购买云资源或改线上配置" in doc_content + assert "cn-beijing" in doc_content + assert "loopx_app" in doc_content + assert "ark.cn-beijing.volces.com" in doc_content + assert "operator.local" in doc_content + assert "worker.cloud" in doc_content + + # Verify public-boundary neutrality: no machine-specific or pre-existing local credential files + for forbidden in ( + "operations-ark-video.json", + "复用本机", + "macOS Apple Silicon dev", + "gateway.loopx.bj.volces.com", + ): + assert forbidden not in doc_content, f"Non-public local assumption {forbidden!r} in deployment doc" + assert "EnvironmentFile" in doc_content or "环境变量" in doc_content + assert "LOOPX_AUTHORITY_CREDENTIAL" in doc_content + assert "ARK_API_KEY" in doc_content + # Verify Stage 2B setup, restricted-role seed execution, and target readback instructions + assert "postgres setup --runtime-role loopx_app --execute" in doc_content + assert "local-to-pg-seed" in doc_content + assert "--store-identity" in doc_content + assert "--execute" in doc_content + assert "ALTER ROLE loopx_app" in doc_content + assert "GRANT CONNECT ON DATABASE" in doc_content + assert "NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT" in doc_content + assert "PostgreSqlAuthorityStore" in doc_content + assert "loadAuthority()" in doc_content + assert '"operation": "snapshot"' in doc_content + + volc_dir = REPO_ROOT / "examples" / "coordination" / "volcengine" + assert volc_dir.is_dir() + + # Terraform template: check valid published provider series (< 0.1.0) and real resource fields + tf_path = volc_dir / "main.tf" + assert tf_path.exists() + tf_content = tf_path.read_text(encoding="utf-8") + assert 'variable "region"' in tf_content + assert 'source = "volcengine/volcengine"' in tf_content + assert "~> 0.1.20" not in tf_content + assert ">= 0.0.186, < 0.1.0" in tf_content + assert "volcengine_rds_postgresql_instance" in tf_content + assert "node_spec" in tf_content + assert "primary_zone_id" in tf_content + assert "secondary_zone_id" in tf_content + assert "charge_info" in tf_content + assert ".endpoints" in tf_content + # Guardrail: computed-only or non-schema root attributes must not appear as instance arguments + rds_block = tf_content.split('resource "volcengine_rds_postgresql_instance"')[1].split("output ")[0] + for invalid_arg in ("instance_type ", "storage_type ", "vpc_id ", "charge_type ="): + # charge_type inside charge_info block is valid, so check root-level indentation (2 spaces) + if invalid_arg == "charge_type =": + assert "\n charge_type " not in rds_block + else: + assert f"\n {invalid_arg}" not in rds_block + assert "prevent_destroy = true" in tf_content + + # Caddyfile + caddy_path = volc_dir / "gateway-caddy-tls.Caddyfile" + assert caddy_path.exists() + caddy_content = caddy_path.read_text(encoding="utf-8") + assert "reverse_proxy 127.0.0.1:8443" in caddy_content + + # Systemd service + svc_path = volc_dir / "remote-authority-systemd.service" + assert svc_path.exists() + svc_content = svc_path.read_text(encoding="utf-8") + assert "DynamicUser=yes" in svc_content + assert "EnvironmentFile=/etc/loopx/authority.env" in svc_content + assert "REPLACE_WITH_RESTRICTED_APP_PASSWORD" not in svc_content + assert "remote-authority-service.ts" in svc_content + + load_credentials = [ + line.split("=", 1)[1].strip() + for line in svc_content.splitlines() + if line.strip().startswith("LoadCredential=") + ] + assert "remote-policy.json:/etc/loopx/remote-policy.json" in load_credentials + assert "authority-cert.pem:/etc/ssl/loopx/internal-cert.pem" in load_credentials + assert "authority-key.pem:/etc/ssl/loopx/internal-key.pem" in load_credentials + assert all("authority.env" not in entry for entry in load_credentials) + assert all("/etc/ssl/loopx/key.pem" not in entry for entry in load_credentials) + + exec_lines = [ + line.split("=", 1)[1].strip() + for line in svc_content.splitlines() + if line.strip().startswith("ExecStart=") + ] + assert len(exec_lines) == 1 + exec_cmd = exec_lines[0] + assert "--policy %d/remote-policy.json" in exec_cmd + assert "--cert %d/authority-cert.pem" in exec_cmd + assert "--key %d/authority-key.pem" in exec_cmd + assert "/etc/loopx/" not in exec_cmd + assert "/etc/ssl/loopx/" not in exec_cmd + + # Runbook permission, unit/Caddy installation, and isolation contract + assert "LoadCredential=" in doc_content + assert "%d/remote-policy.json" in doc_content + assert "/etc/ssl/loopx/internal-key.pem" in doc_content + assert "/etc/ssl/loopx/key.pem" in doc_content + assert "/etc/systemd/system/remote-authority-systemd.service" in doc_content + assert "/etc/caddy/Caddyfile" in doc_content + assert "caddy validate" in doc_content + assert "root:caddy" in doc_content + assert "0640" in doc_content + assert "0600" in doc_content + assert "EACCES" in doc_content + unit_install_idx = doc_content.index("/etc/systemd/system/remote-authority-systemd.service") + reload_idx = doc_content.index("systemctl daemon-reload") + enable_idx = doc_content.index("systemctl enable --now remote-authority-systemd.service") + assert unit_install_idx < reload_idx < enable_idx + + # Least privilege IAM policy + iam_path = volc_dir / "least-privilege-iam-policy.json" + assert iam_path.exists() + iam_json = json.loads(iam_path.read_text(encoding="utf-8")) + assert "Statement" in iam_json + actions = iam_json["Statement"][0]["Action"] + assert "rds_postgresql:DescribeDBInstances" in actions + # Guardrail: Mutating actions must NOT be present in worker policy + for action in actions: + assert not action.startswith("rds_postgresql:Create"), f"Mutating action {action} in policy" + assert not action.startswith("rds_postgresql:Delete"), f"Destructive action {action} in policy" + + +def test_rehearsal_symlink_directory_invocation(tmp_path: Path) -> None: + """Invoking .sh or .ts via a symlinked directory must still run and never false-pass 0.""" + linked_root = tmp_path / "symlink-worktree" + linked_root.symlink_to(REPO_ROOT, target_is_directory=True) + linked_sh = linked_root / "examples" / "coordination" / "colima-pg16-e2e-rehearsal.sh" + linked_ts = linked_root / "examples" / "coordination" / "colima-pg16-e2e-rehearsal.ts" + + sh_sim = subprocess.run([str(linked_sh), "--simulate"], capture_output=True, text=True, check=True, cwd=linked_root) + sh_data = json.loads(sh_sim.stdout) + assert sh_data["ok"] is True + assert len(sh_data["steps"]) == 8 + + sh_bad_url = subprocess.run([str(linked_sh), "--database-url", "postgresql://invalid"], capture_output=True, text=True, cwd=linked_root) + assert sh_bad_url.returncode != 0 + + ts_sim = subprocess.run( + ["node", "--no-warnings", "--experimental-sqlite", "--experimental-strip-types", str(linked_ts), "--simulate"], + capture_output=True, text=True, check=True, cwd=linked_root, + ) + ts_data = json.loads(ts_sim.stdout) + assert ts_data["ok"] is True + assert len(ts_data["steps"]) == 8 + + ts_bad_url = subprocess.run( + ["node", "--no-warnings", "--experimental-sqlite", "--experimental-strip-types", str(linked_ts), "--database-url", "postgresql://invalid"], + capture_output=True, text=True, cwd=linked_root, + ) + assert ts_bad_url.returncode != 0 + + +def _docker_env() -> dict[str, str]: + env = dict(os.environ) + if "DOCKER_HOST" not in env and "DOCKER_CONFIG" not in env and os.name == "posix": + import pwd + + docker_cfg = Path(pwd.getpwuid(os.getuid()).pw_dir) / ".docker" + if docker_cfg.is_dir(): + env["DOCKER_CONFIG"] = str(docker_cfg) + return env + + +def _docker_images_ready() -> tuple[bool, str]: + env = _docker_env() + info = subprocess.run(["docker", "info", "--format", "{{.OSType}}"], capture_output=True, text=True, timeout=5, env=env) + if info.returncode != 0 or info.stdout.strip() != "linux": + return False, "Linux Docker daemon unavailable" + for image in ("node:22-bookworm", "postgres:16-alpine"): + if subprocess.run(["docker", "image", "inspect", image], capture_output=True, text=True, timeout=5, env=env).returncode != 0: + return False, f"Required cached Docker image missing: {image}" + return True, "" + + +def _resolve_host_node_modules_root(repo_root: Path) -> Path | None: + if (repo_root / "node_modules" / "pg" / "package.json").is_file(): + return repo_root + common = subprocess.run(["git", "-C", str(repo_root), "rev-parse", "--git-common-dir"], capture_output=True, text=True, timeout=5) + if common.returncode == 0 and common.stdout.strip(): + raw_dir = Path(common.stdout.strip()) + resolved = raw_dir if raw_dir.is_absolute() else (repo_root / raw_dir).resolve() + if (resolved.parent / "node_modules" / "pg" / "package.json").is_file(): + return resolved.parent + return None + + +def _resolve_node_pkg(nm_dir: Path, pkg_name: str, parent_dir: Path | None, parent_arc: str) -> tuple[str, Path] | None: + candidates: list[tuple[str, Path]] = [] + if parent_dir is not None: + candidates.append((f"{parent_arc}/node_modules/{pkg_name}", parent_dir / "node_modules" / pkg_name)) + candidates.append((pkg_name, nm_dir / pkg_name)) + for arc_rel, candidate in candidates: + try: + resolved = candidate.resolve(strict=True) + except OSError: + continue + if (resolved / "package.json").is_file(): + return arc_rel, resolved + return None + + +def _collect_runtime_node_packages(nm_dir: Path, root_pkg: str = "pg") -> dict[str, Path]: + pending: list[tuple[str, bool, Path | None, str]] = [(root_pkg, True, None, "")] + staged: dict[str, Path] = {} + seen_targets: set[tuple[str, bool]] = set() + while pending: + pkg_name, required, parent_dir, parent_arc = pending.pop(0) + found = _resolve_node_pkg(nm_dir, pkg_name, parent_dir, parent_arc) + if found is None: + if required: + raise AssertionError(f"Required npm package {pkg_name!r} missing or dangling under {nm_dir}") + continue + arc_rel, resolved = found + if (arc_rel, required) in seen_targets: + continue + seen_targets.add((arc_rel, required)) + staged[arc_rel] = resolved + meta = json.loads((resolved / "package.json").read_text(encoding="utf-8")) + for dep in meta.get("dependencies") or {}: + pending.append((dep, True, resolved, arc_rel)) + for dep in meta.get("optionalDependencies") or {}: + pending.append((dep, False, resolved, arc_rel)) + return staged + + +def _build_opt_loopx_tar(repo_root: Path, nm_root: Path, archive: IO[bytes]) -> None: + def _normalize(ti: tarfile.TarInfo) -> tarfile.TarInfo | None: + if "__pycache__" in ti.name.split("/") or ti.issym() or ti.islnk(): + return None + ti.uid = ti.gid = 0 + ti.uname = ti.gname = "root" + ti.mode = 0o755 if ti.isdir() or (ti.mode & 0o111) else 0o644 + return ti + + nm_dir = (nm_root / "node_modules").resolve(strict=True) + runtime_pkgs = _collect_runtime_node_packages(nm_dir, "pg") + with tarfile.open(fileobj=archive, mode="w", dereference=False) as tf: + for rel in ("package.json", "loopx/control_plane", "examples/coordination"): + tf.add((repo_root / rel).resolve(strict=True), arcname=f"loopx/{rel}", filter=_normalize) + tf.add(nm_dir, arcname="loopx/node_modules", recursive=False, filter=_normalize) + for arc_rel, resolved in runtime_pkgs.items(): + tf.add(resolved, arcname=f"loopx/node_modules/{arc_rel}", filter=_normalize) + + +def _run_node_container_with_opt_loopx( + docker_env: dict[str, str], net_name: str, repo_root: Path, container_script: str, env_vars: dict[str, str], +) -> subprocess.CompletedProcess[str]: + env_args = [item for k, v in env_vars.items() for item in ("-e", f"{k}={v}")] + probe = subprocess.run( + [ + "docker", "run", "--rm", "-v", f"{repo_root}:/opt/loopx:ro", "node:22-bookworm", + "test", "-f", "/opt/loopx/node_modules/pg/package.json", + "-a", "-f", "/opt/loopx/examples/coordination/remote-authority-service.ts", + ], + capture_output=True, text=True, timeout=15, env=docker_env, + ) + if probe.returncode == 0: + return subprocess.run( + ["docker", "run", "--rm", "-i", "--network", net_name, "-v", f"{repo_root}:/opt/loopx:ro", "-w", "/opt/loopx", *env_args, "node:22-bookworm", "bash", "-s"], + input=container_script, capture_output=True, text=True, timeout=90, env=docker_env, + ) + + nm_root = _resolve_host_node_modules_root(repo_root) + assert nm_root is not None, "Host node_modules/pg is required for container check" + cid = subprocess.run( + ["docker", "create", "-i", "--network", net_name, "-w", "/opt/loopx", *env_args, "node:22-bookworm", "bash", "-s"], + check=True, capture_output=True, text=True, env=docker_env, + ).stdout.strip() + try: + with tempfile.TemporaryFile() as archive: + _build_opt_loopx_tar(repo_root, nm_root, archive) + archive.seek(0) + subprocess.run(["docker", "cp", "-", f"{cid}:/opt"], stdin=archive, check=True, capture_output=True, env=docker_env) + return subprocess.run( + ["docker", "start", "-a", "-i", cid], input=container_script, capture_output=True, text=True, timeout=90, env=docker_env, + ) + finally: + subprocess.run(["docker", "rm", "-f", cid], capture_output=True, text=True, env=docker_env) + + +def _assert_nonroot_load_credential_snapshot(repo_root: Path) -> None: + ready, reason = _docker_images_ready() + if not ready: + pytest.skip(reason) + + docker_env = _docker_env() + suffix = uuid.uuid4().hex[:10] + net_name = f"loopx-cred-net-{suffix}" + pg_name = f"loopx-cred-pg-{suffix}" + pg_admin_pw = f"pgadm_{suffix}" + pg_app_pw = f"pgapp_{suffix}" + + subprocess.run(["docker", "network", "create", net_name], check=True, capture_output=True, text=True, env=docker_env) + try: + subprocess.run( + ["docker", "run", "-d", "--rm", "--name", pg_name, "--network", net_name, "-e", f"POSTGRES_PASSWORD={pg_admin_pw}", "postgres:16-alpine"], + check=True, capture_output=True, text=True, env=docker_env, + ) + deadline = time.monotonic() + 25.0 + while time.monotonic() < deadline: + if subprocess.run(["docker", "exec", pg_name, "pg_isready", "-U", "postgres"], capture_output=True, text=True, env=docker_env).returncode == 0: + break + time.sleep(0.5) + else: + pytest.fail("PostgreSQL container did not become ready within 25s") + + container_script = r""" +set -eu +ln -sf "$(command -v node)" /usr/bin/node +groupadd -r caddy +useradd -r -g caddy -s /usr/sbin/nologin caddy + +install -d -o root -g root -m 0700 /etc/loopx +install -d -o root -g caddy -m 0750 /etc/ssl/loopx + +openssl req -x509 -newkey rsa:2048 -nodes -days 1 \ + -subj "/CN=127.0.0.1" -addext "subjectAltName=DNS:localhost,IP:127.0.0.1" \ + -keyout /etc/ssl/loopx/internal-key.pem -out /etc/ssl/loopx/internal-cert.pem 2>/dev/null +chown root:root /etc/ssl/loopx/internal-key.pem /etc/ssl/loopx/internal-cert.pem +chmod 0600 /etc/ssl/loopx/internal-key.pem +chmod 0644 /etc/ssl/loopx/internal-cert.pem +install -m 0644 /etc/ssl/loopx/internal-cert.pem /run/public-internal-ca.pem + +openssl req -x509 -newkey rsa:2048 -nodes -days 1 \ + -subj "/CN=gateway.loopx.internal" \ + -keyout /etc/ssl/loopx/key.pem -out /etc/ssl/loopx/cert.pem 2>/dev/null +chown root:root /etc/ssl/loopx/cert.pem +chmod 0644 /etc/ssl/loopx/cert.pem +chown root:caddy /etc/ssl/loopx/key.pem +chmod 0640 /etc/ssl/loopx/key.pem + +STORE_ID="postgresql:$(node -e 'console.log(require("crypto").randomBytes(16).toString("hex"))')" +BEARER_SECRET="cred-test-secret-$(node -e 'console.log(require("crypto").randomBytes(16).toString("hex"))')" +ADMIN_URL="postgresql://postgres:${PG_ADMIN_PW}@${PG_HOST}:5432/postgres" +APP_URL="postgresql://loopx_app:${PG_APP_PW}@${PG_HOST}:5432/postgres" +export ADMIN_URL APP_URL PG_APP_PW STORE_ID BEARER_SECRET + +node --no-warnings --experimental-strip-types --input-type=module - <<'SEED_EOF' +import {createHash} from "node:crypto"; +import {writeFileSync} from "node:fs"; +import {Pool} from "pg"; +import {coordinationTodoReadModel} from "./loopx/control_plane/coordination/coordination_projection.ts"; +import { + canonicalTodoDomainRecord, + TODO_DOMAIN_ITEM_SCHEMA, + TODO_DOMAIN_READ_RECORD_SCHEMA, +} from "./loopx/control_plane/coordination/coordination_state_contract.ts"; +import {setupPostgreSqlAuthoritySchemaAndRole} from "./loopx/control_plane/coordination/postgresql_authority_seed.ts"; +import {PostgreSqlAuthorityStore} from "./loopx/control_plane/coordination/postgresql_authority_store.ts"; +import {REMOTE_AUTHORITY_POLICY} from "./loopx/control_plane/coordination/remote_authority_policy.ts"; +import {materializeTodoRecordForSchema} from "./loopx/control_plane/coordination/todo_presentation.ts"; + +const makeDb = (pool) => ({connect: async () => {const c = await pool.connect(); return {query: (s, a) => c.query(s, a ? [...a] : undefined), release: (e) => c.release(e)};}}); +const adminPool = new Pool({connectionString: process.env.ADMIN_URL}); +try { + await setupPostgreSqlAuthoritySchemaAndRole({database: makeDb(adminPool), storeIdentity: process.env.STORE_ID, runtimeRole: "loopx_app"}); + await adminPool.query(`ALTER ROLE loopx_app LOGIN PASSWORD '${process.env.PG_APP_PW}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT`); + await adminPool.query("GRANT CONNECT ON DATABASE postgres TO loopx_app"); +} finally {await adminPool.end();} +const appPool = new Pool({connectionString: process.env.APP_URL}); +try { + const store = new PostgreSqlAuthorityStore(makeDb(appPool), {tenant_id: "tenant-cred", goal_id: "goal-cred", expected_store_identity: process.env.STORE_ID}); + const todo = materializeTodoRecordForSchema(canonicalTodoDomainRecord({ + schema_version: TODO_DOMAIN_ITEM_SCHEMA, todo_id: "todo_cred_verify", role: "agent", status: "open", done: false, archive_state: "active", + text: "Verify systemd LoadCredential non-root readback", priority: "P1", task_class: "advancement_task", required_write_scopes: ["todo_cred_verify/**"], + }, "cred verify todo domain"), TODO_DOMAIN_READ_RECORD_SCHEMA, "cred verify todo"); + const res = await store.commitAuthority({ + operation_id: "seed-systemd-cred-test", expected_provider_revision: null, events: [], receipts: [], + next_projection: {goal_id: "goal-cred", handoff_mode: "hard_lease", todos: [todo], leases: [], todo_read_model: coordinationTodoReadModel([todo], TODO_DOMAIN_READ_RECORD_SCHEMA)}, + }); + if (res.status !== "applied") throw new Error(`Seed failed: ${JSON.stringify(res)}`); +} finally {await appPool.end();} + +const policy = { + schema_version: REMOTE_AUTHORITY_POLICY, + scopes: [{ + tenant_id: "tenant-cred", + goal_id: "goal-cred", + store_identity: process.env.STORE_ID, + registered_agents: ["operator.local"], + }], + principals: [{ + principal_id: "principal-operator", + credential_sha256: createHash("sha256").update(process.env.BEARER_SECRET).digest("hex"), + grants: [{ + tenant_id: "tenant-cred", + goal_id: "goal-cred", + actor_id: "operator.local", + operations: ["read", "snapshot"], + }], + }], +}; +writeFileSync("/etc/loopx/remote-policy.json", JSON.stringify(policy)); +SEED_EOF + +chown root:root /etc/loopx/remote-policy.json +chmod 0600 /etc/loopx/remote-policy.json + +printf 'LOOPX_AUTHORITY_DATABASE_URL=%s\n' "$APP_URL" > /etc/loopx/authority.env +chown root:root /etc/loopx/authority.env +chmod 0600 /etc/loopx/authority.env + +install -d -o root -g root -m 0755 /etc/systemd/system /etc/caddy +install -d -o caddy -g caddy -m 0750 /var/log/caddy +install -o root -g root -m 0644 /opt/loopx/examples/coordination/volcengine/remote-authority-systemd.service \ + /etc/systemd/system/remote-authority-systemd.service +install -o root -g root -m 0644 /opt/loopx/examples/coordination/volcengine/gateway-caddy-tls.Caddyfile \ + /etc/caddy/Caddyfile + +UNIT_FILE="/etc/systemd/system/remote-authority-systemd.service" +EXEC_TEMPLATE="$(sed -n 's/^ExecStart=//p' "$UNIT_FILE")" +CRED_DIR="/run/credentials/remote-authority-systemd.service" +install -d -o 1000 -g 1000 -m 0500 "$CRED_DIR" +for spec in $(sed -n 's/^LoadCredential=//p' "$UNIT_FILE"); do + cid="${spec%%:*}" + csrc="${spec#*:}" + install -o 1000 -g 1000 -m 0400 "$csrc" "$CRED_DIR/$cid" +done + +# 1. Negative check: non-root reading raw 0600 root-owned key directly must fail EACCES (exit 1) +RAW_ERR_LOG="/run/raw-eacces.log" +set +e +LOOPX_AUTHORITY_DATABASE_URL="$APP_URL" setpriv --reuid=1000 --regid=1000 --clear-groups \ + /usr/bin/node --no-warnings --experimental-strip-types examples/coordination/remote-authority-service.ts \ + --policy "$CRED_DIR/remote-policy.json" --cert "$CRED_DIR/authority-cert.pem" \ + --key /etc/ssl/loopx/internal-key.pem --port 8443 --host 127.0.0.1 > /dev/null 2>"$RAW_ERR_LOG" +RAW_KEY_RC=$? +set -e +grep -q "EACCES" "$RAW_ERR_LOG" +[ "$RAW_KEY_RC" -eq 1 ] + +# 2. Caddy isolation: node cannot read Caddy key/raw policy/db env; caddy reads only cert.pem & key.pem +! setpriv --reuid=1000 --regid=1000 --clear-groups head -c 1 /etc/ssl/loopx/key.pem 2>/dev/null +! setpriv --reuid=1000 --regid=1000 --clear-groups head -c 1 /etc/ssl/loopx/internal-key.pem 2>/dev/null +! setpriv --reuid=1000 --regid=1000 --clear-groups head -c 1 /etc/loopx/remote-policy.json 2>/dev/null +! setpriv --reuid=1000 --regid=1000 --clear-groups head -c 1 /etc/loopx/authority.env 2>/dev/null + +CADDY_UID="$(id -u caddy)" +CADDY_GID="$(id -g caddy)" +setpriv --reuid="$CADDY_UID" --regid="$CADDY_GID" --clear-groups head -c 1 /etc/ssl/loopx/cert.pem >/dev/null +setpriv --reuid="$CADDY_UID" --regid="$CADDY_GID" --clear-groups head -c 1 /etc/ssl/loopx/key.pem >/dev/null +! setpriv --reuid="$CADDY_UID" --regid="$CADDY_GID" --clear-groups head -c 1 /etc/ssl/loopx/internal-key.pem 2>/dev/null +! setpriv --reuid="$CADDY_UID" --regid="$CADDY_GID" --clear-groups head -c 1 /etc/loopx/remote-policy.json 2>/dev/null +! setpriv --reuid="$CADDY_UID" --regid="$CADDY_GID" --clear-groups head -c 1 /etc/loopx/authority.env 2>/dev/null + +# 3. Positive check: non-root ExecStart using %d/ credentials + separate EnvironmentFile listens and serves snapshot +EXEC_CMD="${EXEC_TEMPLATE//%d/$CRED_DIR}" +SVC_OUT="/run/svc-stdout.log" +set -a +. /etc/loopx/authority.env +set +a +CREDENTIALS_DIRECTORY="$CRED_DIR" setpriv --reuid=1000 --regid=1000 --clear-groups \ + sh -c "exec $EXEC_CMD" >"$SVC_OUT" 2>&1 & +SVC_PID=$! +unset LOOPX_AUTHORITY_DATABASE_URL + +LISTENING_JSON="" +for _ in $(seq 1 50); do + if grep -q '"status":"listening"' "$SVC_OUT" 2>/dev/null; then + LISTENING_JSON="$(grep '"status":"listening"' "$SVC_OUT" | head -n 1)" + break + fi + if ! kill -0 "$SVC_PID" 2>/dev/null; then + cat "$SVC_OUT" >&2 + exit 1 + fi + sleep 0.2 +done +[ -n "$LISTENING_JSON" ] +SVC_UID="$(ps -o uid= -p "$SVC_PID" | tr -d ' ')" +[ "$SVC_UID" = "1000" ] + +SNAPSHOT_JSON="$(printf '{"schema_version":"loopx_remote_authority_request_v0","tenant_id":"tenant-cred","goal_id":"goal-cred","actor_id":"operator.local","store_identity":"%s","operation":"snapshot"}' "$STORE_ID" | \ + LOOPX_AUTHORITY_CREDENTIAL="$BEARER_SECRET" setpriv --reuid=1000 --regid=1000 --clear-groups \ + /usr/bin/node --no-warnings --experimental-strip-types examples/coordination/remote-authority-client.ts \ + --endpoint https://127.0.0.1:8443 --ca /run/public-internal-ca.pem)" + +kill -TERM "$SVC_PID" +wait "$SVC_PID" || true + +node -e ' +const listening = JSON.parse(process.argv[1]); +const snapshot = JSON.parse(process.argv[2]); +console.log(JSON.stringify({ + raw_key_eacces_exit: Number(process.argv[3]), + service_uid: Number(process.argv[4]), + listening, + snapshot_status: snapshot.status, + goal_id: snapshot.goal_id, + store_identity: snapshot.store_identity, + todo_ids: (snapshot.todos || []).map(t => t.todo_id), + caddy_isolated: true, +})); +' "$LISTENING_JSON" "$SNAPSHOT_JSON" "$RAW_KEY_RC" "$SVC_UID" +""" + + res = _run_node_container_with_opt_loopx( + docker_env, net_name, repo_root, container_script, + {"PG_HOST": pg_name, "PG_ADMIN_PW": pg_admin_pw, "PG_APP_PW": pg_app_pw}, + ) + assert res.returncode == 0, f"Container verification failed (rc={res.returncode}):\nSTDOUT:\n{res.stdout}\nSTDERR:\n{res.stderr}" + report = json.loads(res.stdout.strip().splitlines()[-1]) + assert report["raw_key_eacces_exit"] == 1 + assert report["service_uid"] == 1000 + assert report["listening"] == {"status": "listening", "host": "127.0.0.1", "port": 8443} + assert report["snapshot_status"] == "snapshot" + assert report["goal_id"] == "goal-cred" + assert report["todo_ids"] == ["todo_cred_verify"] + assert report["caddy_isolated"] is True + finally: + subprocess.run(["docker", "rm", "-f", pg_name], capture_output=True, text=True, env=docker_env) + subprocess.run(["docker", "network", "rm", net_name], capture_output=True, text=True, env=docker_env) + + +def test_systemd_load_credential_nonroot_linux_isolation_and_snapshot() -> None: + """Verify non-root EACCES on raw 0600 root keys vs LoadCredential readback in Linux.""" + _assert_nonroot_load_credential_snapshot(REPO_ROOT) + + +def test_detached_worktree_staging_ignores_dangling_unrelated_link(tmp_path: Path) -> None: + """Verify detached worktree staging tolerates dangling/looping unrelated links and fails cleanly on missing pg deps.""" + nm_root = _resolve_host_node_modules_root(REPO_ROOT) + assert nm_root is not None + wt = tmp_path / "detached-wt" + (wt / "loopx").mkdir(parents=True) + (wt / "examples").mkdir(parents=True) + (wt / "node_modules").mkdir() + (wt / "package.json").symlink_to(REPO_ROOT / "package.json") + (wt / "loopx" / "control_plane").symlink_to(REPO_ROOT / "loopx" / "control_plane") + (wt / "examples" / "coordination").symlink_to(REPO_ROOT / "examples" / "coordination") + for entry in (nm_root / "node_modules").iterdir(): + if not entry.name.startswith("."): + (wt / "node_modules" / entry.name).symlink_to(entry.resolve()) + (wt / "node_modules" / f"unused-local-link-{uuid.uuid4().hex[:6]}").symlink_to(tmp_path / "deleted-target") + (wt / "node_modules" / ".node_modules-loop").symlink_to(wt / "node_modules") + # Missing required transitive dependency must fail with explicit package name. + broken_nm = tmp_path / "broken_nm" / "node_modules" + broken_nm.mkdir(parents=True) + for entry in (nm_root / "node_modules").iterdir(): + if not entry.name.startswith(".") and entry.name != "postgres-array": + (broken_nm / entry.name).symlink_to(entry.resolve()) + with pytest.raises(AssertionError, match="postgres-array"): + _collect_runtime_node_packages(broken_nm, "pg") + _assert_nonroot_load_credential_snapshot(wt) diff --git a/tsconfig.control-plane.json b/tsconfig.control-plane.json index 096f2a8094..d60f4f9cf7 100644 --- a/tsconfig.control-plane.json +++ b/tsconfig.control-plane.json @@ -33,6 +33,8 @@ "examples/coordination/sqlite-authority-migration.ts", "examples/coordination/remote-authority-service.ts", "examples/coordination/remote-authority-client.ts", + "examples/coordination/colima-pg16-e2e-rehearsal.ts", + "tests/control_plane_ts/coordination_colima_rehearsal.test.ts", "tests/control_plane_ts/remote_authority.test.ts", "tests/control_plane_ts/remote_authority.integration.test.ts", "tests/control_plane_ts/remote_authority_fixture.ts",