diff --git a/.github/workflows/apply-paper-candidate.yml b/.github/workflows/apply-paper-candidate.yml index ba53e78..c9e9432 100644 --- a/.github/workflows/apply-paper-candidate.yml +++ b/.github/workflows/apply-paper-candidate.yml @@ -44,7 +44,8 @@ jobs: LONGBRIDGE_PHYSICAL_ACCOUNT_ID: ${{ vars.LONGBRIDGE_PHYSICAL_ACCOUNT_ID }} GCP_ARTIFACT_REGISTRY_HOSTNAME: ${{ vars.GCP_ARTIFACT_REGISTRY_HOSTNAME }} GCP_ARTIFACT_REGISTRY_REPOSITORY: ${{ vars.GCP_ARTIFACT_REGISTRY_REPOSITORY || 'cloud-run-source-deploy' }} - QSL_CONTROL_PLANE_SYNC_URL: ${{ vars.QSL_CONTROL_PLANE_SYNC_URL || 'https://qsl-strategy-switch-console.pigbibi.workers.dev' }} + QSL_CONTROL_PLANE_SYNC_URL: ${{ vars.QSL_CONTROL_PLANE_SYNC_URL }} + QSL_CONSOLE_ORIGIN: ${{ vars.QSL_CONSOLE_ORIGIN }} EXECUTION_EVIDENCE_SYNC_TOKEN: ${{ secrets.EXECUTION_EVIDENCE_SYNC_TOKEN }} steps: - name: Checkout protected main @@ -83,6 +84,10 @@ jobs: chmod 700 "$work" echo "work=$work" >> "$GITHUB_OUTPUT" umask 077 + # Keep this revision's transport: later steps check out the candidate commit, + # whose older transport may not accept the configured console origin. + mkdir "$work/transport" + cp scripts/v7_paper_application_http.py "$work/transport/" uv run python -m scripts.v7_paper_application_http fetch \ --base-url "$QSL_CONTROL_PLANE_SYNC_URL" \ --application-id "$APPLICATION_ID" \ @@ -248,7 +253,7 @@ jobs: RUN_ATTEMPT: ${{ github.run_attempt }} run: | set -euo pipefail - uv run python -m scripts.v7_paper_application_http result \ + python3 -I "${{ steps.application.outputs.work }}/transport/v7_paper_application_http.py" result \ --base-url "$QSL_CONTROL_PLANE_SYNC_URL" \ --record-file "${{ steps.application.outputs.work }}/application.json" \ --readback-file "${{ steps.application.outputs.work }}/readback-inner.json" \ @@ -261,7 +266,7 @@ jobs: RUN_ATTEMPT: ${{ github.run_attempt }} run: | set -euo pipefail - uv run python -m scripts.v7_paper_application_http result \ + python3 -I "${{ steps.application.outputs.work }}/transport/v7_paper_application_http.py" result \ --base-url "$QSL_CONTROL_PLANE_SYNC_URL" \ --record-file "${{ steps.application.outputs.work }}/application.json" \ --status uncertain --run-id "$RUN_ID" --attempt "$RUN_ATTEMPT" >/dev/null diff --git a/.github/workflows/execution-report-heartbeat.yml b/.github/workflows/execution-report-heartbeat.yml index 1432015..7438c15 100644 --- a/.github/workflows/execution-report-heartbeat.yml +++ b/.github/workflows/execution-report-heartbeat.yml @@ -307,6 +307,7 @@ jobs: env: ACCOUNT_HISTORY_EXPECTED_SOURCE_BINDING_ID: ${{ secrets.ACCOUNT_HISTORY_EXPECTED_SOURCE_BINDING_ID }} EXECUTION_EVIDENCE_SYNC_TOKEN: ${{ secrets.EXECUTION_EVIDENCE_SYNC_TOKEN }} + RUNTIME_DAILY_SYNC_URL: ${{ vars.RUNTIME_DAILY_SYNC_URL }} GOOGLE_CLOUD_PROJECT: ${{ env.GCP_PROJECT_ID }} run: uv run --no-sync python -m scripts.publish_daily_runtime_projection --one-shot-live diff --git a/.github/workflows/publish-runtime-daily-once.yml b/.github/workflows/publish-runtime-daily-once.yml index a9d37f2..689781f 100644 --- a/.github/workflows/publish-runtime-daily-once.yml +++ b/.github/workflows/publish-runtime-daily-once.yml @@ -103,6 +103,7 @@ jobs: - name: Create one truthful daily projection and verify QRS ACK env: EXECUTION_EVIDENCE_SYNC_TOKEN: ${{ secrets.EXECUTION_EVIDENCE_SYNC_TOKEN }} + RUNTIME_DAILY_SYNC_URL: ${{ vars.RUNTIME_DAILY_SYNC_URL }} run: | if [ "${DAILY_MODE}" = "preflight" ]; then uv run --no-sync python -m scripts.publish_daily_runtime_projection --live-preflight diff --git a/docs/daily-runtime-projection.md b/docs/daily-runtime-projection.md index ef9bdb7..7bb0433 100644 --- a/docs/daily-runtime-projection.md +++ b/docs/daily-runtime-projection.md @@ -90,6 +90,8 @@ heartbeat 的告警、返回码和交易链不变。这个步骤不调用 heartb 该同步仍默认关闭;此前的只读核验记录(非本次线上配置确认)显示 LongBridge PAPER 环境当时尚无 `RUNTIME_DAILY_SYNC_ENABLED` 或 `RUNTIME_DAILY_SYNC_URL` variable。它复用已有 execution-evidence secret 名称,不新增 secret。真实报告前缀、桶权限及第一份对象仍需在获准身份上验收。bot 送达不在这一步。 +一次性 PAPER/实盘日记录、接收端 token 探测和 heartbeat 实盘步骤都从 `RUNTIME_DAILY_SYNC_URL` 读取完整同步地址(形如 `https://console.example.com/api/runtime-daily/sync`),源码不再固定控制台主机;该变量缺失或格式不精确时拒绝执行,不发送 token。V7 PAPER 申请流程另读 `QSL_CONTROL_PLANE_SYNC_URL`(纯来源地址,形如 `https://console.example.com`)和 `QSL_CONSOLE_ORIGIN`(同一纯来源地址);两者不一致、请求被重定向或变量缺失时均不发送 token。两个变量格式不同,不能填同一个值。 + ## 一次性 PAPER 日记录 原有每日 heartbeat 的日报步骤复用下述已验证的 PAPER 只读入口;只有原环境的 `RUNTIME_DAILY_PROJECTION_ENABLED` 与 `RUNTIME_DAILY_SYNC_ENABLED` 同为 `true` 才执行。输出前缀从原受保护 secret 取得,原 `20 22 * * *` 时刻不变。每次生成独立观测对象并核对 QRS ACK;这不补造交易调度证明,运行计划未确认时继续保留 incomplete。自然定时结果与手动单次发布结果分别验收。 diff --git a/logs.json b/logs.json new file mode 100644 index 0000000..656e9df --- /dev/null +++ b/logs.json @@ -0,0 +1 @@ +[{"jsonPayload": {"event": "other", "status": "applied_paused", "readback": {"application_id": "61743a15-6dcc-4ebf-8ecb-454660014af7", "revision_name": "paper-v7-00001", "runtime_target_enabled": false}}}] \ No newline at end of file diff --git a/scripts/publish_daily_runtime_projection.py b/scripts/publish_daily_runtime_projection.py index 3f75088..fdc70aa 100644 --- a/scripts/publish_daily_runtime_projection.py +++ b/scripts/publish_daily_runtime_projection.py @@ -48,7 +48,6 @@ _RUNTIME_DAILY_SYNC_MAX_RESPONSE_BYTES = 64 * 1024 _HTTPS_HOST = re.compile(r"^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$") _RUNTIME_DAILY_SYNC_TARGET_KEY = "longbridge-quant-paper-service|russell_top50_leader_rotation|paper" -_ONE_SHOT_SYNC_URL = "https://qsl-strategy-switch-console.pigbibi.workers.dev/api/runtime-daily/sync" class _Rejected(Exception): @@ -236,7 +235,8 @@ def _one_shot_environment( scoped = { **env, "RUNTIME_DAILY_PROJECTION_ENABLED": "true", "RUNTIME_DAILY_PROJECTION_TARGET_ID": env.get("RUNTIME_HEARTBEAT_ACCOUNT_SCOPE", "").lower() if live else "paper", "RUNTIME_DAILY_PROJECTION_GCS_PREFIX": prefix, "RUNTIME_DAILY_SYNC_ENABLED": "true", - "RUNTIME_DAILY_SYNC_URL": _ONE_SHOT_SYNC_URL, + # The console origin comes from protected configuration, never from source. + "RUNTIME_DAILY_SYNC_URL": _runtime_daily_sync_url(str(env.get("RUNTIME_DAILY_SYNC_URL") or "")), } target = _select_target(scoped, live=live) if not env.get("CLOUD_RUN_SERVICE") or target.get("service") != env["CLOUD_RUN_SERVICE"]: @@ -825,7 +825,8 @@ def _verify_receiver_token(env: Mapping[str, str], http_post: Callable[..., Any] if http_post is None: import requests http_post = requests.post - response = http_post(_ONE_SHOT_SYNC_URL, headers={"Authorization": f"Bearer {token}", + url = _runtime_daily_sync_url(str(env.get("RUNTIME_DAILY_SYNC_URL") or "")) + response = http_post(url, headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"}, data=b"{", timeout=_RUNTIME_DAILY_SYNC_TIMEOUT_SECONDS, allow_redirects=False, stream=True) diff --git a/scripts/v7_paper_application_http.py b/scripts/v7_paper_application_http.py index 17f3892..b6926ee 100644 --- a/scripts/v7_paper_application_http.py +++ b/scripts/v7_paper_application_http.py @@ -5,6 +5,8 @@ import argparse import json +import os +import re import sys import urllib.error import urllib.parse @@ -13,7 +15,8 @@ from collections.abc import Mapping from pathlib import Path -_EXPECTED_HOST = "qsl-strategy-switch-console.pigbibi.workers.dev" +# The console origin comes from protected configuration (vars.QSL_CONTROL_PLANE_SYNC_URL). +_HTTPS_HOST = re.compile(r"^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$") _PATH_PREFIX = "/api/internal/research-promotion-application/" @@ -29,24 +32,32 @@ def _application_id(value: str) -> str: def _endpoint(base_url: str, application_id: str) -> str: - parsed = urllib.parse.urlsplit(base_url.strip()) + # The bearer token goes only to the origin approved separately in QSL_CONSOLE_ORIGIN. + approved = os.environ.get("QSL_CONSOLE_ORIGIN", "") + parsed = urllib.parse.urlsplit(base_url) + origin = f"https://{parsed.hostname}" if ( - parsed.scheme != "https" - or parsed.hostname != _EXPECTED_HOST - or parsed.port is not None - or parsed.username - or parsed.password - or parsed.query - or parsed.fragment - or parsed.path not in {"", "/"} + _HTTPS_HOST.fullmatch(parsed.hostname or "") is None + or base_url not in {origin, origin + "/"} + or approved != origin ): raise ApplicationTransportError("invalid control-plane origin") return urllib.parse.urljoin( - f"https://{_EXPECTED_HOST}/", + f"{origin}/", f"{_PATH_PREFIX}{urllib.parse.quote(_application_id(application_id), safe='')}", ) +class _NoRedirect(urllib.request.HTTPRedirectHandler): + """Authenticated control-plane calls never follow a redirect.""" + + def redirect_request(self, *args, **kwargs): + return None + + +_open = urllib.request.build_opener(_NoRedirect()).open + + def _request(*, method: str, url: str, token: str, payload: Mapping[str, object] | None = None) -> dict[str, object]: if not token.strip(): raise ApplicationTransportError("sync token is missing") @@ -57,7 +68,7 @@ def _request(*, method: str, url: str, token: str, payload: Mapping[str, object] headers["Content-Type"] = "application/json" request = urllib.request.Request(url, data=body, headers=headers, method=method) try: - with urllib.request.urlopen(request, timeout=20) as response: + with _open(request, timeout=20) as response: raw = response.read(256 * 1024) except (urllib.error.HTTPError, urllib.error.URLError, TimeoutError) as exc: raise ApplicationTransportError("control-plane request failed") from exc @@ -161,7 +172,7 @@ def main() -> int: parser.add_argument("--attempt", required=True) args = parser.parse_args() try: - token = __import__("os").environ.get("EXECUTION_EVIDENCE_SYNC_TOKEN", "") + token = os.environ.get("EXECUTION_EVIDENCE_SYNC_TOKEN", "") if args.operation == "fetch": result = fetch(base_url=args.base_url, token=token, application_id=args.application_id or "") else: diff --git a/tests/test_publish_daily_runtime_projection.py b/tests/test_publish_daily_runtime_projection.py index 34bcef3..b9570d9 100644 --- a/tests/test_publish_daily_runtime_projection.py +++ b/tests/test_publish_daily_runtime_projection.py @@ -1928,7 +1928,7 @@ def prohibited(*_a, **_kw): objects = [] if report is None else [{"url": "gs://synthetic-existing/reports/run.json", "metadata": {"updated": OBSERVED.isoformat()}}] def post(url, **kwargs): observed["post"] += 1 - assert url == publisher._ONE_SHOT_SYNC_URL + assert url == "https://qrs.example.com/api/runtime-daily/sync" assert kwargs["allow_redirects"] is False assert kwargs["data"].decode() == blob.uploads[0]["data"] if http_post is not None: @@ -2015,12 +2015,12 @@ def test_one_shot_report_root_preserves_bucket_root_compatibility(value): def test_single_observation_uses_protected_output_prefix_separate_from_report_root(): original = _one_shot_env( RUNTIME_DAILY_PROJECTION_GCS_PREFIX="gs://synthetic-existing/runtime_daily", - RUNTIME_DAILY_SYNC_URL="https://unapproved.example.com/api/runtime-daily/sync", + RUNTIME_DAILY_SYNC_URL="https://qrs.example.com/api/runtime-daily/sync", ) scoped = publisher._one_shot_environment(original, report_root_uri="gs://synthetic-existing/reports") assert scoped["RUNTIME_DAILY_PROJECTION_GCS_PREFIX"] == "gs://synthetic-existing/runtime_daily" assert scoped["RUNTIME_DAILY_PROJECTION_GCS_PREFIX"] != "gs://synthetic-existing/reports/runtime_daily" - assert scoped["RUNTIME_DAILY_SYNC_URL"] == publisher._ONE_SHOT_SYNC_URL + assert scoped["RUNTIME_DAILY_SYNC_URL"] == "https://qrs.example.com/api/runtime-daily/sync" assert scoped["RUNTIME_TARGET_ENABLED"] == original["RUNTIME_TARGET_ENABLED"] == "false" @@ -2471,5 +2471,6 @@ def test_scheduled_live_daily_uses_existing_heartbeat_without_new_schedule(): assert "steps.gcp_auth_retry.outcome == 'success'" in step assert "secrets.ACCOUNT_HISTORY_EXPECTED_SOURCE_BINDING_ID" in step assert "secrets.EXECUTION_EVIDENCE_SYNC_TOKEN" in step + assert "RUNTIME_DAILY_SYNC_URL: ${{ vars.RUNTIME_DAILY_SYNC_URL }}" in step assert "--one-shot-live" in step and "continue-on-error: true" in step assert workflow.count('cron:') == 1 diff --git a/tests/test_v7_paper_application.py b/tests/test_v7_paper_application.py index 823d5f0..71924bc 100644 --- a/tests/test_v7_paper_application.py +++ b/tests/test_v7_paper_application.py @@ -34,6 +34,12 @@ FIXED_MONDAY = datetime(2026, 9, 14, 21, 0, tzinfo=timezone.utc) + +@pytest.fixture(autouse=True) +def _approved_console_origin(monkeypatch): + monkeypatch.setenv("QSL_CONSOLE_ORIGIN", "https://console.example.com") + + def _record(**overrides): record = { "application_id": str(uuid.uuid4()), @@ -365,7 +371,7 @@ def fake_request(**kwargs): monkeypatch.setattr(transport, "_request", fake_request) transport.post_claim( - base_url="https://qsl-strategy-switch-console.pigbibi.workers.dev", + base_url="https://console.example.com", token="secret-token", record=record, run_id="200", @@ -375,11 +381,51 @@ def fake_request(**kwargs): assert "claim_token" not in calls[0]["payload"] -def test_qsl_application_origin_is_fixed() -> None: +def test_qsl_application_origin_is_bound_to_configured_origin(monkeypatch) -> None: from scripts.v7_paper_application_http import ApplicationTransportError, _endpoint + application_id = str(uuid.uuid4()) + assert _endpoint("https://console.example.com", application_id) == ( + f"https://console.example.com/api/internal/research-promotion-application/{application_id}" + ) + for origin in ( + "", + "http://console.example.com", + "https://user:pass@console.example.com", + "https://@console.example.com", + "https://console.example.com:8443", + "https://console.example.com/other", + "https://console.example.com/?", + "https://console.example.com/#fragment", + "https://Console.example.com", + " https://console.example.com", + "https://console.exa\tmple.com", + "https://127.0.0.1", + "https://other.example.com", + ): + with pytest.raises(ApplicationTransportError): + _endpoint(origin, application_id) + monkeypatch.delenv("QSL_CONSOLE_ORIGIN") with pytest.raises(ApplicationTransportError): - _endpoint("https://attacker.example", str(uuid.uuid4())) + _endpoint("https://console.example.com", application_id) + + +def test_qsl_application_request_does_not_follow_redirects() -> None: + import email.message + import io + import urllib.request + + from scripts import v7_paper_application_http as transport + + request = urllib.request.Request("https://console.example.com/a", headers={"Authorization": "Bearer synthetic"}) + headers = email.message.Message() + headers["Location"] = "https://other.example.com/b" + assert transport._NoRedirect().redirect_request( + request, io.BytesIO(), 302, "Found", headers, "https://other.example.com/b" + ) is None + handlers = transport._open.__self__.handlers + assert any(isinstance(handler, transport._NoRedirect) for handler in handlers) + assert not any(type(handler) is urllib.request.HTTPRedirectHandler for handler in handlers) def _loaded_v7_readback(monkeypatch): diff --git a/tests/test_v7_paper_application_workflow.py b/tests/test_v7_paper_application_workflow.py index 20ce30c..dc4d86d 100644 --- a/tests/test_v7_paper_application_workflow.py +++ b/tests/test_v7_paper_application_workflow.py @@ -51,7 +51,9 @@ def test_workflow_preserves_paper_pause_and_real_loaded_readback() -> None: def test_workflow_uses_nested_claims_and_marks_post_claim_failures_uncertain() -> None: assert "scripts.v7_paper_application_http claim" in WORKFLOW - assert "scripts.v7_paper_application_http result" in WORKFLOW + assert 'cp scripts/v7_paper_application_http.py "$work/transport/"' in WORKFLOW + assert WORKFLOW.count('transport/v7_paper_application_http.py" result') == 2 + assert "scripts.v7_paper_application_http result" not in WORKFLOW assert "status uncertain" in WORKFLOW assert "failure() && steps.claim.outcome == 'success'" in WORKFLOW assert "--token" not in WORKFLOW