diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 589afff5b..82de08644 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,10 +20,25 @@ on: workflow_dispatch: inputs: live_acceptance: - description: Paid official-provider acceptance only (skips ordinary platform checks) + description: Optional acceptance or secretless preflight (skips platform checks) type: choice - options: ['off', style, style-diagnostic, search] + options: ['off', style, style-diagnostic, search, intent-style-comparison, intent-style-preflight] default: 'off' + intent_recipient_certificate: + description: Public PEM recipient certificate for encrypted intent evidence (never a private key) + type: string + required: false + default: '' + intent_expected_source_sha: + description: Reviewed 40-character source/workflow SHA for intent preflight or comparison + type: string + required: false + default: '' + intent_recipient_sha256: + description: Locally confirmed recipient certificate DER SHA256 for this single intent dispatch + type: string + required: false + default: '' platform: description: Platforms to check (macos runs only macOS gates) type: choice @@ -1282,9 +1297,53 @@ jobs: test "$MSRV_RESULT" = success fi + intent-secretless-preflight: + name: Optional secretless intent preflight + if: >- + github.event_name == 'workflow_dispatch' && + inputs.live_acceptance == 'intent-style-preflight' && + github.repository == 'Open-Less/openless' && + contains(fromJSON('["refs/heads/main","refs/heads/beta"]'), github.ref) + runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + contents: read + defaults: + run: + working-directory: openless-all/app + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Verify reviewed source without provider credentials + env: + INTENT_EXPECTED_SOURCE_SHA: ${{ inputs.intent_expected_source_sha }} + INTENT_WORKFLOW_SHA: ${{ github.workflow_sha }} + run: python3 scripts/intent-style-comparison-ci.py source-preflight + - uses: dtolnay/rust-toolchain@stable + - name: Compile once and verify only dummy and local mock paths + run: | + set -euo pipefail + umask 077 + scratch=$(mktemp -d "$RUNNER_TEMP/openless-intent-preflight.XXXXXX") + trap 'rm -rf "$scratch"' EXIT + export TMPDIR="$scratch/tmp" + export CARGO_TARGET_DIR="$scratch/target" + mkdir -p "$TMPDIR" + bash scripts/intent-style-gates.sh python + binary_assignment=$(bash scripts/intent-style-gates.sh build "$scratch/manifest.jsonl") + [[ "$binary_assignment" == binary=* ]] + binary=${binary_assignment#binary=} + bash scripts/intent-style-gates.sh verify "$binary" + live-acceptance: name: Optional official-provider live acceptance - if: github.event_name == 'workflow_dispatch' && inputs.live_acceptance != 'off' + if: >- + github.event_name == 'workflow_dispatch' && + inputs.live_acceptance != 'off' && + inputs.live_acceptance != 'intent-style-preflight' && + github.repository == 'Open-Less/openless' && + contains(fromJSON('["refs/heads/main","refs/heads/beta"]'), github.ref) runs-on: ubuntu-latest timeout-minutes: 20 permissions: @@ -1294,11 +1353,40 @@ jobs: working-directory: openless-all/app steps: - uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Validate intent evidence recipient before any paid request + if: inputs.live_acceptance == 'intent-style-comparison' + env: + INTENT_RECIPIENT_CERTIFICATE: ${{ inputs.intent_recipient_certificate }} + INTENT_RECIPIENT_SHA256: ${{ inputs.intent_recipient_sha256 }} + INTENT_EXPECTED_SOURCE_SHA: ${{ inputs.intent_expected_source_sha }} + INTENT_WORKFLOW_SHA: ${{ github.workflow_sha }} + INTENT_TRIGGERING_ACTOR: ${{ github.triggering_actor }} + run: python3 scripts/intent-style-comparison-ci.py preflight - uses: dtolnay/rust-toolchain@stable - name: Build acceptance without credentials - run: cargo test --locked -p openless-core --lib --no-run + id: live-build + env: + CARGO_TARGET_DIR: ${{ runner.temp }}/openless-live-target + run: | + set -euo pipefail + umask 077 + build_manifest=$(mktemp "$RUNNER_TEMP/openless-live-build.XXXXXX") + trap 'rm -f "$build_manifest"' EXIT + bash scripts/intent-style-gates.sh build "$build_manifest" >> "$GITHUB_OUTPUT" + - name: Verify intent mock transport gates without provider credentials + if: inputs.live_acceptance == 'intent-style-comparison' + env: + INTENT_TEST_BINARY: ${{ steps.live-build.outputs.binary }} + run: | + set -euo pipefail + bash scripts/intent-style-gates.sh python + bash scripts/intent-style-gates.sh verify "$INTENT_TEST_BINARY" - name: Run explicitly selected bounded acceptance + if: inputs.live_acceptance != 'intent-style-comparison' env: + CARGO_TARGET_DIR: ${{ runner.temp }}/openless-live-target DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }} LIVE_ACCEPTANCE: ${{ inputs.live_acceptance }} run: | @@ -1311,10 +1399,42 @@ jobs: esac cargo test --locked -p openless-core --lib "$target" -- --list --ignored | grep -q "$target: test" cargo test --locked -p openless-core --lib "$target" -- --ignored --nocapture --test-threads=1 | tee live-acceptance.log + - name: Compare intent 1.3.0 and 1.4.0 with existing official credentials + if: inputs.live_acceptance == 'intent-style-comparison' + env: + DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }} + INTENT_TEST_BINARY: ${{ steps.live-build.outputs.binary }} + INTENT_RECIPIENT_CERTIFICATE: ${{ inputs.intent_recipient_certificate }} + INTENT_RECIPIENT_SHA256: ${{ inputs.intent_recipient_sha256 }} + INTENT_EXPECTED_SOURCE_SHA: ${{ inputs.intent_expected_source_sha }} + INTENT_WORKFLOW_SHA: ${{ github.workflow_sha }} + INTENT_TRIGGERING_ACTOR: ${{ github.triggering_actor }} + run: | + set -euo pipefail + umask 077 + private_dir=$(mktemp -d "$RUNNER_TEMP/openless-intent.XXXXXX") + chmod 700 "$private_dir" + trap 'rm -rf "$private_dir"' EXIT + python3 scripts/intent-style-comparison-ci.py run \ + "$INTENT_TEST_BINARY" "$private_dir" "$RUNNER_TEMP/openless-intent-evidence" - name: Preserve public output evidence - if: always() + if: always() && inputs.live_acceptance != 'intent-style-comparison' uses: actions/upload-artifact@v4 with: name: official-provider-live-acceptance path: openless-all/app/live-acceptance.log if-no-files-found: ignore + - name: Preserve encrypted intent review and safe execution status + if: always() && inputs.live_acceptance == 'intent-style-comparison' + uses: actions/upload-artifact@v4 + with: + name: intent-style-comparison-evidence + path: | + ${{ runner.temp }}/openless-intent-evidence/status.json + ${{ runner.temp }}/openless-intent-evidence/comparison.cms + if-no-files-found: ignore + retention-days: 7 + - name: Clean dedicated live acceptance artifacts + if: always() + run: | + rm -rf "$RUNNER_TEMP/openless-live-target" "$RUNNER_TEMP/openless-intent-evidence" diff --git a/docs/intent-style-evaluation.md b/docs/intent-style-evaluation.md index ae3c36a0c..693bca05f 100644 --- a/docs/intent-style-evaluation.md +++ b/docs/intent-style-evaluation.md @@ -18,45 +18,19 @@ node scripts/intent-style-comparison.mjs /tmp/intent-comparison.json /tmp/intent 结果对象使用 `{"text":"最终正文","sourceText":"翻译前源文或 null","elapsedMs":123}`。失败时使用 `{"errorCode":"Provider"}`。离线渲染器不发请求、不读取凭据。 -## 获准后使用现有后处理渠道对照 - -先获得真实调用许可,说明请求数:16 条 × 旧新版各一次 = 32 个主要请求;两个翻译样例若两版都缺少标记,现有纯翻译兜底最多再发 4 次,合计最多 36 次。无自动重试、无多渠道或多模型扫描,遇到首个渠道错误即停止并保留部分记录。 - -提供的是被 `#[ignore]` 排除的测试 `intent_style_tests::intent_live_configured_channel_comparison`。它复用 `SharedCloudTextPolisher`、生产请求组装、协议、翻译解析与兜底路径,不自行创建另一个模型客户端。仅测试构造的内存凭据被使用,不修改应用设置、渠道、风格选择或请求参数。 - -从用户已经配置的后处理渠道复制渠道 ID、协议类型、模型、思考开关、endpoint、API Key 和渠道级选项到仓库之外的私有 JSON 文件。不要把密钥写到命令行、日志、报告或 Git。以下仅描述字段形状,所有字段值均应来自同一现有渠道: - -```json -{ - "channelId": "existing-channel-id", - "providerType": "openai-compatible", - "model": "existing-model-id", - "thinkingEnabled": false, - "baseline": "1.0.0", - "credentials": { - "ark.endpoint": "https://your-configured-endpoint.example/v1", - "ark.api_key": "your-existing-key", - "ark.request_format": "chat_completions" - } -} -``` - -`thinkingEnabled` 必须与现有配置一致,示例中的 `false` 不代表要求修改用户设置。`providerType` 和 `ark.request_format` 也应照抄,兼容渠道支持 `chat_completions`、`responses`、`messages`,也支持已有 Gemini API 渠道。需要时同时复制 `ark.temperature`、`ark.extra_headers`、`ark.messages_thinking`、`ark.max_tokens`、`ark.thinking_budget`、`ark.service_tier`;凭据值均为字符串,与 Core 存储一致。OAuth / ChatGPT Plan 渠道使用下方应用操作步骤,不由该测试隐式选取登录身份。 +## 本任务的真实对照范围 -旧基线默认由配置显式指定为反馈中的 `1.0.0`;也可填 `1.3.0` 对比当前 beta 实际运行版本。两者均使用不可变的发布快照。新版本为 `1.4.0`。为保持可比,两版使用同一当前组装器及全局口述修正规则;这不是复刻旧应用二进制。每条按旧版、新版顺序串行执行,未注入热词、应用或历史。选区专用指令放在独立的 `selection_instruction` 段,原文始终作为数据处理。 +唯一真实入口为默认 ignored 的 `intent_style_tests::intent_live_configured_channel_comparison`, +只允许下方已授权官方 DeepSeek 配置、1.3.0 与 1.4.0,不接受另一个模型或本机渠道导出。 +生产组装、选区封套、翻译解析与兜底保持共用;测试独立作用域在共同实际发送边界计数, +拒绝第 37 次 send,首个错误停止,无生产重试。隔离客户端禁重定向、协议重试与连接池 +复用;正常产品和旧 style/diagnostic/search 的路径不变。 -获得许可、填好私有配置后执行(以下命令会真实调用渠道): - -```sh -chmod 600 /private/path/intent-channel.json -OPENLESS_INTENT_COMPARISON_APPROVED=yes \ -OPENLESS_INTENT_COMPARISON_CONFIG=/private/path/intent-channel.json \ -OPENLESS_INTENT_COMPARISON_OUTPUT=/tmp/intent-live-results.json \ -cargo test -p openless-core -j 1 intent_style_tests::intent_live_configured_channel_comparison -- --ignored --exact --test-threads=1 -node scripts/intent-style-comparison.mjs /tmp/intent-live-results.json /tmp/intent-live-results.md -``` - -批准标志只是防误触门槛,不能代替调用前的用户许可。输出包含渠道 ID、请求模型、思考开关、基线版本、候选版本、原始输入、期望要点、源文、最终正文和耗时;不保存配置中的凭据。耗时为整个处理路径耗时,可能包括翻译兜底,并非单次首 token 延迟。该工具不将调用成功视作语义通过,也不声称服务端返回的实际模型与请求名称一致。 +本项目禁止本机 Cargo/编译。不要手工复制用户密钥或直接运行 ignored 测试;仅由协调者 +在 B1–B3 重审及目标云端 mock 门禁通过后,使用下方锁定来源与收件人的唯一手动模式。 +32 主请求加最多 4 翻译兜底是上限;安全证据另给实际 attemptedSends/fallbackSends。 +只有正常结束并写出 final 计数才可确证;超时、信号中止或不完整报告均记 unknown, +不能用 32/36 常量当实际请求数,也不能无证据重跑。 ## 在应用内手工对照 @@ -66,6 +40,162 @@ OAuth 渠道或不希望复制凭据时,在风格设置建立两个临时自 逐条检查信息是否遗漏、撤销是否生效、是否重复归组、层级与编号是否合理、专名数字是否保留、是否新增要求或代答。给每条记录通过 / 不通过和具体偏差;失败后可以修改提示词,但不能覆盖已有对照证据。最终效果由用户判断。渠道是否返回缓存读取和推理用量,仍须通过应用的用量账本另行检查;该并排记录不代替缓存或计费测量。 +## 无 provider secret 的云端预验证 + +先使用非默认手动模式 `intent-style-preflight` 取得通道动态证据,**不要用付费模式来做 +预验**。独立 job `intent-secretless-preflight` 只有 contents:read,checkout 不保留凭据, +没有 provider secret 映射或 environment。它仅允许官方仓库 main/beta,复用同一来源 +校验:40 位 expected SHA、事件 SHA、workflow SHA、checkout HEAD 和官方 ci.yml ref +必须一致;无需 API key、收件人证书或指纹,也不调用 wrapper 的 `run`。 + +协调者先把补丁纳入经过审查的完整集成版本,在该 checkout 的 `openless-all/app/` +记录确切 SHA。以下仅为协调者后续的云端命令,本任务没有执行: + +```sh +expected_source_sha=$(git rev-parse HEAD) +test "$(gh api repos/Open-Less/openless/git/ref/heads/beta --jq .object.sha)" = "$expected_source_sha" +gh workflow run ci.yml --repo Open-Less/openless --ref beta \ + -f live_acceptance=intent-style-preflight \ + -f "intent_expected_source_sha=$expected_source_sha" +``` + +这个模式与 paid live-acceptance 在条件上互斥,不会在预验通过后自动付款。 +changes/平台 gate 不启动,默认 off 和旧 style/diagnostic/search 不变。 +独占 runner.temp 目录内依次执行: + +1. 22 项 Python/OpenSSL dummy(模型进程/git context 均 mock,OpenSSL 使用临时 dummy)。 +2. **一次** `cargo test --locked -p openless-core --lib -j 1 --no-run --message-format=json`; + 既有 select-binary 从 manifest 取得唯一 Core 测试二进制。 +3. 严格逐名枚举 5 项非 ignored 测试,再执行其精确共同前缀;必须实际 5 passed、 + 0 failed、0 ignored,不能接受 0 tests。 +4. 对唯一 live 函数仅执行 `--ignored --exact --list`,要求恰一个精确匹配,绝不执行。 + +其中前四项 Rust 目标验证真实本地传输/循环,第五项只检查旧限额常量和当前 scope 状态。 +编译/枚举/mock 的无 provider 步骤共用 `scripts/intent-style-gates.sh`,供预验与付费路径 +各自的前置检查使用;脚本没有 live 执行分支。日志只保留已验证的测试计数、来源 SHA +及固定失败阶段,临时 manifest、target、TMPDIR、dummy 文件和原始命令输出均清理。 + +保留这次确切 run ID、实际执行的 job、验证过的 SHA 和安全计数;skipped 不是通过。 +预验成功只证明这个 SHA 的通道测试,不证明模型效果,也不会生成语义对照。 +后续如有集成改动,必须在新的最终 SHA 重新取得无密钥证据,不能移用旧 SHA 的结果。 +只有门禁和复审完成后,才按下面**另外一次明确的付费模式 dispatch**安排既有授权的 +唯一真实对照;预验不会调用它,付费流程的身份/attempt/SHA/证书门禁保持原样。 + +## 使用既有 Actions secret 的加密语义对照 + +现有 `Optional official-provider live acceptance` 的非默认选项 +`intent-style-comparison` 只接受 `Open-Less/openless` 仓库的 `main` / `beta` +分支手动运行。fork、PR、tag 和其他分支不进入带 secret 的 job;默认仍为 `off`。 +新模式还要求原 actor 为 `appergb`(稳定 ID `192432815`)、triggering actor +同为 `appergb`、run attempt 严格为 1。身份来自 GitHub 上下文,不能通过 input 覆盖。 +官方 repo/ref 外的 skipped job 不等于验收通过;合法 ref 内的错误身份/SHA/指纹会显式失败。 +不能运行只留下状态的旧入口:调用前必须有已在协调者本机验证的一次性公有收件人证书, +云端只接收该证书,私钥留在协调者本机。新增机制不增加模型请求或 App 构建。 + +以下是供协调者执行的步骤,本改动的开发/离线测试没有执行真实请求或生成正式收件人。 +协调者先将本改动接入经审查的集成版本,锁定可信分支 SHA;使用已经安装且支持 +CMS AuthEnvelopedData、AES-256-GCM 和 RSA-OAEP 的 OpenSSL,不在本任务安装组件。 +本机若只有不支持该格式的工具,应停止并采用受控 Dev 真机路径。 + +1. 在仓库之外创建私有目录、一次性 RSA 3072 收件人;下面的私钥不加口令,仅靠 0700 + 目录与 0600 权限保管,以便本地解密 helper 无交互运行。它永远不提交、不上传: + + ```sh + umask 077 + review_dir=$(mktemp -d "${TMPDIR:-/tmp}/openless-intent-review.XXXXXX") + chmod 700 "$review_dir" + openssl req -x509 -newkey rsa:3072 -sha256 -nodes -days 2 \ + -subj /CN=OpenLess-intent-review \ + -keyout "$review_dir/recipient.key" -out "$review_dir/recipient.crt" + chmod 600 "$review_dir/recipient.key" "$review_dir/recipient.crt" + recipient_sha256=$(python3 scripts/intent-style-comparison-ci.py check-recipient \ + "$review_dir/recipient.crt" "$review_dir/recipient.key") + recipient_sha256=${recipient_sha256#recipientSha256=} + ``` + + 在 `openless-all/app/` 运行 helper;固定无敏感内容的本地 roundtrip 成功时仅显示公有 + `recipientSha256`。保留这个指纹、私钥与目录路径到审核结束,不在流水线生成私钥。 + 本地验证失败时不要继续,也不要把 private key 粘贴为 workflow input。 + +2. 在已完成重审和云端 mock 的完整集成 checkout 记录审查 SHA;不能把未验的 worker + 候选当作可调用版本。下面 `git rev-parse HEAD` 必须是这一确切审查值。 + 核对可信 ref 后,只执行一次下面的付费手动调用。 + `-F` 的文件必须是 `.crt` 公有证书,绝不能是 `.key`: + + ```sh + expected_source_sha=$(git rev-parse HEAD) + test "$(gh api repos/Open-Less/openless/git/ref/heads/beta --jq .object.sha)" = "$expected_source_sha" + gh workflow run ci.yml --repo Open-Less/openless --ref beta \ + -f live_acceptance=intent-style-comparison \ + -f "intent_expected_source_sha=$expected_source_sha" \ + -f "intent_recipient_sha256=$recipient_sha256" \ + -F "intent_recipient_certificate=@$review_dir/recipient.crt" + ``` + + 沿用调用前授权,不选择第二个模型、不额外重跑。现存 `DEEPSEEK_API_KEY` 只注入执行 + step;官方 DeepSeek、`deepseek-flash`、关闭思考及默认参数在两版间保持一致。 + 旧实际内置 **1.3.0** 对照 **1.4.0**,原 16 条夹具(12 听写/2 翻译/2 选区) + 共 32 主请求,加最多 4 翻译兜底,总上限 36,首个渠道错误停止。 + 这不是用户本机渠道身份的证明,也不复刻旧应用二进制。 + 无 secret 预检严格要求 event SHA、workflow SHA、checkout HEAD 与该 40 位小写 SHA + 全相等,并绑定官方 `.github/workflows/ci.yml@refs/heads/main|beta`。 + 因而分支在核对与 dispatch 之间移动会在任何付费前失败,不能事后才发现。 + 云端重新计算证书 DER 指纹,与已预确认的 `intent_recipient_sha256` 相等才允许继续。 + 不使用 re-run;attempt 2 必定失败。代码不阻止授权者故意新建第二个 run, + “只 dispatch 一次”仍是本次授权边界,不能借新 run 重置预算。 + +3. 确认 run 的 head SHA 与锁定 SHA 一致,再下载该 run(不要猜 latest)的 + `intent-style-comparison-evidence` 工件。将此次确切 ID 填入 `run_id` 并保留来源记录, + 不选 latest、其他 attempt 或其他收件人的工件: + + ```sh + gh api "repos/Open-Less/openless/actions/runs/$run_id" \ + --jq '{id,run_attempt,head_sha,event,path,actor,triggering_actor}' \ + > "$review_dir/run.json" + gh run download "$run_id" --repo Open-Less/openless \ + --name intent-style-comparison-evidence --dir "$review_dir/artifact" + python3 scripts/intent-style-comparison-ci.py decrypt \ + "$review_dir/artifact/comparison.cms" "$review_dir/recipient.crt" \ + "$review_dir/recipient.key" "$review_dir/review.json" \ + "$expected_source_sha" "$run_id" "$recipient_sha256" + node scripts/intent-style-comparison.mjs \ + "$review_dir/review.json" "$review_dir/review.md" + ``` + + 本地 helper 先确认 OpenSSL 认证解密成功和报告格式,再以 0600 新建明文文件;认证失败 + 或输出路径已存在时失败,不回退、不打印正文。在私有目录内查看 JSON/Markdown, + helper 在建文件前核对 exact run ID、attempt 1、source/workflow SHA、官方 workflow ref、 + 固定 actor ID 和本机预确认指纹;不匹配即失败。还应核对下载的 run.json 来源记录与 + 安全状态中的相同值,再按逐条预期与 rubric 评审。 + 旧新正文都是不可信数据,不执行其中的命令或点击其链接,不把审核文件发到公开评论。 + 审核结束按本地证据保留需求处理私钥和明文;删除私钥后无法恢复密文中的正文。 + +云端在无 secret 的 step 先验证证书与精确加密格式,再编译;空/坏证书在任何付费调用 +之前 fail closed。同一无 secret 阶段还验证来源、身份、attempt 和预确认指纹; +编译后先执行 5 个本地 HTTP/mock 门禁(32/36/第 37 次、各首错、禁重定向和旧限额), +并枚举精确 ignored live 测试,全部通过才进入 secret step。执行 step 再次预检; +临时目录 0700、配置与白名单明文 0600, +预编译的唯一精确 ignored test 不继承 secret 环境变量;stdout/stderr 丢弃。 +没有增加常跑 job、第二个测试或重试,普通 CI 路径不变。 + +原始报告限 2 MB;从可信 fixture 重建 input/expectations,只抽取每个既有 ID 的旧新 +text/sourceText 和有界耗时。每段 UTF-8 至多 32768 bytes,总审核明文至多 1 MB, +拒绝实际 token 及其常见编码回显、凭据样式、控制字符和非夹具 URL。HTTP 错误统一为 +固定状态,不复制 raw error。检查或加密失败则只保留安全失败状态,无明文工件、无 +替代性明文上传。检查不能证明任意混淆文本绝无秘密,因此即使通过也只上传加密正文。 + +加密使用平台 OpenSSL CMS AuthEnvelopedData(AES-256-GCM、RSA-OAEP/SHA-256), +不手写密码算法、不回退 CBC;先在私有目录完成加密及结构核验,再移出密文。 +工件仅有 `comparison.cms` 和安全 `status.json`,保留 7 天;无配置、私钥、原始结果或 +Cargo/HTTP 日志。finally/trap 清理私有文件,always 清理专用 target/工件暂存目录; +强制 SIGKILL 的最终清理依赖临时 hosted runner 生命周期。 + +`status=completed` 或成功解密均不表示语义通过。缺密文时不要再次消耗预算,先核对 +安全失败状态及已发请求;部分渠道失败仍可能留下经过同样检查和加密的部分对照。 +`transport.state=final` 的 attemptedSends/fallbackSends 才是本轮实际发送尝试计数; +`unknown` 表示无法确证,禁止把固定上限当作可重跑额度。 +密文完整性不是发送者签名,必须从锁定 SHA 的可信 GitHub run 取得并核对来源。 + ## 版本与迁移设计 运行版此前已是 1.3.0,所以本次递增为 1.4.0,而非回退至 1.1.0。主 JSON 的两个作者槽和共享 Markdown 内容一致,运行时仅追加一次全局口述撤回规则。稳定正文不包含热词占位符,组装器在正文之后追加可变热词和上下文,不向存储回写动态数据。 diff --git a/openless-all/app/crates/openless-core/src/cloud_providers.rs b/openless-all/app/crates/openless-core/src/cloud_providers.rs index 91b8dcbed..59b907af8 100644 --- a/openless-all/app/crates/openless-core/src/cloud_providers.rs +++ b/openless-all/app/crates/openless-core/src/cloud_providers.rs @@ -1549,6 +1549,8 @@ async fn run_cloud_polish( "[cloud-provider] polish+translate response missing markers; using plain translation" ); // No target section was published, so fallback starts at offset zero. + #[cfg(test)] + let _intent_fallback = crate::polish::live_acceptance::intent_fallback(); let stream = PolishStreamPublisher::new( Arc::clone(&partials), Arc::clone(&cancellation), diff --git a/openless-all/app/crates/openless-core/src/intent_style_tests.rs b/openless-all/app/crates/openless-core/src/intent_style_tests.rs index 23ac062be..3ad5045c4 100644 --- a/openless-all/app/crates/openless-core/src/intent_style_tests.rs +++ b/openless-all/app/crates/openless-core/src/intent_style_tests.rs @@ -245,28 +245,26 @@ fn intent_stable_prefix_survives_hotwords_context_translation_and_custom_slots() ); } -/// No endpoint or key is selected implicitly; copy settings from the user's existing -/// channel into a private config. Normal test runs never enter this function. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ComparisonConfig { + channel_id: String, + provider_type: String, + model: String, + thinking_enabled: bool, + baseline: String, + credentials: std::collections::BTreeMap, +} + +/// Normal test runs never enter the approved official-channel comparison. #[tokio::test] #[ignore = "real configured-channel requests; approval and private config required"] async fn intent_live_configured_channel_comparison() { - use crate::credentials::{CredentialKey, CredentialNamespace, CredentialStore}; - use crate::ports::TextPolisher; - #[derive(Deserialize)] - #[serde(rename_all = "camelCase", deny_unknown_fields)] - struct Config { - channel_id: String, - provider_type: String, - model: String, - thinking_enabled: bool, - baseline: String, - credentials: std::collections::BTreeMap, - } assert_eq!( std::env::var("OPENLESS_INTENT_COMPARISON_APPROVED").as_deref(), Ok("yes") ); - let config: Config = serde_json::from_slice( + let config: ComparisonConfig = serde_json::from_slice( &std::fs::read( std::env::var("OPENLESS_INTENT_COMPARISON_CONFIG").expect("private config path"), ) @@ -294,11 +292,25 @@ async fn intent_live_configured_channel_comparison() { .is_some_and(|endpoint| !endpoint.trim().is_empty()), "copy the existing channel endpoint explicitly; no implicit provider default" ); - let old = match config.baseline.as_str() { - "1.0.0" => original_intent_pack(), - "1.3.0" => released_intent_v1_3_pack(), - _ => panic!("baseline must be 1.0.0 or 1.3.0"), - }; + assert_eq!(config.provider_type, "deepseek"); + assert_eq!(config.model, crate::deepseek_suite::MODEL); + assert!(!config.thinking_enabled); + assert_eq!(config.baseline, "1.3.0"); + assert_eq!( + config.credentials.get(crate::credentials::LLM_ENDPOINT_ACCOUNT).map(String::as_str), + Some(crate::deepseek_suite::ENDPOINT), + ); + let report = crate::polish::live_acceptance::intent_scope( + run_intent_comparison(&config, &output_path), + ).await; + assert_eq!(report["executionStatus"], "completed", "comparison stopped; safe report retained"); +} + +// The same loop is exercised against a local HTTP fixture by the non-live tests. +async fn run_intent_comparison(config: &ComparisonConfig, output_path: &str) -> Value { + use crate::credentials::{CredentialKey, CredentialNamespace, CredentialStore}; + use crate::ports::TextPolisher; + let old = released_intent_v1_3_pack(); let new = builtin_intent_pack(); let evaluation = evaluation(); let store = std::sync::Arc::new(crate::InMemoryCredentialStore::default()); @@ -327,6 +339,8 @@ async fn intent_live_configured_channel_comparison() { "schemaVersion": 1, "channelId": config.channel_id, "providerType": config.provider_type, "requestedModel": config.model, "thinkingEnabled": config.thinking_enabled, "baselineVersion": old.version, "candidateVersion": new.version, + "executionStatus": "running", + "transport": {"state": "running"}, "provenance": evaluation.provenance, "semanticReview": "pending human review", "cases": evaluation.cases.iter().map(|case| json!({ "id": case.id, "input": case.input, "operation": case.operation, @@ -339,12 +353,12 @@ async fn intent_live_configured_channel_comparison() { let mut file = std::fs::OpenOptions::new() .create_new(true) .write(true) - .open(&output_path) + .open(output_path) .unwrap(); file.write_all(&serde_json::to_vec_pretty(&report).unwrap()) .unwrap(); drop(file); - for (index, case) in evaluation.cases.iter().enumerate() { + 'cases: for (index, case) in evaluation.cases.iter().enumerate() { for (side, pack) in [("old", &old), ("new", &new)] { let mut context = case_context(pack, case); context.llm = crate::ProviderInvocation::for_provider(&config.provider_type); @@ -367,12 +381,223 @@ async fn intent_live_configured_channel_comparison() { }), Err(error) => json!({"errorCode": format!("{:?}", error.code)}), }; - std::fs::write(&output_path, serde_json::to_vec_pretty(&report).unwrap()).unwrap(); - assert!( - result.is_ok(), - "{} {side}: channel failed; partial report retained", - case.id + let mut counts = crate::polish::live_acceptance::intent_counts(); + counts["state"] = json!("running"); + report["transport"] = counts; + std::fs::write(output_path, serde_json::to_vec_pretty(&report).unwrap()).unwrap(); + if result.is_err() { + report["executionStatus"] = json!("failed"); + break 'cases; + } + } + } + if report["executionStatus"] == "running" { + report["executionStatus"] = json!("completed"); + } + let mut counts = crate::polish::live_acceptance::intent_counts(); + counts["state"] = json!("final"); + report["transport"] = counts; + std::fs::write(output_path, serde_json::to_vec_pretty(&report).unwrap()).unwrap(); + report +} + +// These are local HTTP fixtures, never provider calls. They use the exact loop, +// production assembly, translation fallback and common send boundary above. +async fn comparison_mock(fallback: bool, failure: Option<(usize, bool)>) -> (Value, usize) { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://{}/v1", listener.local_addr().unwrap()); + let (stop, mut stopping) = tokio::sync::oneshot::channel::<()>(); + let server = tokio::spawn(async move { + let mut seen = 0; + loop { + let accepted = tokio::select! { + _ = &mut stopping => break, + accepted = listener.accept() => accepted.unwrap(), + }; + let mut socket = accepted.0; + let mut request = Vec::new(); + let mut buffer = [0_u8; 4096]; + loop { + let count = socket.read(&mut buffer).await.unwrap(); + if count == 0 { break; } + request.extend_from_slice(&buffer[..count]); + if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") { + let headers = String::from_utf8_lossy(&request[..end]); + let length = headers.lines().find_map(|line| { + line.to_ascii_lowercase().strip_prefix("content-length:") + .and_then(|value| value.trim().parse::().ok()) + }).unwrap(); + if request.len() >= end + 4 + length { break; } + } + } + seen += 1; + if failure == Some((seen, true)) { + // A request/read error that the production retry arm would retry. + drop(socket); + continue; + } + let content = if fallback { + "fixture output" + } else { + "[[OPENLESS_POLISHED_SOURCE]]\n源文。\n[[OPENLESS_TRANSLATION]]\nTranslation." + }; + let event = json!({"choices":[{"delta":{"content":content}}]}); + let body = format!("data: {event}\n\ndata: [DONE]\n\n"); + let status = if failure == Some((seen, false)) { 500 } else { 200 }; + let response = format!( + "HTTP/1.1 {status} fixture\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len(), ); + socket.write_all(response.as_bytes()).await.unwrap(); } + seen + }); + struct Scratch(std::path::PathBuf); + impl Drop for Scratch { + fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } + } + let scratch = Scratch(std::env::temp_dir().join(format!("intent-mock-{}", uuid::Uuid::new_v4()))); + std::fs::create_dir(&scratch.0).unwrap(); + let output = scratch.0.join("results.json"); + let config = ComparisonConfig { + channel_id: "fixture".into(), provider_type: "deepseek".into(), + model: crate::deepseek_suite::MODEL.into(), thinking_enabled: false, baseline: "1.3.0".into(), + credentials: [ + ("ark.api_key".into(), "fixture-key".into()), + ("ark.endpoint".into(), endpoint), + ].into_iter().collect(), + }; + let report = crate::polish::live_acceptance::intent_scope( + run_intent_comparison(&config, output.to_str().unwrap()), + ).await; + stop.send(()).unwrap(); + (report, server.await.unwrap()) +} + +#[tokio::test] +async fn intent_comparison_http_loop_32_and_36() { + for (fallback, expected) in [(false, 32), (true, 36)] { + let (report, seen) = comparison_mock(fallback, None).await; + assert_eq!(report["executionStatus"], "completed"); + assert_eq!(seen, expected); + assert_eq!(report["transport"]["attemptedSends"], expected); + assert_eq!(report["transport"]["fallbackSends"], if fallback { 4 } else { 0 }); + assert_eq!(report["transport"]["state"], "final"); + } +} + +#[tokio::test] +async fn intent_comparison_http_loop_stops_on_first_error() { + for (fallback, failure, expected_fallbacks) in [ + (false, (1, true), 0), (false, (1, false), 0), + (true, (24, false), 1), (true, (24, true), 1), + ] { + let (report, seen) = comparison_mock(fallback, Some(failure)).await; + assert_eq!(report["executionStatus"], "failed"); + assert_eq!(seen, failure.0); + assert_eq!(report["transport"]["attemptedSends"], failure.0); + assert_eq!(report["transport"]["fallbackSends"], expected_fallbacks); + } +} + +// These transport fixtures receive POST requests with Content-Length framing. +// A response requires a complete request, including across partial TCP reads. +async fn read_mock_request(socket: &mut tokio::net::TcpStream) { + use tokio::io::AsyncReadExt; + tokio::time::timeout(std::time::Duration::from_secs(2), async { + let mut request = Vec::new(); + let mut buffer = [0_u8; 4096]; + loop { + let count = socket.read(&mut buffer).await.unwrap(); + assert!(count > 0, "mock request ended before completion"); + request.extend_from_slice(&buffer[..count]); + assert!(request.len() <= 64 * 1024, "mock request exceeds size limit"); + if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") { + let headers = std::str::from_utf8(&request[..end]).unwrap(); + assert!(headers.starts_with("POST "), "mock expected a POST request"); + let length = headers.lines().find_map(|line| { + line.to_ascii_lowercase().strip_prefix("content-length:") + .map(|value| value.trim().parse::().unwrap()) + }).unwrap_or(0); + let total = (end + 4).checked_add(length).unwrap(); + assert!(total <= 64 * 1024, "mock request exceeds size limit"); + if request.len() >= total { break; } + } + } + }).await.expect("mock request timed out before completion"); +} + +#[tokio::test] +async fn intent_comparison_transport_budget_and_redirects() { + use crate::polish::{live_acceptance as probe, send_with_transient_retry as send}; + use tokio::io::AsyncWriteExt; + probe::intent_scope(async { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + for _ in 0..36 { + let (mut socket, _) = listener.accept().await.unwrap(); + read_mock_request(&mut socket).await; + socket.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").await.unwrap(); + } + assert!(tokio::time::timeout(std::time::Duration::from_millis(50), listener.accept()).await.is_err()); + }); + let client = probe::intent_client(&url, 1); + for _ in 0..36 { send(client.post(&url)).await.unwrap(); } + assert!(send(client.post(&url)).await.is_err()); + assert_eq!(probe::intent_counts()["attemptedSends"], 36); + server.await.unwrap(); + }).await; + probe::intent_scope(async { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let redirect = format!("{url}/must-not-follow"); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + read_mock_request(&mut socket).await; + socket.write_all(format!("HTTP/1.1 307 Temporary Redirect\r\nLocation: {redirect}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").as_bytes()).await.unwrap(); + assert!(tokio::time::timeout(std::time::Duration::from_millis(50), listener.accept()).await.is_err()); + }); + let client = probe::intent_client(&url, 1); + assert_eq!(send(client.post(&url)).await.unwrap().status(), 307); + assert!(send(client.post(&url)).await.is_err()); + assert_eq!(probe::intent_counts()["attemptedSends"], 1); + server.await.unwrap(); + }).await; +} + +#[tokio::test] +async fn intent_comparison_transport_connect_request_and_timeout_stop() { + use crate::polish::{live_acceptance as probe, send_with_transient_retry as send}; + // A closed port (connect) and invalid URI (request building) cannot retry. + for invalid_uri in [false, true] { + probe::intent_scope(async { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + drop(listener); + let client = probe::intent_client(&url, 1); + assert!(send(client.post(if invalid_uri { "http://[" } else { &url })).await.is_err()); + assert!(send(client.post(&url)).await.is_err()); + assert_eq!(probe::intent_counts()["attemptedSends"], 1); + }).await; } + probe::intent_scope(async { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let client = probe::intent_client(&url, 1); + assert!(tokio::time::timeout( + std::time::Duration::from_millis(20), send(client.post(&url)), + ).await.is_err()); + assert!(send(client.post(&url)).await.is_err()); + assert_eq!(probe::intent_counts()["attemptedSends"], 1); + }).await; +} + +#[test] +fn intent_comparison_legacy_limits_remain_independent() { + let probe = crate::polish::live_acceptance::legacy_limit; + assert_eq!(probe(false), 10); + assert_eq!(probe(true), 1); + assert!(!crate::polish::live_acceptance::intent_active()); } diff --git a/openless-all/app/crates/openless-core/src/polish.rs b/openless-all/app/crates/openless-core/src/polish.rs index 62502b9cc..52fd14334 100644 --- a/openless-all/app/crates/openless-core/src/polish.rs +++ b/openless-all/app/crates/openless-core/src/polish.rs @@ -594,12 +594,22 @@ impl OpenAICompatibleLLMProvider { let no_proxy = crate::net::should_bypass_proxy(&config.base_url, crate::net::use_system_proxy()); let polish_base_url = config.base_url.clone(); - let polish_client = + let cached_client = || crate::net::cached_client((POLISH_CLIENT_HARD_CAP_SECS, no_proxy), || { http_client_builder(&polish_base_url, POLISH_CLIENT_HARD_CAP_SECS) .build() .unwrap_or_else(|_| reqwest::Client::new()) }); + // The comparison must never reuse a production client's pool, redirects, + // or protocol retry policy. Other tests and production keep the cache. + #[cfg(test)] + let polish_client = if live_acceptance::intent_active() { + live_acceptance::intent_client(&polish_base_url, POLISH_CLIENT_HARD_CAP_SECS) + } else { + cached_client() + }; + #[cfg(not(test))] + let polish_client = cached_client(); Self { config, qa_web_search: false, @@ -1921,6 +1931,13 @@ fn should_retry_transient(is_connect: bool, is_request: bool, is_timeout: bool) pub(crate) async fn send_with_transient_retry( request: reqwest::RequestBuilder, ) -> Result { + #[cfg(test)] + if live_acceptance::intent_active() { + let mut send = live_acceptance::intent_before_send()?; + let response = request.send().await.map_err(llm_error_from_reqwest); + send.succeeded = response.as_ref().is_ok_and(|response| response.status().is_success()); + return response; + } #[cfg(test)] if live_acceptance::active() { let attempt = live_acceptance::before_send()?; @@ -5746,15 +5763,78 @@ mod tests { // and observes the public response model without retaining raw SSE or reasoning. #[cfg(test)] pub(crate) mod live_acceptance { - use std::sync::{atomic::{AtomicBool, AtomicUsize, Ordering}, Mutex}; + use std::sync::{atomic::{AtomicBool, AtomicUsize, Ordering}, Arc, Mutex}; + tokio::task_local! { + static INTENT: Arc>; + } + #[derive(Default)] + struct IntentState { + sends: usize, + fallbacks: usize, + in_fallback: bool, + stopped: bool, + } + pub async fn intent_scope(future: F) -> F::Output { + INTENT.scope(Arc::new(Mutex::new(IntentState::default())), future).await + } + pub fn intent_active() -> bool { INTENT.try_with(|_| ()).is_ok() } + pub fn intent_client(base_url: &str, timeout_secs: u64) -> reqwest::Client { + super::http_client_builder(base_url, timeout_secs) + .no_proxy() + .redirect(reqwest::redirect::Policy::none()) + .retry(reqwest::retry::never()) + .http1_only() + .pool_max_idle_per_host(0) + .build() + .expect("isolated intent transport") + } + pub struct IntentSend { + state: Arc>, + pub succeeded: bool, + } + impl Drop for IntentSend { + fn drop(&mut self) { + if !self.succeeded { self.state.lock().unwrap().stopped = true; } + } + } + pub fn intent_before_send() -> Result { + let state = INTENT.with(Arc::clone); + { + let mut current = state.lock().unwrap(); + if current.stopped || current.sends >= 36 { + return Err(super::LLMError::Network("intent comparison stopped or budget exhausted".into())); + } + current.sends += 1; + if current.in_fallback { current.fallbacks += 1; } + } + Ok(IntentSend { state, succeeded: false }) + } + pub struct IntentFallback(Option>>); + impl Drop for IntentFallback { + fn drop(&mut self) { + if let Some(state) = &self.0 { state.lock().unwrap().in_fallback = false; } + } + } + pub fn intent_fallback() -> IntentFallback { + let state = INTENT.try_with(Arc::clone).ok(); + if let Some(state) = &state { state.lock().unwrap().in_fallback = true; } + IntentFallback(state) + } + pub fn intent_counts() -> serde_json::Value { + INTENT.with(|state| { + let current = state.lock().unwrap(); + serde_json::json!({"attemptedSends": current.sends, "fallbackSends": current.fallbacks}) + }) + } static ACTIVE: AtomicBool = AtomicBool::new(false); static SENDS: AtomicUsize = AtomicUsize::new(0); static RESPONSE_MODEL: Mutex> = Mutex::new(None); pub fn begin() { SENDS.store(0, Ordering::SeqCst); ACTIVE.store(true, Ordering::SeqCst); } pub fn active() -> bool { ACTIVE.load(Ordering::SeqCst) } + pub fn legacy_limit(first_only: bool) -> usize { if first_only { 1 } else { 10 } } pub fn before_send() -> Result { let previous = SENDS.fetch_add(1, Ordering::SeqCst); - if previous >= if std::env::var_os("OPENLESS_LIVE_FIRST_ONLY").is_some() { 1 } else { 10 } { + if previous >= legacy_limit(std::env::var_os("OPENLESS_LIVE_FIRST_ONLY").is_some()) { return Err(super::LLMError::Network("live acceptance request limit reached".into())); } Ok(previous + 1) diff --git a/openless-all/app/scripts/intent-style-comparison-ci.py b/openless-all/app/scripts/intent-style-comparison-ci.py new file mode 100644 index 000000000..e45b54635 --- /dev/null +++ b/openless-all/app/scripts/intent-style-comparison-ci.py @@ -0,0 +1,486 @@ +"""Opt-in CI runner. Review text leaves the runner only in authenticated CMS.""" +import base64 +import copy +import hashlib +import hmac +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile +from urllib.parse import quote + +TARGET = "intent_style_tests::intent_live_configured_channel_comparison" +MODEL = "deepseek-flash" +ENDPOINT = "https://api.deepseek.com/v1" +MAX_REPORT = 2_000_000 +MAX_REVIEW = 1_000_000 +MAX_TEXT = 32_768 +REPOSITORY = "Open-Less/openless" +AUTHORIZED_ACTOR = "appergb" +AUTHORIZED_ACTOR_ID = "192432815" +FIXTURE = Path(__file__).resolve().parent.parent / ( + "crates/openless-core/tests/fixtures/intent-reconstruction-evaluation.json" +) + + +def select_binary(manifest): + binaries = set() + for line in Path(manifest).read_text().splitlines(): + row = json.loads(line) + if ( + row.get("reason") == "compiler-artifact" + and row.get("target", {}).get("name") == "openless_core" + and row.get("profile", {}).get("test") is True + and row.get("executable") + ): + binaries.add(row["executable"]) + if len(binaries) != 1: + raise ValueError("expected one compiled Core test binary") + binary = next(iter(binaries)) + if "\n" in binary or "\r" in binary or not Path(binary).is_file(): + raise ValueError("invalid compiled test binary") + print("binary=" + binary) + + +def safe_report(evaluation): + # Every string comes from a trusted repository fixture or a constant here. + # Arbitrary response text cannot be guaranteed secret-free, so omit it. + return { + "schemaVersion": 1, + "baselineVersion": "1.3.0", + "candidateVersion": "1.4.0", + "requestedModel": MODEL, + "thinkingEnabled": False, + "primaryRequestLimit": 32, + "totalRequestLimit": 36, + "executionStatus": "not_started", + "transport": {"state": "not_started", "attemptedSends": 0, "fallbackSends": 0}, + "semanticReview": "pending human review; outputs are untrusted text", + "cases": [ + { + **{ + key: case[key] + for key in ( + "id", "operation", "input", "mustPreserve", "mustRemove", "structure" + ) + }, + **{ + key: case[key] + for key in ("instruction", "targetLanguage") + if key in case + }, + "old": {"status": "pending"}, + "new": {"status": "pending"}, + } + for case in evaluation["cases"] + ], + } + + +def apply_status(report, raw): + if ( + raw.get("schemaVersion") != 1 + or raw.get("baselineVersion") != "1.3.0" + or raw.get("candidateVersion") != "1.4.0" + or raw.get("requestedModel") != MODEL + or raw.get("thinkingEnabled") is not False + or not isinstance(raw.get("cases"), list) + or [case.get("id") for case in raw["cases"]] + != [case["id"] for case in report["cases"]] + ): + raise ValueError("unexpected comparison report") + for target, case in zip(report["cases"], raw["cases"]): + for side in ("old", "new"): + value = case.get(side) + if value is None: + continue + if not isinstance(value, dict): + raise ValueError("unexpected result") + if "errorCode" in value: + target[side] = {"status": "request_failed"} + elif isinstance(value.get("text"), str): + target[side] = {"status": "completed"} + elapsed = value.get("elapsedMs") + if type(elapsed) is int and 0 <= elapsed <= 900_000: + target[side]["elapsedMs"] = elapsed + else: + raise ValueError("unexpected result") + + +def validate_source(): + expected = os.environ.get("INTENT_EXPECTED_SOURCE_SHA", "") + ref = os.environ.get("GITHUB_REF", "") + if ( + not re.fullmatch("[0-9a-f]{40}", expected) + or os.environ.get("GITHUB_EVENT_NAME") != "workflow_dispatch" + or os.environ.get("GITHUB_REPOSITORY") != REPOSITORY + or ref not in ("refs/heads/main", "refs/heads/beta") + or os.environ.get("GITHUB_SHA") != expected + or os.environ.get("INTENT_WORKFLOW_SHA") != expected + or os.environ.get("GITHUB_WORKFLOW_REF") != f"{REPOSITORY}/.github/workflows/ci.yml@{ref}" + ): + raise ValueError("unverified dispatch") + checkout = subprocess.run( + ["git", "rev-parse", "HEAD"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + timeout=10, check=False, + env={name: os.environ[name] for name in ("PATH", "HOME", "TMPDIR", "LANG") + if name in os.environ}, + ) + if checkout.returncode != 0 or checkout.stdout.decode("ascii").strip() != expected: + raise ValueError("unverified checkout") + return { + "sourceSha": expected, "workflowSha": expected, + "workflowRef": os.environ["GITHUB_WORKFLOW_REF"], + } + + +def validate_dispatch(): + verified = validate_source() + run_id = os.environ.get("GITHUB_RUN_ID", "") + if ( + os.environ.get("GITHUB_ACTOR") != AUTHORIZED_ACTOR + or os.environ.get("GITHUB_ACTOR_ID") != AUTHORIZED_ACTOR_ID + or os.environ.get("INTENT_TRIGGERING_ACTOR") != AUTHORIZED_ACTOR + or os.environ.get("GITHUB_RUN_ATTEMPT") != "1" + or not re.fullmatch("[1-9][0-9]{0,19}", run_id) + ): + raise ValueError("unverified dispatch") + return { + **verified, + "runId": run_id, "runAttempt": 1, + "actor": AUTHORIZED_ACTOR, "actorId": AUTHORIZED_ACTOR_ID, + } + + +def intent_preflight(directory): + verified = validate_dispatch() + expected = os.environ.get("INTENT_RECIPIENT_SHA256", "") + if not re.fullmatch("[0-9a-f]{64}", expected): + raise ValueError("unconfirmed recipient") + certificate, actual = validate_recipient( + os.environ.get("INTENT_RECIPIENT_CERTIFICATE", ""), directory + ) + if not hmac.compare_digest(expected, actual): + raise ValueError("recipient mismatch") + verified["recipientSha256"] = actual + return certificate, verified + + +def apply_transport(report, raw, returncode): + report["transport"] = {"state": "unknown"} + counts = raw.get("transport", {}) + sends, fallbacks = counts.get("attemptedSends"), counts.get("fallbackSends") + if ( + returncode < 0 or counts.get("state") != "final" + or type(sends) is not int or not 0 <= sends <= 36 + or type(fallbacks) is not int or not 0 <= fallbacks <= min(4, sends) + ): + raise ValueError("unknown transport count") + report["transport"] = { + "state": "final", "attemptedSends": sends, "fallbackSends": fallbacks, + } + +def openssl(arguments, data=None): + result = subprocess.run( + ["openssl", *arguments], input=data, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, timeout=30, check=False, + env={name: os.environ[name] for name in ("PATH", "HOME", "TMPDIR", "LANG") + if name in os.environ}, + ) + if result.returncode != 0: + raise ValueError("cryptographic operation failed") + return result.stdout + + +def private_write(path, data): + with open(path, "xb", opener=lambda name, flags: os.open(name, flags, 0o600)) as stream: + stream.write(data) + + +def cms_encrypt(plaintext, ciphertext, certificate): + openssl([ + "cms", "-encrypt", "-binary", "-aes-256-gcm", + "-in", str(plaintext), "-outform", "DER", "-out", str(ciphertext), + "-recip", str(certificate), "-keyopt", "rsa_padding_mode:oaep", + "-keyopt", "rsa_oaep_md:sha256", "-keyopt", "rsa_mgf1_md:sha256", + ]) + validate_ciphertext(ciphertext) + + +def validate_ciphertext(ciphertext): + # Both sides reject unauthenticated CBC, even for an otherwise valid CMS file. + if not 128 <= ciphertext.stat().st_size <= MAX_REPORT: + raise ValueError("unexpected ciphertext size") + structure = openssl(["cms", "-cmsout", "-inform", "DER", "-in", str(ciphertext), "-print"]) + for field in ( + rb"^ contentType: id-smime-ct-authEnvelopedData \(", + rb"^\s+algorithm: aes-256-gcm \(", + rb"^\s+algorithm: rsaesOaep \(", + ): + if not re.search(field, structure, re.M): + raise ValueError("authenticated CMS required") + + +def validate_recipient(certificate, directory): + if ( + not isinstance(certificate, str) or len(certificate) > 8192 + or not re.fullmatch( + r"\s*-----BEGIN CERTIFICATE-----\r?\n[A-Za-z0-9+/=\r\n]+" + r"-----END CERTIFICATE-----\s*", certificate + ) + ): + raise ValueError("one public PEM certificate required") + path = directory / "recipient.pem" + private_write(path, certificate.encode("ascii")) + der = openssl(["x509", "-in", str(path), "-outform", "DER"]) + openssl(["x509", "-in", str(path), "-checkend", "3600", "-noout"]) + public = openssl(["x509", "-in", str(path), "-pubkey", "-noout"]) + details = openssl(["rsa", "-pubin", "-text", "-noout"], public) + bits = re.search(rb"Public-Key: \((\d+) bit\)", details) + if not bits or not 3072 <= int(bits[1]) <= 8192: + raise ValueError("RSA 3072..8192 recipient required") + # Prove that this installed OpenSSL supports the exact authenticated format + # before the caller reads provider credentials or starts a paid request. + probe = directory / "probe.json" + encrypted = directory / "probe.cms" + private_write(probe, b'{"preflight":"non-sensitive fixture"}') + cms_encrypt(probe, encrypted, path) + probe.unlink() + encrypted.unlink() + return path, hashlib.sha256(der).hexdigest() + + +def review_text(text, key, allowed_urls): + if not isinstance(text, str) or len(text.encode("utf-8")) > MAX_TEXT: + raise ValueError("invalid review text") + if any(ord(char) < 32 and char not in "\r\n\t" for char in text): + raise ValueError("unexpected control character") + variants = { + key, quote(key, safe=""), key.encode().hex(), + base64.b64encode(key.encode()).decode(), + base64.urlsafe_b64encode(key.encode()).decode(), + json.dumps(key)[1:-1], + } + if any(value in text for value in variants): + raise ValueError("credential echo rejected") + if re.search( + r"-----BEGIN (?:[A-Z ]*PRIVATE KEY|CERTIFICATE)-----" + r"|authorization\s*:\s*bearer|(?:api[_ -]?key|token)\s*[:=]" + r"|\bsk-[A-Za-z0-9_-]{16,}", text, re.I + ): + raise ValueError("credential-like content rejected") + if set(re.findall(r'https?://[^\s<>"`(),。;)]+', text)) - allowed_urls: + raise ValueError("unexpected URL") + return text + + +def review_payload(report, raw, key): + payload = copy.deepcopy(report) + for target, canonical, case in zip(payload["cases"], report["cases"], raw["cases"]): + allowed_urls = set(re.findall(r'https?://[^\s<>"`(),。;)]+', canonical["input"])) + for side in ("old", "new"): + value = case.get(side) + if value is None: + target[side] = None + elif "errorCode" in value: + target[side] = {"errorCode": "request_failed"} + else: + selected = {"text": review_text(value["text"], key, allowed_urls)} + source = value.get("sourceText") + if source is not None: + selected["sourceText"] = review_text(source, key, allowed_urls) + elapsed = canonical[side].get("elapsedMs") + if elapsed is not None: + selected["elapsedMs"] = elapsed + target[side] = selected + encoded = (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode() + if len(encoded) > MAX_REVIEW: + raise ValueError("oversize review") + return encoded + + +def decrypt_review(ciphertext, certificate, private_key, output, expected_sha, run_id, fingerprint): + """Local explicit command only. Never writes unauthenticated plaintext.""" + ciphertext = Path(ciphertext) + if ( + not re.fullmatch("[0-9a-f]{40}", expected_sha) + or not re.fullmatch("[1-9][0-9]{0,19}", run_id) + or not re.fullmatch("[0-9a-f]{64}", fingerprint) + ): + raise ValueError("receipt binding required") + actual = hashlib.sha256(openssl(["x509", "-in", certificate, "-outform", "DER"])).hexdigest() + if not hmac.compare_digest(fingerprint, actual): + raise ValueError("wrong local recipient") + validate_ciphertext(ciphertext) + plaintext = openssl([ + "cms", "-decrypt", "-binary", "-inform", "DER", "-in", str(ciphertext), + "-recip", certificate, "-inkey", private_key, + ]) + if len(plaintext) > MAX_REVIEW: + raise ValueError("oversize review") + payload = json.loads(plaintext) + if ( + payload.get("sourceSha") != expected_sha or payload.get("workflowSha") != expected_sha + or payload.get("runId") != run_id or type(payload.get("runAttempt")) is not int + or payload["runAttempt"] != 1 or payload.get("recipientSha256") != fingerprint + or payload.get("actor") != AUTHORIZED_ACTOR + or payload.get("actorId") != AUTHORIZED_ACTOR_ID + or payload.get("workflowRef") not in { + f"{REPOSITORY}/.github/workflows/ci.yml@refs/heads/main", + f"{REPOSITORY}/.github/workflows/ci.yml@refs/heads/beta", + } + ): + raise ValueError("wrong evidence origin") + canonical = safe_report(json.loads(FIXTURE.read_text())) + apply_status(canonical, payload) + apply_transport(canonical, payload, 0) + # Keep the plaintext out of stdout; the original renderer reads this private file. + private_write(Path(output), plaintext) + + +def check_recipient(certificate, private_key): + """Coordinator-only local receipt check, with fixed non-sensitive bytes.""" + with tempfile.TemporaryDirectory(prefix="openless-local-recipient-") as scratch: + directory = Path(scratch) + recipient, fingerprint = validate_recipient(Path(certificate).read_text(), directory) + plaintext = directory / "local-check.txt" + ciphertext = directory / "local-check.cms" + expected = b"OpenLess one-time recipient possession check" + private_write(plaintext, expected) + cms_encrypt(plaintext, ciphertext, recipient) + actual = openssl([ + "cms", "-decrypt", "-binary", "-inform", "DER", "-in", str(ciphertext), + "-recip", str(recipient), "-inkey", private_key, + ]) + if actual != expected: + raise ValueError("recipient possession check failed") + return fingerprint + + +def run(binary, private_directory, evidence_directory): + report = safe_report(json.loads(FIXTURE.read_text())) + operations = [case["operation"] for case in report["cases"]] + if ( + len(operations) != 16 + or operations.count("dictation") != 12 + or operations.count("translation") != 2 + or operations.count("selection") != 2 + ): + raise ValueError("expected the original bounded 16 fixtures") + evidence_directory = Path(evidence_directory) + evidence_directory.mkdir(mode=0o700, parents=True, exist_ok=False) + output = evidence_directory / "status.json" + private_directory = Path(private_directory) + config = private_directory / "channel.json" + raw_output = private_directory / "results.json" + result = 1 + ciphertext = evidence_directory / "comparison.cms" + try: + try: + recipient, verified = intent_preflight(private_directory) + report.update(verified) + except Exception: + report["executionStatus"] = "dispatch_or_recipient_unverified" + return 1 + key = os.environ.pop("DEEPSEEK_API_KEY", "") + if not key or key != key.strip() or any(char.isspace() for char in key): + report["executionStatus"] = "credentials_missing_or_invalid" + return result + # This matches the existing official-provider suite, not local user settings. + settings = { + "channelId": "deepseek", + "providerType": "deepseek", + "model": MODEL, + "thinkingEnabled": False, + "baseline": "1.3.0", + "credentials": { + "ark.endpoint": ENDPOINT, + "ark.api_key": key, + }, + } + with open(config, "x", opener=lambda path, flags: os.open(path, flags, 0o600)) as stream: + json.dump(settings, stream) + # No workflow credentials or logging environment are inherited by the test. + environment = { + name: os.environ[name] + for name in ("PATH", "HOME", "TMPDIR", "LANG") + if name in os.environ + } + environment.update({ + "OPENLESS_INTENT_COMPARISON_APPROVED": "yes", + "OPENLESS_INTENT_COMPARISON_CONFIG": str(config), + "OPENLESS_INTENT_COMPARISON_OUTPUT": str(raw_output), + }) + report["transport"] = {"state": "unknown"} + completed = subprocess.run( + [binary, TARGET, "--ignored", "--exact", "--test-threads=1"], + env=environment, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=900, + check=False, + ) + if not raw_output.is_file() or raw_output.stat().st_size > MAX_REPORT: + report["executionStatus"] = "missing_or_invalid_report" + return result + raw = json.loads(raw_output.read_text()) + apply_status(report, raw) + apply_transport(report, raw, completed.returncode) + all_completed = all( + case[side]["status"] == "completed" + for case in report["cases"] + for side in ("old", "new") + ) + result = 0 if completed.returncode == 0 and all_completed else 1 + report["executionStatus"] = "completed" if result == 0 else "test_failed" + try: + plaintext = private_directory / "review.json" + private_write(plaintext, review_payload(report, raw, key)) + encrypted = private_directory / "comparison.cms" + cms_encrypt(plaintext, encrypted, recipient) + encrypted.replace(ciphertext) + report["encryptedReview"] = "available" + except Exception: + report["executionStatus"] = "review_rejected_or_encryption_failed" + return 1 + return result + except subprocess.TimeoutExpired: + report["executionStatus"] = "timed_out" + return 1 + except Exception: + # No repr/traceback: even parser and filesystem errors can contain secrets. + report["executionStatus"] = "execution_or_report_failed" + return 1 + finally: + for name in ( + "channel.json", "results.json", "review.json", "comparison.cms", + "recipient.pem", "probe.json", "probe.cms", + ): + (private_directory / name).unlink(missing_ok=True) + output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n") + + +if __name__ == "__main__": + try: + if len(sys.argv) == 3 and sys.argv[1] == "select-binary": + select_binary(sys.argv[2]) + elif len(sys.argv) == 2 and sys.argv[1] == "source-preflight": + print(json.dumps(validate_source(), sort_keys=True)) + elif len(sys.argv) == 2 and sys.argv[1] == "preflight": + with tempfile.TemporaryDirectory(prefix="openless-intent-recipient-") as scratch: + intent_preflight(Path(scratch)) + elif len(sys.argv) == 9 and sys.argv[1] == "decrypt": + decrypt_review(*sys.argv[2:]) + elif len(sys.argv) == 4 and sys.argv[1] == "check-recipient": + print("recipientSha256=" + check_recipient(*sys.argv[2:])) + elif len(sys.argv) == 5 and sys.argv[1] == "run": + sys.exit(run(*sys.argv[2:])) + else: + sys.exit(2) + except Exception: + # Inputs in this wrapper are never printed, including exception messages. + print("Intent comparison wrapper failed; no private diagnostic was published.") + sys.exit(1) diff --git a/openless-all/app/scripts/intent-style-comparison.test.mjs b/openless-all/app/scripts/intent-style-comparison.test.mjs index 3c7ad3e0a..ce6a5379a 100644 --- a/openless-all/app/scripts/intent-style-comparison.test.mjs +++ b/openless-all/app/scripts/intent-style-comparison.test.mjs @@ -15,7 +15,9 @@ const rendered = renderComparison(report); assert.ok(rendered.includes('<old> | before
second')); assert.ok(rendered.includes('Source: 源文

after')); assert.ok(rendered.includes('12 ms')); -assert.ok(!rendered.includes('must-never-render')); +assert.ok(!rendered.includes(report.credentials['ark.api_key'])); +assert.ok(!rendered.includes('credentials')); +assert.ok(!rendered.includes('ark.api_key')); report.cases[0].old = { errorCode: 'Provider' }; assert.ok(renderComparison(report).includes('Request failed: Provider')); assert.throws(() => renderComparison({ schemaVersion: 2, cases: [] })); diff --git a/openless-all/app/scripts/intent-style-gates.sh b/openless-all/app/scripts/intent-style-gates.sh new file mode 100644 index 000000000..fe6c9bde6 --- /dev/null +++ b/openless-all/app/scripts/intent-style-gates.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# Shared, provider-free build/enumeration/mock gates. No live execution branch. +set -euo pipefail +umask 077 +log=$(mktemp "${TMPDIR:-/tmp}/openless-intent-gates.XXXXXX") +trap 'rm -f "$log"' EXIT +fail() { printf 'FAIL intent_gate=%s\n' "$1" >&2; exit 1; } +[[ $# -ge 1 ]] || fail arguments + +case "$1" in + python) + [[ $# == 1 ]] || fail arguments + PYTHONDONTWRITEBYTECODE=1 python3 scripts/test_intent_style_comparison_ci.py \ + > "$log" 2>&1 || fail python_dummy + grep -Eq '^Ran 22 tests in ' "$log" || fail python_count + grep -Fx 'OK' "$log" > /dev/null || fail python_result + printf 'PASS python_tests=22\n' + ;; + build) + [[ $# == 2 ]] || fail arguments + # Exactly one compilation; stdout is only select-binary's safe assignment. + cargo test --locked -p openless-core --lib -j 1 --no-run --message-format=json \ + > "$2" 2> "$log" || fail core_test_lib_compile + python3 scripts/intent-style-comparison-ci.py select-binary "$2" \ + > "$log" 2>&1 || fail core_test_binary_selection + cat "$log" + printf 'PASS core_test_lib_compilations=1\n' >&2 + ;; + verify) + [[ $# == 2 ]] || fail arguments + binary=$2 + [[ -f "$binary" && -x "$binary" ]] || fail test_binary + listed_once() { + local target=$1 + shift + "$binary" "$target" "$@" --exact --list > "$log" 2>&1 || fail enumeration + [[ "$(grep -Fxc "$target: test" "$log")" == 1 ]] || fail exact_name + [[ "$(grep -c ': test$' "$log")" == 1 ]] || fail enumeration_count + } + for name in \ + intent_comparison_http_loop_32_and_36 \ + intent_comparison_http_loop_stops_on_first_error \ + intent_comparison_transport_budget_and_redirects \ + intent_comparison_transport_connect_request_and_timeout_stop \ + intent_comparison_legacy_limits_remain_independent; do + listed_once "intent_style_tests::$name" + done + "$binary" intent_style_tests::intent_comparison_ --test-threads=1 \ + > "$log" 2>&1 || fail intent_mocks + grep -Eq '^test result: ok\. 5 passed; 0 failed; 0 ignored;' "$log" || fail mock_count + listed_once intent_style_tests::intent_live_configured_channel_comparison --ignored + printf 'PASS mock_tests=5 exact_mock_names=5 ignored_live_listed=1 live_tests_executed=0\n' + ;; + *) fail operation ;; +esac diff --git a/openless-all/app/scripts/test_intent_secretless_preflight.py b/openless-all/app/scripts/test_intent_secretless_preflight.py new file mode 100644 index 000000000..d34084c1c --- /dev/null +++ b/openless-all/app/scripts/test_intent_secretless_preflight.py @@ -0,0 +1,132 @@ +"""Offline contracts only. No Cargo or real Rust binary is invoked here.""" +import importlib.util +import os +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[3] +SCRIPT = Path(__file__).with_name("intent-style-comparison-ci.py") +SPEC = importlib.util.spec_from_file_location("intent_secretless_ci", SCRIPT) +ci = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(ci) +GATES = Path(__file__).with_name("intent-style-gates.sh") + + +class SecretlessPreflightTests(unittest.TestCase): + def test_source_only_gate_binds_sha_without_provider_or_recipient(self): + environment = { + "GITHUB_EVENT_NAME": "workflow_dispatch", "GITHUB_REPOSITORY": ci.REPOSITORY, + "GITHUB_REF": "refs/heads/beta", "GITHUB_SHA": "a" * 40, + "INTENT_EXPECTED_SOURCE_SHA": "a" * 40, "INTENT_WORKFLOW_SHA": "a" * 40, + "GITHUB_WORKFLOW_REF": ci.REPOSITORY + "/.github/workflows/ci.yml@refs/heads/beta", + } + git = subprocess.CompletedProcess([], 0, stdout=("a" * 40 + "\n").encode()) + with patch.dict(os.environ, environment, clear=True): + with patch.object(ci.subprocess, "run", return_value=git): + self.assertEqual(ci.validate_source()["sourceSha"], "a" * 40) + # The paid validator still requires its original actor/attempt gates. + with self.assertRaises(ValueError): + ci.validate_dispatch() + for field in ("GITHUB_SHA", "INTENT_WORKFLOW_SHA", "INTENT_EXPECTED_SOURCE_SHA"): + with patch.dict(os.environ, {field: "b" * 40}): + with self.assertRaises(ValueError): + ci.validate_source() + with patch.object(ci.subprocess, "run", return_value=subprocess.CompletedProcess( + [], 0, stdout=("b" * 40 + "\n").encode() + )): + with self.assertRaises(ValueError): + ci.validate_source() + + def test_workflow_is_nondefault_mutually_exclusive_and_secretless(self): + workflow = (ROOT / ".github/workflows/ci.yml").read_text() + secretless = workflow.split("\n intent-secretless-preflight:\n", 1)[1].split( + "\n live-acceptance:\n", 1 + )[0] + paid = workflow.split("\n live-acceptance:\n", 1)[1] + self.assertIn("default: 'off'", workflow) + self.assertIn("inputs.live_acceptance == 'intent-style-preflight'", secretless) + self.assertIn("inputs.live_acceptance != 'intent-style-preflight'", paid) + self.assertIn("github.event_name != 'workflow_dispatch' || inputs.live_acceptance == 'off'", workflow) + for text in (secretless, paid): + self.assertIn("github.repository == 'Open-Less/openless'", text) + self.assertIn('["refs/heads/main","refs/heads/beta"]', text) + self.assertIn("contents: read", text) + self.assertIn("persist-credentials: false", text) + for forbidden in ("secrets.", "environment:", "DEEPSEEK", "ci.py run", "gh workflow"): + self.assertNotIn(forbidden, secretless) + self.assertIn("ci.py source-preflight", secretless) + self.assertIn('export CARGO_TARGET_DIR="$scratch/target"', secretless) + self.assertIn('export TMPDIR="$scratch/tmp"', secretless) + self.assertIn("trap 'rm -rf", secretless) + self.assertLess(secretless.index("gates.sh python"), secretless.index("gates.sh build")) + self.assertLess(secretless.index("gates.sh build"), secretless.index("gates.sh verify")) + helper = GATES.read_text() + self.assertEqual(helper.count("cargo test --locked -p openless-core --lib -j 1 --no-run --message-format=json"), 1) + self.assertNotIn("cargo ", helper.split(" verify)", 1)[1]) + + def test_paid_target_uses_step_env_not_unavailable_job_runner_context(self): + workflow = (ROOT / ".github/workflows/ci.yml").read_text() + paid = workflow.split("\n live-acceptance:\n", 1)[1] + header, steps = paid.split(" steps:\n", 1) + self.assertNotIn("runner.", header) + for name in ("Build acceptance without credentials", "Run explicitly selected bounded acceptance"): + step = steps.split(" - name: " + name + "\n", 1)[1].split("\n - name:", 1)[0] + self.assertIn(" env:\n", step) + self.assertIn("CARGO_TARGET_DIR: ${{ runner.temp }}/openless-live-target", step) + self.assertIn('rm -rf "$RUNNER_TEMP/openless-live-target"', steps) + + def test_shared_gate_lists_live_only_and_rejects_zero_tests(self): + # Stubs are intentional: this validates shell control flow without compiling. + with tempfile.TemporaryDirectory(prefix="openless-secretless-contract-") as scratch: + directory = Path(scratch) + binary = directory / "fixture-binary" + binary.write_text("""#!/bin/sh +printf '%s\\n' "$*" >> "$CALLS_FILE" +if [ "$1" = intent_style_tests::intent_comparison_ ]; then + if [ "$ZERO_TESTS" = 1 ]; then + printf 'test result: ok. 0 passed; 0 failed; 0 ignored;\\n' + else + printf 'test result: ok. 5 passed; 0 failed; 0 ignored;\\n' + fi +else + case " $* " in *" --exact --list "*) ;; *) exit 90 ;; esac + case "$1" in + *intent_live_configured_channel_comparison) + case " $* " in *" --ignored --exact --list "*) ;; *) exit 91 ;; esac ;; + esac + printf '%s: test\\n' "$1" +fi +""") + binary.chmod(0o700) + temporary = directory / "tmp" + temporary.mkdir() + calls = directory / "calls" + environment = { + "PATH": os.environ["PATH"], "TMPDIR": str(temporary), + "CALLS_FILE": str(calls), "ZERO_TESTS": "0", + } + result = subprocess.run( + ["bash", str(GATES), "verify", str(binary)], env=environment, + text=True, capture_output=True, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("mock_tests=5", result.stdout) + recorded = calls.read_text().splitlines() + self.assertEqual(len(recorded), 7) + self.assertEqual(recorded[-1], ci.TARGET + " --ignored --exact --list") + self.assertEqual(list(temporary.iterdir()), []) + environment["ZERO_TESTS"] = "1" + result = subprocess.run( + ["bash", str(GATES), "verify", str(binary)], env=environment, + text=True, capture_output=True, + ) + self.assertNotEqual(result.returncode, 0) + self.assertIn("FAIL intent_gate=mock_count", result.stderr) + self.assertEqual(list(temporary.iterdir()), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/openless-all/app/scripts/test_intent_style_comparison_ci.py b/openless-all/app/scripts/test_intent_style_comparison_ci.py new file mode 100644 index 000000000..9ed020b8f --- /dev/null +++ b/openless-all/app/scripts/test_intent_style_comparison_ci.py @@ -0,0 +1,403 @@ +"""Offline tests only: the process boundary is mocked; no credentials or network.""" +import importlib.util +import contextlib +import io +import json +import os +from pathlib import Path +import re +import stat +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +SCRIPT = Path(__file__).with_name("intent-style-comparison-ci.py") +SPEC = importlib.util.spec_from_file_location("intent_comparison_ci", SCRIPT) +ci = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(ci) +SENTINEL = "synthetic-ci-fixture-secret" +REAL_RUN = subprocess.run + + +class IntentComparisonCiTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.recipient_scratch = tempfile.TemporaryDirectory(prefix="openless-dummy-recipient-") + cls.addClassCleanup(cls.recipient_scratch.cleanup) + cls.cert = Path(cls.recipient_scratch.name) / "dummy.crt" + cls.key = Path(cls.recipient_scratch.name) / "dummy.key" + result = REAL_RUN([ + "openssl", "req", "-x509", "-newkey", "rsa:3072", "-sha256", "-nodes", + "-keyout", str(cls.key), "-out", str(cls.cert), "-days", "2", + "-subj", "/CN=OpenLess-offline-dummy", + ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30) + if result.returncode != 0: + raise RuntimeError("existing OpenSSL required for offline dummy roundtrip") + cls.certificate = cls.cert.read_text() + cls.fingerprint = ci.hashlib.sha256( + ci.openssl(["x509", "-in", str(cls.cert), "-outform", "DER"]) + ).hexdigest() + + def setUp(self): + self.scratch = tempfile.TemporaryDirectory(prefix="openless-intent-ci-test-") + self.addCleanup(self.scratch.cleanup) + self.private = Path(self.scratch.name) / "private" + self.private.mkdir(mode=0o700) + self.evidence = Path(self.scratch.name) / "evidence" + self.evaluation = json.loads(ci.FIXTURE.read_text()) + + def raw(self): + return { + **ci.safe_report(self.evaluation), + "transport": {"state": "final", "attemptedSends": 32, "fallbackSends": 0}, + "credentials": {"key": SENTINEL}, + "cases": [ + { + "id": case["id"], + "input": SENTINEL, + "old": {"text": "合成旧版正文。", "elapsedMs": 12}, + "new": {"text": "合成新版正文。", "sourceText": "合成源文。", "elapsedMs": 15}, + } + for case in self.evaluation["cases"] + ], + } + + def execute(self, raw=None, returncode=0, exception=None, key=SENTINEL, certificate=None, + env_changes=None, checkout_sha="a" * 40): + model_calls = [] + def fake_process(argv, **kwargs): + if argv == ["git", "rev-parse", "HEAD"]: + return subprocess.CompletedProcess(argv, 0, stdout=(checkout_sha + "\n").encode()) + if argv[0] != "/unused/test-binary": + return REAL_RUN(argv, **kwargs) + model_calls.append(argv) + self.assertEqual(argv, [ + "/unused/test-binary", ci.TARGET, "--ignored", "--exact", "--test-threads=1" + ]) + self.assertEqual(kwargs["stdout"], subprocess.DEVNULL) + self.assertEqual(kwargs["stderr"], subprocess.DEVNULL) + self.assertNotIn("DEEPSEEK_API_KEY", kwargs["env"]) + self.assertNotIn("GITHUB_TOKEN", kwargs["env"]) + self.assertNotIn("INTENT_RECIPIENT_CERTIFICATE", kwargs["env"]) + config = self.private / "channel.json" + self.assertEqual(stat.S_IMODE(config.stat().st_mode), 0o600) + settings = json.loads(config.read_text()) + self.assertEqual(settings["credentials"]["ark.api_key"], SENTINEL) + self.assertEqual(settings["baseline"], "1.3.0") + self.assertEqual(settings["model"], ci.MODEL) + self.assertIs(settings["thinkingEnabled"], False) + if exception: + raise exception + if raw is not None: + (self.private / "results.json").write_text(json.dumps(raw)) + return subprocess.CompletedProcess(argv, returncode) + + environment = { + "DEEPSEEK_API_KEY": key, "GITHUB_TOKEN": SENTINEL, "GITHUB_SHA": "a" * 40, + "GITHUB_EVENT_NAME": "workflow_dispatch", "GITHUB_REPOSITORY": ci.REPOSITORY, + "GITHUB_REF": "refs/heads/beta", "GITHUB_RUN_ID": "123456789", "GITHUB_RUN_ATTEMPT": "1", + "GITHUB_ACTOR": "appergb", "GITHUB_ACTOR_ID": ci.AUTHORIZED_ACTOR_ID, + "INTENT_TRIGGERING_ACTOR": "appergb", "INTENT_WORKFLOW_SHA": "a" * 40, + "GITHUB_WORKFLOW_REF": ci.REPOSITORY + "/.github/workflows/ci.yml@refs/heads/beta", + "INTENT_EXPECTED_SOURCE_SHA": "a" * 40, "INTENT_RECIPIENT_SHA256": self.fingerprint, + "INTENT_RECIPIENT_CERTIFICATE": ( + self.certificate if certificate is None else certificate + ), + } + environment.update(env_changes or {}) + with patch.dict(os.environ, environment): + with patch.object(ci.subprocess, "run", side_effect=fake_process): + code = ci.run("/unused/test-binary", self.private, self.evidence) + published = (self.evidence / "status.json").read_text() + self.assertNotIn(SENTINEL, published) + self.assertNotIn("private.invalid", published) + self.assertNotIn("合成旧版正文", published) + self.assertNotIn("合成新版正文", published) + self.assertEqual(list(self.private.iterdir()), []) + if code == 0: + self.assertTrue((self.evidence / "comparison.cms").is_file()) + else: + self.assertFalse((self.evidence / "review.json").exists()) + self.assertEqual( + {path.name for path in self.evidence.iterdir()} - {"status.json", "comparison.cms"}, + set(), + ) + return code, json.loads(published), len(model_calls) + + def decrypt(self, ciphertext, output, sha="a" * 40, run_id="123456789", fingerprint=None): + return ci.decrypt_review( + ciphertext, str(self.cert), str(self.key), str(output), sha, run_id, + self.fingerprint if fingerprint is None else fingerprint, + ) + + def test_success_uploads_only_canonical_fixtures_and_status(self): + code, report, calls = self.execute(self.raw()) + self.assertEqual((code, calls), (0, 1)) + self.assertEqual(report["executionStatus"], "completed") + self.assertEqual(report["cases"][0]["old"], {"status": "completed", "elapsedMs": 12}) + self.assertEqual(report["cases"][0]["input"], self.evaluation["cases"][0]["input"]) + self.assertNotIn("credentials", report) + self.assertNotIn("text", report["cases"][0]["new"]) + self.assertEqual(report["sourceSha"], "a" * 40) + self.assertEqual(report["encryptedReview"], "available") + output = Path(self.scratch.name) / "reviewed.json" + self.decrypt(self.evidence / "comparison.cms", output) + review = json.loads(output.read_text()) + self.assertEqual(review["cases"][0]["old"]["text"], "合成旧版正文。") + self.assertEqual(review["cases"][0]["new"]["sourceText"], "合成源文。") + self.assertNotIn(SENTINEL, output.read_text()) + self.assertEqual(stat.S_IMODE(output.stat().st_mode), 0o600) + self.assertEqual(report["transport"], { + "state": "final", "attemptedSends": 32, "fallbackSends": 0, + }) + self.assertEqual((report["runId"], report["runAttempt"]), ("123456789", 1)) + + def test_missing_recipient_fails_before_any_model_process(self): + code, report, calls = self.execute(certificate="") + self.assertEqual((code, calls), (1, 0)) + self.assertEqual(report["executionStatus"], "dispatch_or_recipient_unverified") + self.assertFalse((self.evidence / "comparison.cms").exists()) + + def test_dispatch_sha_actor_attempt_and_recipient_fail_before_model(self): + changes = [ + {"INTENT_EXPECTED_SOURCE_SHA": ""}, + {"INTENT_EXPECTED_SOURCE_SHA": "a" * 39}, + {"INTENT_EXPECTED_SOURCE_SHA": "A" * 40}, + {"INTENT_EXPECTED_SOURCE_SHA": "a" * 40 + "\n"}, + {"INTENT_EXPECTED_SOURCE_SHA": "b" * 40}, + {"GITHUB_SHA": "b" * 40}, + {"INTENT_WORKFLOW_SHA": "b" * 40}, + {"GITHUB_REF": "refs/tags/beta"}, + {"GITHUB_REF": "refs/heads/beta/child"}, + {"GITHUB_REPOSITORY": "fork/openless"}, + {"GITHUB_EVENT_NAME": "pull_request"}, + {"GITHUB_WORKFLOW_REF": ci.REPOSITORY + "/.github/workflows/other.yml@refs/heads/beta"}, + {"GITHUB_WORKFLOW_REF": ci.REPOSITORY + "/.github/workflows/ci.yml@refs/heads/main"}, + {"GITHUB_ACTOR": "another-writer"}, + {"GITHUB_ACTOR_ID": "0"}, + {"INTENT_TRIGGERING_ACTOR": "another-writer"}, + {"GITHUB_RUN_ATTEMPT": "2"}, + {"GITHUB_RUN_ATTEMPT": "01"}, + {"GITHUB_RUN_ID": ""}, + {"INTENT_RECIPIENT_SHA256": ""}, + {"INTENT_RECIPIENT_SHA256": "b" * 64}, + ] + for index, change in enumerate(changes): + self.evidence = Path(self.scratch.name) / f"blocked-{index}" + code, report, calls = self.execute(self.raw(), env_changes=change) + self.assertEqual((code, calls), (1, 0), next(iter(change))) + self.assertEqual(report["executionStatus"], "dispatch_or_recipient_unverified") + self.assertEqual(report["transport"]["attemptedSends"], 0) + self.assertFalse((self.evidence / "comparison.cms").exists()) + + def test_checkout_drift_is_rejected_before_model(self): + code, report, calls = self.execute(self.raw(), checkout_sha="b" * 40) + self.assertEqual((code, calls), (1, 0)) + self.assertEqual(report["executionStatus"], "dispatch_or_recipient_unverified") + + def test_receipt_decrypt_is_bound_to_exact_run_sha_and_fingerprint(self): + self.execute(self.raw()) + for index, binding in enumerate(( + {"sha": "b" * 40}, {"run_id": "123456790"}, {"fingerprint": "b" * 64}, + )): + output = Path(self.scratch.name) / f"wrong-receipt-{index}.json" + with self.assertRaises(ValueError): + self.decrypt(self.evidence / "comparison.cms", output, **binding) + self.assertFalse(output.exists()) + + def test_only_final_bounded_transport_counts_are_certified(self): + raw = self.raw() + raw["transport"] = {"state": "final", "attemptedSends": 36, "fallbackSends": 4} + code, report, _ = self.execute(raw) + self.assertEqual(code, 0) + self.assertEqual(report["transport"], raw["transport"]) + for index, (counts, returncode) in enumerate(( + ({"state": "running", "attemptedSends": 3, "fallbackSends": 0}, 0), + ({"state": "final", "attemptedSends": 37, "fallbackSends": 4}, 0), + ({"state": "final", "attemptedSends": 36, "fallbackSends": 5}, 0), + ({"state": "final", "attemptedSends": 36, "fallbackSends": 4}, -9), + )): + self.evidence = Path(self.scratch.name) / f"unknown-{index}" + raw["transport"] = counts + code, report, _ = self.execute(raw, returncode=returncode) + self.assertEqual(code, 1) + self.assertEqual(report["transport"], {"state": "unknown"}) + + def test_private_key_or_bad_certificate_is_rejected_before_model(self): + code, report, calls = self.execute(certificate=self.key.read_text()) + self.assertEqual((code, calls), (1, 0)) + self.assertEqual(report["executionStatus"], "dispatch_or_recipient_unverified") + + def test_malformed_public_certificate_is_rejected_before_model(self): + code, _, calls = self.execute( + certificate="-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n" + ) + self.assertEqual((code, calls), (1, 0)) + + def test_sensitive_echo_is_rejected_and_no_plaintext_is_published(self): + raw = self.raw() + raw["cases"][0]["new"]["text"] = SENTINEL + code, report, calls = self.execute(raw) + self.assertEqual((code, calls), (1, 1)) + self.assertEqual(report["executionStatus"], "review_rejected_or_encryption_failed") + self.assertFalse((self.evidence / "comparison.cms").exists()) + + def test_encoded_echo_and_abnormal_output_are_rejected(self): + for index, text in enumerate(( + ci.base64.b64encode(SENTINEL.encode()).decode(), + "Authorization: Bearer hidden", "https://private.invalid/path", + "\x00", "x" * (ci.MAX_TEXT + 1), + )): + self.evidence = Path(self.scratch.name) / f"rejected-{index}" + raw = self.raw() + raw["cases"][0]["new"]["sourceText"] = text + code, report, _ = self.execute(raw) + self.assertEqual(code, 1) + self.assertEqual(report["executionStatus"], "review_rejected_or_encryption_failed") + self.assertFalse((self.evidence / "comparison.cms").exists()) + + def test_tampered_ciphertext_never_writes_decrypted_output(self): + self.execute(self.raw()) + ciphertext = self.evidence / "comparison.cms" + data = bytearray(ciphertext.read_bytes()) + data[-1] ^= 1 + ciphertext.write_bytes(data) + output = Path(self.scratch.name) / "must-not-exist.json" + with self.assertRaises(ValueError): + self.decrypt(ciphertext, output) + self.assertFalse(output.exists()) + + def test_cms_uses_fresh_randomness(self): + plain = self.private / "dummy.json" + plain.write_bytes(b'{"dummy":true}') + first = self.private / "first.cms" + second = self.private / "second.cms" + ci.cms_encrypt(plain, first, self.cert) + ci.cms_encrypt(plain, second, self.cert) + self.assertNotEqual(first.read_bytes(), second.read_bytes()) + + def test_local_decrypt_rejects_unauthenticated_cms_before_private_key_use(self): + plain = self.private / "dummy.txt" + plain.write_bytes(b"non-sensitive fixture") + cipher = self.private / "cbc.cms" + ci.openssl([ + "cms", "-encrypt", "-binary", "-aes-256-cbc", "-in", str(plain), + "-outform", "DER", "-out", str(cipher), str(self.cert) + ]) + output = self.private / "must-not-exist.json" + with patch.object(ci, "openssl", wraps=ci.openssl) as operations: + with self.assertRaises(ValueError): + self.decrypt(cipher, output) + self.assertFalse(any("-decrypt" in call.args[0] for call in operations.call_args_list)) + self.assertFalse(output.exists()) + + def test_encrypt_failure_cleans_plaintext_and_publishes_no_ciphertext(self): + real_encrypt = ci.cms_encrypt + calls = [] + def fail_second(plain, cipher, certificate): + calls.append(plain) + if len(calls) == 1: + return real_encrypt(plain, cipher, certificate) + cipher.write_bytes(b"partial cipher") + raise ValueError(SENTINEL) + with patch.object(ci, "cms_encrypt", side_effect=fail_second): + code, report, _ = self.execute(self.raw()) + self.assertEqual(code, 1) + self.assertEqual(report["executionStatus"], "review_rejected_or_encryption_failed") + self.assertFalse((self.evidence / "comparison.cms").exists()) + + def test_coordinator_can_check_dummy_recipient_without_paid_requests(self): + fingerprint = ci.check_recipient(str(self.cert), str(self.key)) + self.assertRegex(fingerprint, "^[0-9a-f]{64}$") + + def test_provider_failure_drops_error_and_retains_pending(self): + raw = self.raw() + raw["cases"][0]["new"] = {"errorCode": SENTINEL} + raw["transport"]["attemptedSends"] = 2 + for case in raw["cases"][1:]: + case["old"] = case["new"] = None + code, report, _ = self.execute(raw, returncode=101) + self.assertEqual(code, 1) + self.assertEqual(report["cases"][0]["new"], {"status": "request_failed"}) + self.assertEqual(report["cases"][1]["old"], {"status": "pending"}) + + def test_missing_or_invalid_credentials_fail_before_process(self): + code, report, calls = self.execute(key="") + self.assertEqual((code, calls), (1, 0)) + self.assertEqual(report["executionStatus"], "credentials_missing_or_invalid") + + def test_timeout_is_safe_and_cleans_config(self): + code, report, _ = self.execute(exception=subprocess.TimeoutExpired(SENTINEL, 900)) + self.assertEqual(code, 1) + self.assertEqual(report["executionStatus"], "timed_out") + self.assertEqual(report["transport"], {"state": "unknown"}) + + def test_invalid_report_never_publishes_raw_diagnostic(self): + raw = self.raw() + raw["cases"][0]["id"] = SENTINEL + code, report, _ = self.execute(raw) + self.assertEqual(code, 1) + self.assertEqual(report["executionStatus"], "execution_or_report_failed") + + def test_zero_tests_is_failure(self): + code, report, _ = self.execute() + self.assertEqual(code, 1) + self.assertEqual(report["executionStatus"], "missing_or_invalid_report") + + def test_selects_one_precompiled_binary_and_rejects_ambiguity(self): + binary = self.private / "test-binary" + binary.touch() + manifest = self.private / "build.jsonl" + artifact = { + "reason": "compiler-artifact", "target": {"name": "openless_core"}, + "profile": {"test": True}, "executable": str(binary) + } + manifest.write_text(json.dumps(artifact) + "\n") + with contextlib.redirect_stdout(io.StringIO()) as output: + ci.select_binary(manifest) + self.assertEqual(output.getvalue(), "binary=" + str(binary) + "\n") + artifact["executable"] = str(self.private / "another-binary") + with manifest.open("a") as stream: + stream.write(json.dumps(artifact) + "\n") + with self.assertRaises(ValueError): + ci.select_binary(manifest) + + def test_workflow_uses_only_trusted_manual_path_and_safe_artifact(self): + workflow = SCRIPT.parents[3] / ".github/workflows/ci.yml" + text = workflow.read_text() + live = text.split("\n live-acceptance:\n", 1)[1] + self.assertIn("default: 'off'", text) + self.assertIn('["refs/heads/main","refs/heads/beta"]', live) + self.assertIn("github.repository == 'Open-Less/openless'", live) + self.assertIn("github.event_name == 'workflow_dispatch'", live) + self.assertIn("persist-credentials: false", live) + self.assertIn("chmod 700", live) + self.assertIn("trap 'rm -rf", live) + self.assertIn("inputs.live_acceptance != 'intent-style-comparison'", live) + self.assertIn("openless-intent-evidence/status.json", live) + self.assertIn("openless-intent-evidence/comparison.cms", live) + self.assertNotIn("openless-intent-evidence/*.json", live) + self.assertLess(live.index("preflight"), live.index("Build acceptance without credentials")) + self.assertIn("INTENT_WORKFLOW_SHA: ${{ github.workflow_sha }}", live) + self.assertIn("INTENT_TRIGGERING_ACTOR: ${{ github.triggering_actor }}", live) + self.assertIn("intent_expected_source_sha", text) + self.assertIn("intent_recipient_sha256", text) + self.assertNotIn("intent_allowed_actor", text) + self.assertLess( + live.index("Verify intent mock transport gates"), + live.index("Compare intent 1.3.0 and 1.4.0"), + ) + self.assertIn("CARGO_TARGET_DIR: ${{ runner.temp }}/openless-live-target", live) + self.assertIn('rm -rf "$RUNNER_TEMP/openless-live-target"', live) + suite = SCRIPT.parent.parent / "crates/openless-core/src/deepseek_suite.rs" + for name, value in (("MODEL", ci.MODEL), ("ENDPOINT", ci.ENDPOINT)): + found = re.search(rf'pub const {name}: &str = "([^"]+)";', suite.read_text()) + self.assertEqual(found.group(1), value) + self.assertEqual( + sum(c["operation"] == "translation" for c in self.evaluation["cases"]), 2 + ) + + +if __name__ == "__main__": + unittest.main()