From 52d338a6d439abba21ca64e960bafcaf1c6e0c0c Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:31:53 +0000 Subject: [PATCH 1/3] fix(console): read the console origin from configuration The one-shot daily sync, its receiver-token probe and the V7 paper application transport pinned the retired console host in source. Read the origin from vars.RUNTIME_DAILY_SYNC_URL and vars.QSL_CONTROL_PLANE_SYNC_URL instead, keep the strict https/host/path validation, and fail closed when the variable is missing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011iHeYdZHqdsDyVsVxzUJLA --- .github/workflows/apply-paper-candidate.yml | 2 +- .../workflows/publish-runtime-daily-once.yml | 1 + scripts/publish_daily_runtime_projection.py | 7 +++--- scripts/v7_paper_application_http.py | 8 ++++--- .../test_publish_daily_runtime_projection.py | 6 ++--- tests/test_v7_paper_application.py | 22 +++++++++++++++---- 6 files changed, 32 insertions(+), 14 deletions(-) diff --git a/.github/workflows/apply-paper-candidate.yml b/.github/workflows/apply-paper-candidate.yml index ba53e782..77d1e05f 100644 --- a/.github/workflows/apply-paper-candidate.yml +++ b/.github/workflows/apply-paper-candidate.yml @@ -44,7 +44,7 @@ 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 }} EXECUTION_EVIDENCE_SYNC_TOKEN: ${{ secrets.EXECUTION_EVIDENCE_SYNC_TOKEN }} steps: - name: Checkout protected main diff --git a/.github/workflows/publish-runtime-daily-once.yml b/.github/workflows/publish-runtime-daily-once.yml index a9d37f22..689781f7 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/scripts/publish_daily_runtime_projection.py b/scripts/publish_daily_runtime_projection.py index 3f750882..fdc70aab 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 17f38928..b1a86db4 100644 --- a/scripts/v7_paper_application_http.py +++ b/scripts/v7_paper_application_http.py @@ -5,6 +5,7 @@ import argparse import json +import re import sys import urllib.error import urllib.parse @@ -13,7 +14,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/" @@ -32,7 +34,7 @@ def _endpoint(base_url: str, application_id: str) -> str: parsed = urllib.parse.urlsplit(base_url.strip()) if ( parsed.scheme != "https" - or parsed.hostname != _EXPECTED_HOST + or _HTTPS_HOST.fullmatch(parsed.hostname or "") is None or parsed.port is not None or parsed.username or parsed.password @@ -42,7 +44,7 @@ def _endpoint(base_url: str, application_id: str) -> str: ): raise ApplicationTransportError("invalid control-plane origin") return urllib.parse.urljoin( - f"https://{_EXPECTED_HOST}/", + f"https://{parsed.hostname}/", f"{_PATH_PREFIX}{urllib.parse.quote(_application_id(application_id), safe='')}", ) diff --git a/tests/test_publish_daily_runtime_projection.py b/tests/test_publish_daily_runtime_projection.py index 34bcef30..d4fdf892 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" diff --git a/tests/test_v7_paper_application.py b/tests/test_v7_paper_application.py index 823d5f0f..f88e1fb9 100644 --- a/tests/test_v7_paper_application.py +++ b/tests/test_v7_paper_application.py @@ -365,7 +365,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 +375,25 @@ 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() -> None: from scripts.v7_paper_application_http import ApplicationTransportError, _endpoint - with pytest.raises(ApplicationTransportError): - _endpoint("https://attacker.example", str(uuid.uuid4())) + 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:8443", + "https://console.example.com/other", + "https://console.example.com/?redirect=1", + "https://console.example.com/#fragment", + "https://127.0.0.1", + ): + with pytest.raises(ApplicationTransportError): + _endpoint(origin, application_id) def _loaded_v7_readback(monkeypatch): From e6db9b5fc0018b4dc80c64eb34af96dec88fb959 Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:34:37 +0000 Subject: [PATCH 2/3] fix(console): pass sync URL to live heartbeat and keep result transport Map vars.RUNTIME_DAILY_SYNC_URL into the scheduled live projection step, and run the paper application result callbacks from a copy of this revision's transport so an older checked-out candidate cannot reject the configured console origin. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011iHeYdZHqdsDyVsVxzUJLA --- .github/workflows/apply-paper-candidate.yml | 8 ++++++-- .github/workflows/execution-report-heartbeat.yml | 1 + tests/test_publish_daily_runtime_projection.py | 1 + tests/test_v7_paper_application_workflow.py | 4 +++- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.github/workflows/apply-paper-candidate.yml b/.github/workflows/apply-paper-candidate.yml index 77d1e05f..63906ec7 100644 --- a/.github/workflows/apply-paper-candidate.yml +++ b/.github/workflows/apply-paper-candidate.yml @@ -83,6 +83,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 +252,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 +265,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 1432015a..7438c152 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/tests/test_publish_daily_runtime_projection.py b/tests/test_publish_daily_runtime_projection.py index d4fdf892..b9570d9e 100644 --- a/tests/test_publish_daily_runtime_projection.py +++ b/tests/test_publish_daily_runtime_projection.py @@ -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_workflow.py b/tests/test_v7_paper_application_workflow.py index 20ce30ca..dc4d86d1 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 From 805e9c643c2d19db3dfcaee141985694d1decbbc Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:47:07 +0000 Subject: [PATCH 3/3] fix(console): bind the V7 transport to an approved origin Require the paper application origin to match vars.QSL_CONSOLE_ORIGIN exactly and refuse redirects before the token is sent. Document the two console variables and their formats. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011iHeYdZHqdsDyVsVxzUJLA --- .github/workflows/apply-paper-candidate.yml | 1 + docs/daily-runtime-projection.md | 2 ++ logs.json | 1 + scripts/v7_paper_application_http.py | 33 ++++++++++++------- tests/test_v7_paper_application.py | 36 +++++++++++++++++++-- 5 files changed, 59 insertions(+), 14 deletions(-) create mode 100644 logs.json diff --git a/.github/workflows/apply-paper-candidate.yml b/.github/workflows/apply-paper-candidate.yml index 63906ec7..c9e94325 100644 --- a/.github/workflows/apply-paper-candidate.yml +++ b/.github/workflows/apply-paper-candidate.yml @@ -45,6 +45,7 @@ jobs: 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 }} + QSL_CONSOLE_ORIGIN: ${{ vars.QSL_CONSOLE_ORIGIN }} EXECUTION_EVIDENCE_SYNC_TOKEN: ${{ secrets.EXECUTION_EVIDENCE_SYNC_TOKEN }} steps: - name: Checkout protected main diff --git a/docs/daily-runtime-projection.md b/docs/daily-runtime-projection.md index ef9bdb74..7bb0433b 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 00000000..656e9dfc --- /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/v7_paper_application_http.py b/scripts/v7_paper_application_http.py index b1a86db4..b6926eeb 100644 --- a/scripts/v7_paper_application_http.py +++ b/scripts/v7_paper_application_http.py @@ -5,6 +5,7 @@ import argparse import json +import os import re import sys import urllib.error @@ -31,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 _HTTPS_HOST.fullmatch(parsed.hostname or "") is None - 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://{parsed.hostname}/", + 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") @@ -59,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 @@ -163,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_v7_paper_application.py b/tests/test_v7_paper_application.py index f88e1fb9..71924bcd 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()), @@ -375,7 +381,7 @@ def fake_request(**kwargs): assert "claim_token" not in calls[0]["payload"] -def test_qsl_application_origin_is_bound_to_configured_origin() -> 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()) @@ -386,14 +392,40 @@ def test_qsl_application_origin_is_bound_to_configured_origin() -> None: "", "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/?redirect=1", + "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://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):