diff --git a/.github/workflows/execution-report-heartbeat.yml b/.github/workflows/execution-report-heartbeat.yml index 5fda64b..dfb2f68 100644 --- a/.github/workflows/execution-report-heartbeat.yml +++ b/.github/workflows/execution-report-heartbeat.yml @@ -197,6 +197,8 @@ jobs: FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID: ${{ secrets.FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID }} EXECUTION_REPORT_GCS_URI: ${{ vars.EXECUTION_REPORT_GCS_URI || secrets.EXECUTION_REPORT_GCS_URI }} EXECUTION_EVIDENCE_SYNC_URL: ${{ vars.EXECUTION_EVIDENCE_SYNC_URL }} + FIRSTRADE_ACCOUNT_FACTS_SYNC_URL: ${{ vars.FIRSTRADE_ACCOUNT_FACTS_SYNC_URL }} + QSL_CONSOLE_BASE_URL: ${{ vars.QSL_CONSOLE_BASE_URL }} EXECUTION_EVIDENCE_SYNC_TOKEN: ${{ secrets.EXECUTION_EVIDENCE_SYNC_TOKEN }} RUNTIME_TARGET_JSON: ${{ secrets.RUNTIME_TARGET_JSON }} steps: diff --git a/.github/workflows/ft-adopt-facts-revision.yml b/.github/workflows/ft-adopt-facts-revision.yml index 32d4a5e..8f197de 100644 --- a/.github/workflows/ft-adopt-facts-revision.yml +++ b/.github/workflows/ft-adopt-facts-revision.yml @@ -32,6 +32,9 @@ jobs: CLOUD_RUN_REGION: ${{ vars.CLOUD_RUN_REGION }} CLOUD_RUN_SERVICE: ${{ secrets.CLOUD_RUN_SERVICE }} EXPECTED_SHA: ${{ inputs.expected_sha }} + QSL_CONSOLE_BASE_URL: ${{ vars.QSL_CONSOLE_BASE_URL }} + EXECUTION_EVIDENCE_SYNC_URL: ${{ vars.EXECUTION_EVIDENCE_SYNC_URL }} + APPROVED_ACCOUNT_FACTS_SYNC_URL: ${{ vars.FIRSTRADE_ACCOUNT_FACTS_SYNC_URL }} steps: - name: Validate source run: | @@ -73,6 +76,7 @@ jobs: rev_json="$(gcloud run revisions describe "${revision}" --region="${CLOUD_RUN_REGION}" --format=json)" REVISION_JSON="${rev_json}" EXPECTED_SHA="${EXPECTED_SHA}" python3 - <<'PY' import json, os, re, sys + from urllib.parse import urlsplit rev=json.loads(os.environ["REVISION_JSON"]) expected=os.environ["EXPECTED_SHA"] labels=((rev.get("metadata") or {}).get("labels") or {}) @@ -96,14 +100,57 @@ jobs: def has_value_or_secret(row): return bool((row or {}).get("value")) or has_secret_ref(row or {}) + host_re = re.compile(r"(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}\Z", re.ASCII) + + def resolve_origin(raw, allowed_paths): + if not raw or raw != raw.strip() or any(ord(c) < 0x20 or ord(c) == 0x7F for c in raw): + return None + try: + parsed = urlsplit(raw) + port = parsed.port + except ValueError: + return None + host = parsed.hostname or "" + if ( + parsed.scheme != "https" + or not host + or parsed.netloc != host + or parsed.username is not None + or parsed.password is not None + or port is not None + or parsed.path not in allowed_paths + or parsed.query + or parsed.fragment + or host_re.fullmatch(host) is None + ): + return None + return f"https://{host}" + + raw_origin = os.environ.get("QSL_CONSOLE_BASE_URL") or "" + if raw_origin: + expected_origin = resolve_origin(raw_origin, {""}) + else: + expected_origin = resolve_origin( + os.environ.get("EXECUTION_EVIDENCE_SYNC_URL") or "", + {"", "/", "/api/execution-evidence/sync"}, + ) + if not expected_origin: + print("approved_origin_invalid", file=sys.stderr); sys.exit(1) + expected_url = f"{expected_origin}/api/account-facts/sync" + if (os.environ.get("APPROVED_ACCOUNT_FACTS_SYNC_URL") or "") != expected_url: + print("approved_sync_url_invalid", file=sys.stderr); sys.exit(1) + enabled=(values.get("FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED") or {}).get("value") url=(values.get("FIRSTRADE_ACCOUNT_FACTS_SYNC_URL") or {}).get("value") + console_origin=(values.get("QSL_CONSOLE_BASE_URL") or {}).get("value") token=values.get("FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN") needed=["FIRSTRADE_ACCOUNT_FACTS_TARGET_ID","FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID","FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY","FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_SCOPE"] if enabled != "true": print(f"sync_not_enabled value={enabled!r}", file=sys.stderr); sys.exit(1) - if url != "https://qsl-strategy-switch-console.pigbibi-e06.workers.dev/api/account-facts/sync": + if url != expected_url: print("sync_url_invalid", file=sys.stderr); sys.exit(1) + if console_origin != expected_origin: + print("console_origin_invalid", file=sys.stderr); sys.exit(1) if not has_secret_ref(token): keys=sorted((token or {}).keys()) print(f"sync_token_missing keys={keys}", file=sys.stderr); sys.exit(1) diff --git a/.github/workflows/publish-archived-account-history.yml b/.github/workflows/publish-archived-account-history.yml index c859ace..4f22750 100644 --- a/.github/workflows/publish-archived-account-history.yml +++ b/.github/workflows/publish-archived-account-history.yml @@ -34,6 +34,8 @@ jobs: CLOUD_RUN_SERVICE: ${{ secrets.CLOUD_RUN_SERVICE }} FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED: ${{ vars.FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED }} FIRSTRADE_ACCOUNT_FACTS_SYNC_URL: ${{ vars.FIRSTRADE_ACCOUNT_FACTS_SYNC_URL }} + QSL_CONSOLE_BASE_URL: ${{ vars.QSL_CONSOLE_BASE_URL }} + EXECUTION_EVIDENCE_SYNC_URL: ${{ vars.EXECUTION_EVIDENCE_SYNC_URL }} FIRSTRADE_ACCOUNT_FACTS_TARGET_ID: ${{ secrets.FIRSTRADE_ACCOUNT_FACTS_TARGET_ID }} FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID: ${{ secrets.FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID }} FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY: ${{ secrets.FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY }} diff --git a/.github/workflows/publish-runtime-daily-once.yml b/.github/workflows/publish-runtime-daily-once.yml index 5de1e7d..14af8b0 100644 --- a/.github/workflows/publish-runtime-daily-once.yml +++ b/.github/workflows/publish-runtime-daily-once.yml @@ -39,6 +39,8 @@ jobs: FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID: ${{ secrets.FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID }} EXECUTION_REPORT_GCS_URI: ${{ vars.EXECUTION_REPORT_GCS_URI || secrets.EXECUTION_REPORT_GCS_URI }} EXECUTION_EVIDENCE_SYNC_URL: ${{ vars.EXECUTION_EVIDENCE_SYNC_URL }} + FIRSTRADE_ACCOUNT_FACTS_SYNC_URL: ${{ vars.FIRSTRADE_ACCOUNT_FACTS_SYNC_URL }} + QSL_CONSOLE_BASE_URL: ${{ vars.QSL_CONSOLE_BASE_URL }} EXECUTION_EVIDENCE_SYNC_TOKEN: ${{ secrets.EXECUTION_EVIDENCE_SYNC_TOKEN }} CLOUD_RUN_SERVICE: ${{ secrets.CLOUD_RUN_SERVICE }} CLOUD_RUN_REGION: ${{ vars.CLOUD_RUN_REGION }} diff --git a/.github/workflows/runtime-target-lifecycle.yml b/.github/workflows/runtime-target-lifecycle.yml index 7526002..f3ee37d 100644 --- a/.github/workflows/runtime-target-lifecycle.yml +++ b/.github/workflows/runtime-target-lifecycle.yml @@ -227,6 +227,8 @@ jobs: env: CLOUD_RUN_REGION: ${{ vars.CLOUD_RUN_REGION }} CLOUD_RUN_SERVICE: ${{ secrets.CLOUD_RUN_SERVICE }} + QSL_CONSOLE_BASE_URL: ${{ vars.QSL_CONSOLE_BASE_URL }} + EXECUTION_EVIDENCE_SYNC_URL: ${{ vars.EXECUTION_EVIDENCE_SYNC_URL }} steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 diff --git a/.github/workflows/sync-cloud-run-env.yml b/.github/workflows/sync-cloud-run-env.yml index c5b39c9..e5bf744 100644 --- a/.github/workflows/sync-cloud-run-env.yml +++ b/.github/workflows/sync-cloud-run-env.yml @@ -77,6 +77,8 @@ jobs: GCP_WORKLOAD_IDENTITY_SERVICE_ACCOUNT: firstrade-platform-deploy@firstradequant.iam.gserviceaccount.com FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED: ${{ vars.FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED }} FIRSTRADE_ACCOUNT_FACTS_SYNC_URL: ${{ vars.FIRSTRADE_ACCOUNT_FACTS_SYNC_URL }} + QSL_CONSOLE_BASE_URL: ${{ vars.QSL_CONSOLE_BASE_URL }} + EXECUTION_EVIDENCE_SYNC_URL: ${{ vars.EXECUTION_EVIDENCE_SYNC_URL }} FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN_SECRET_NAME: ${{ vars.FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN_SECRET_NAME }} FIRSTRADE_ACCOUNT_FACTS_TARGET_ID: ${{ secrets.FIRSTRADE_ACCOUNT_FACTS_TARGET_ID }} FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID: ${{ secrets.FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID }} @@ -190,7 +192,8 @@ jobs: REVISION_JSON: ${{ runner.temp }}/account-facts-revision-after.json run: | set -euo pipefail - env_updates="^|^FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED=${FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED}|FIRSTRADE_ACCOUNT_FACTS_SYNC_URL=${FIRSTRADE_ACCOUNT_FACTS_SYNC_URL}|FIRSTRADE_ACCOUNT_FACTS_TARGET_ID=${FIRSTRADE_ACCOUNT_FACTS_TARGET_ID}|FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID=${FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID}|FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY=${FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY}|FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_SCOPE=${FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_SCOPE}" + resolved_console_origin="$(python3 scripts/account_facts_config_sync.py origin)" + env_updates="^|^FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED=${FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED}|FIRSTRADE_ACCOUNT_FACTS_SYNC_URL=${FIRSTRADE_ACCOUNT_FACTS_SYNC_URL}|QSL_CONSOLE_BASE_URL=${resolved_console_origin}|FIRSTRADE_ACCOUNT_FACTS_TARGET_ID=${FIRSTRADE_ACCOUNT_FACTS_TARGET_ID}|FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID=${FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID}|FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY=${FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY}|FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_SCOPE=${FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_SCOPE}" secret_updates="^|^FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN=${FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN_SECRET_NAME}:latest" if ! gcloud run services update "${CLOUD_RUN_SERVICE}" \ --project="${GCP_PROJECT_ID}" --region="${CLOUD_RUN_REGION}" \ @@ -532,6 +535,8 @@ jobs: FIRSTRADE_MFA_CODE_SECRET_NAME: ${{ vars.FIRSTRADE_MFA_CODE_SECRET_NAME }} FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED: ${{ vars.FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED }} FIRSTRADE_ACCOUNT_FACTS_SYNC_URL: ${{ vars.FIRSTRADE_ACCOUNT_FACTS_SYNC_URL }} + QSL_CONSOLE_BASE_URL: ${{ vars.QSL_CONSOLE_BASE_URL }} + EXECUTION_EVIDENCE_SYNC_URL: ${{ vars.EXECUTION_EVIDENCE_SYNC_URL }} FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN_SECRET_NAME: ${{ vars.FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN_SECRET_NAME }} FIRSTRADE_ACCOUNT_FACTS_TARGET_ID: ${{ secrets.FIRSTRADE_ACCOUNT_FACTS_TARGET_ID }} FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID: ${{ secrets.FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID }} diff --git a/README.md b/README.md index de388a6..1ff142c 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,7 @@ The existing daily Execution Report Heartbeat also invokes this snapshot path on The Cloud Run service must remain IAM-protected. The caller needs `roles/run.invoker` and must send its Google-signed ID token in `X-Serverless-Authorization`; the separate application token goes in `Authorization: Bearer …`. See [Cloud Run service-to-service authentication](https://cloud.google.com/run/docs/authenticating/service-to-service). Neither token is a Firstrade credential. -Configure the following only through protected Cloud Run environment variables and Secret Manager references: `FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED`, `FIRSTRADE_ACCOUNT_FACTS_SYNC_URL` (must equal the approved sync URL defined as `_APPROVED_SYNC_URL` in `src/firstrade_platform/application/account_facts_publisher.py`), `FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN` (a dedicated secret), `FIRSTRADE_ACCOUNT_FACTS_TARGET_ID`, `FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID`, `FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY`, and `FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_SCOPE`. The account identity is taken from the single exact selector in the protected runtime target; if `FIRSTRADE_ACCOUNT` is also set, it must match. All values must match the trusted QRS binding and current runtime target. Do not derive or invent a binding ID. +Configure the following only through protected Cloud Run environment variables and Secret Manager references: `FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED`, `QSL_CONSOLE_BASE_URL` (the approved HTTPS console origin; when unset in workflows, the canonical HTTPS origin is extracted and validated from `vars.EXECUTION_EVIDENCE_SYNC_URL`), `FIRSTRADE_ACCOUNT_FACTS_SYNC_URL` (must equal `resolve_approved_sync_url` in `src/firstrade_platform/application/account_facts_publisher.py`, i.e. `/api/account-facts/sync`), `FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN` (a dedicated secret), `FIRSTRADE_ACCOUNT_FACTS_TARGET_ID`, `FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID`, `FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY`, and `FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_SCOPE`. The account identity is taken from the single exact selector in the protected runtime target; if `FIRSTRADE_ACCOUNT` is also set, it must match. All values must match the trusted QRS binding and current runtime target. Do not derive or invent a binding ID. The existing manual Cloud Run environment sync carries the six non-token settings through the selected Firstrade target's `env` configuration in `CLOUD_RUN_SERVICE_TARGETS_JSON`; the legacy single-service path can use matching `FIRSTRADE_ACCOUNT_FACTS_*` inputs. Keep target, binding, account key, and scope in protected GitHub configuration. Set the protected GitHub variable `FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN_SECRET_NAME` to the name of the already-approved Secret Manager secret. The workflow maps that Secret Manager reference to `FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN`; it never accepts a raw token value from GitHub Actions. Keep the enable switch unset or `false` until deployment adoption is separately reviewed. This source change does not apply Cloud Run configuration or establish deployment adoption. diff --git a/README.zh-CN.md b/README.zh-CN.md index b4e89e7..e59a889 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -54,7 +54,7 @@ FirstradePlatform 是 QuantStrategyLab 的实验性 Firstrade 执行平台。实 Cloud Run 服务必须继续受 IAM 保护。调用方需要 `roles/run.invoker`,并把 Google 签名的 ID token 放在 `X-Serverless-Authorization`;独立的应用 token 放在 `Authorization: Bearer …`。参见 [Cloud Run 服务间认证文档](https://cloud.google.com/run/docs/authenticating/service-to-service)。这两种 token 都不是 Firstrade 凭据。 -以下配置只能通过受保护的 Cloud Run 环境变量和 Secret Manager 引用配置:`FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED`、`FIRSTRADE_ACCOUNT_FACTS_SYNC_URL`(必须与 `src/firstrade_platform/application/account_facts_publisher.py` 中 `_APPROVED_SYNC_URL` 定义的已批准同步地址完全一致)、`FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN`(专用 secret)、`FIRSTRADE_ACCOUNT_FACTS_TARGET_ID`、`FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID`、`FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY` 和 `FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_SCOPE`。账户身份复用受保护 runtime target 中唯一且精确的 selector;若同时设置 `FIRSTRADE_ACCOUNT`,它必须完全匹配。所有值都必须与 QRS 可信绑定及当前 runtime target 一致;不要推导或编造 binding ID。 +以下配置只能通过受保护的 Cloud Run 环境变量和 Secret Manager 引用配置:`FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED`、`QSL_CONSOLE_BASE_URL`(受保护的 HTTPS 控制台 origin;工作流未单独设置时,从 `vars.EXECUTION_EVIDENCE_SYNC_URL` 提取并校验规范 HTTPS origin)、`FIRSTRADE_ACCOUNT_FACTS_SYNC_URL`(必须与 `src/firstrade_platform/application/account_facts_publisher.py` 中 `resolve_approved_sync_url` 计算出的 `/api/account-facts/sync` 完全一致)、`FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN`(专用 secret)、`FIRSTRADE_ACCOUNT_FACTS_TARGET_ID`、`FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID`、`FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY` 和 `FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_SCOPE`。账户身份复用受保护 runtime target 中唯一且精确的 selector;若同时设置 `FIRSTRADE_ACCOUNT`,它必须完全匹配。所有值都必须与 QRS 可信绑定及当前 runtime target 一致;不要推导或编造 binding ID。 现有手动 Cloud Run 环境同步会从 `CLOUD_RUN_SERVICE_TARGETS_JSON` 中所选 Firstrade target 的 `env` 配置传递六个非 token 项;单服务旧配置路径也可使用匹配的 `FIRSTRADE_ACCOUNT_FACTS_*` 输入。target、binding、account key 和 scope 放在受保护的 GitHub 配置中。受保护的 GitHub variable `FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN_SECRET_NAME` 只填写已批准 Secret Manager secret 的名称;workflow 只把这个 Secret Manager 引用映射到 `FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN`,不会接受 GitHub Actions 传入的明文 token。部署另行审查和采用前,启用开关应保持未设置或 `false`。本次源码修改没有应用 Cloud Run 配置,也不代表部署已采用。 diff --git a/scripts/account_facts_config_sync.py b/scripts/account_facts_config_sync.py index 465cdc3..2f9ac8b 100644 --- a/scripts/account_facts_config_sync.py +++ b/scripts/account_facts_config_sync.py @@ -12,12 +12,22 @@ import sys from collections.abc import Mapping from typing import Any +from urllib.parse import urlsplit -APPROVED_SYNC_URL = "https://qsl-strategy-switch-console.pigbibi-e06.workers.dev/api/account-facts/sync" +ACCOUNT_FACTS_SYNC_PATH = "/api/account-facts/sync" +APPROVED_CONSOLE_BASE_URL_ENV = "QSL_CONSOLE_BASE_URL" +EXECUTION_EVIDENCE_SYNC_URL_ENV = "EXECUTION_EVIDENCE_SYNC_URL" +_EXPLICIT_ORIGIN_PATHS = frozenset({""}) +_FALLBACK_EVIDENCE_PATHS = frozenset({"", "/", "/api/execution-evidence/sync"}) +_CONSOLE_HOST_RE = re.compile( + r"(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}\Z", + re.ASCII, +) FACTS_ENV_KEYS = ( "FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED", "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL", + "QSL_CONSOLE_BASE_URL", "FIRSTRADE_ACCOUNT_FACTS_TARGET_ID", "FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID", "FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY", @@ -53,11 +63,52 @@ def _required(name: str) -> str: return value +def _parse_console_origin(raw: object, *, allowed_paths: frozenset[str]) -> str: + if not isinstance(raw, str) or not raw or raw != raw.strip(): + raise ConfigSyncError("destination_not_approved") + if any(ord(char) < 0x20 or ord(char) == 0x7F for char in raw): + raise ConfigSyncError("destination_not_approved") + try: + parsed = urlsplit(raw) + port = parsed.port + except ValueError: + raise ConfigSyncError("destination_not_approved") from None + host = parsed.hostname or "" + if ( + parsed.scheme != "https" + or not host + or parsed.netloc != host + or parsed.username is not None + or parsed.password is not None + or port is not None + or parsed.path not in allowed_paths + or parsed.query + or parsed.fragment + or _CONSOLE_HOST_RE.fullmatch(host) is None + ): + raise ConfigSyncError("destination_not_approved") + return f"https://{host}" + + +def approved_console_origin(environ: Mapping[str, str] | None = None) -> str: + env = os.environ if environ is None else environ + raw_origin = env.get(APPROVED_CONSOLE_BASE_URL_ENV) + if raw_origin is not None and raw_origin != "": + return _parse_console_origin(raw_origin, allowed_paths=_EXPLICIT_ORIGIN_PATHS) + raw_fallback = env.get(EXECUTION_EVIDENCE_SYNC_URL_ENV) + if raw_fallback is not None and raw_fallback != "": + return _parse_console_origin(raw_fallback, allowed_paths=_FALLBACK_EVIDENCE_PATHS) + raise ConfigSyncError("destination_not_approved") + + def desired_facts_config() -> dict[str, str]: enabled = _required("FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED") if enabled not in {"true", "false"}: raise ConfigSyncError("configuration_invalid") - if _required("FIRSTRADE_ACCOUNT_FACTS_SYNC_URL") != APPROVED_SYNC_URL: + sync_url = _required("FIRSTRADE_ACCOUNT_FACTS_SYNC_URL") + console_origin = approved_console_origin() + approved_sync_url = f"{console_origin}{ACCOUNT_FACTS_SYNC_PATH}" + if sync_url != approved_sync_url: raise ConfigSyncError("destination_not_approved") target_id = _required("FIRSTRADE_ACCOUNT_FACTS_TARGET_ID") binding_id = _required("FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID") @@ -76,7 +127,8 @@ def desired_facts_config() -> dict[str, str]: raise ConfigSyncError("secret_reference_invalid") return { "FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED": enabled, - "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": APPROVED_SYNC_URL, + "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": approved_sync_url, + "QSL_CONSOLE_BASE_URL": console_origin, "FIRSTRADE_ACCOUNT_FACTS_TARGET_ID": target_id, "FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID": binding_id, "FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY": account_key, @@ -475,7 +527,7 @@ def _load_stdin() -> Mapping[str, Any]: def main() -> int: parser = argparse.ArgumentParser() - parser.add_argument("mode", choices=("config", "before", "revision", "after")) + parser.add_argument("mode", choices=("config", "origin", "before", "revision", "after")) parser.add_argument("--service", default=os.environ.get("CLOUD_RUN_SERVICE", "")) parser.add_argument("--expected-sha", default=os.environ.get("EXPECTED_SHA", "")) args = parser.parse_args() @@ -484,6 +536,9 @@ def main() -> int: desired_facts_config() print("account_facts_config_validated=true") return 0 + if args.mode == "origin": + print(desired_facts_config()["QSL_CONSOLE_BASE_URL"]) + return 0 payload = _load_stdin() if not args.service: raise ConfigSyncError("service_target_unavailable") diff --git a/scripts/build_cloud_run_env_sync_plan.py b/scripts/build_cloud_run_env_sync_plan.py index 57b1747..649ff41 100644 --- a/scripts/build_cloud_run_env_sync_plan.py +++ b/scripts/build_cloud_run_env_sync_plan.py @@ -42,6 +42,10 @@ def _should_add_local_src(candidate: Path) -> bool: from scripts.cloud_run_tag_preflight import validate_diagnostic +from firstrade_platform.application.account_facts_publisher import ( # noqa: E402 + AccountFactsPublishError, + resolve_approved_console_origin, +) from firstrade_platform.strategy_registry import ( # noqa: E402 FIRSTRADE_PLATFORM, get_platform_profile_status_matrix, @@ -66,6 +70,7 @@ def _should_add_local_src(candidate: Path) -> bool: { "FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED", "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL", + "QSL_CONSOLE_BASE_URL", "FIRSTRADE_ACCOUNT_FACTS_TARGET_ID", "FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID", "FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY", @@ -85,6 +90,7 @@ def _should_add_local_src(candidate: Path) -> bool: "FIRSTRADE_ENABLE_LIVE_TRADING", "FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED", "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL", + "QSL_CONSOLE_BASE_URL", "FIRSTRADE_ACCOUNT_FACTS_TARGET_ID", "FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID", "FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY", @@ -505,6 +511,26 @@ def _build_target_plan( override_value = overrides.get(name) or overrides.get(name.lower()) if override_value is not None: value = _coerce_env_value(override_value) + if name == "QSL_CONSOLE_BASE_URL": + if value is not None: + try: + value = resolve_approved_console_origin({"QSL_CONSOLE_BASE_URL": value}) + except AccountFactsPublishError: + raise ValueError( + f"Target {service_name} QSL_CONSOLE_BASE_URL is invalid" + ) from None + elif ( + (not per_service_mode or is_current_firstrade_facts_target) + and env.get("EXECUTION_EVIDENCE_SYNC_URL") + ): + try: + value = resolve_approved_console_origin( + {"EXECUTION_EVIDENCE_SYNC_URL": env["EXECUTION_EVIDENCE_SYNC_URL"]} + ) + except AccountFactsPublishError: + raise ValueError( + f"Target {service_name} EXECUTION_EVIDENCE_SYNC_URL fallback origin is invalid" + ) from None if value is None: remove_env_vars.append(name) diff --git a/scripts/inspect_account_data_readiness.py b/scripts/inspect_account_data_readiness.py index 1f7a9e9..631d757 100644 --- a/scripts/inspect_account_data_readiness.py +++ b/scripts/inspect_account_data_readiness.py @@ -21,7 +21,86 @@ REGION_RE = re.compile(REGION_PATH_PATTERN + r"\Z") COMMIT_RE = re.compile(r"[0-9a-fA-F]{40}\Z") MAX_RESPONSE_BYTES = 2_000_000 -ACCOUNT_FACTS_DESTINATION = "https://qsl-strategy-switch-console.pigbibi-e06.workers.dev/api/account-facts/sync" +ACCOUNT_FACTS_SYNC_PATH = "/api/account-facts/sync" +APPROVED_CONSOLE_BASE_URL_ENV = "QSL_CONSOLE_BASE_URL" +EXECUTION_EVIDENCE_SYNC_URL_ENV = "EXECUTION_EVIDENCE_SYNC_URL" +_EXPLICIT_ORIGIN_PATHS = frozenset({""}) +_FALLBACK_EVIDENCE_PATHS = frozenset({"", "/", "/api/execution-evidence/sync"}) +_CONSOLE_HOST_RE = re.compile( + r"(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}\Z", + re.ASCII, +) + + +def _parse_console_origin(raw: object, *, allowed_paths: frozenset[str]) -> str | None: + if not isinstance(raw, str) or not raw or raw != raw.strip(): + return None + if any(ord(char) < 0x20 or ord(char) == 0x7F for char in raw): + return None + try: + parsed = urllib.parse.urlsplit(raw) + port = parsed.port + except ValueError: + return None + host = parsed.hostname or "" + if ( + parsed.scheme != "https" + or not host + or parsed.netloc != host + or parsed.username is not None + or parsed.password is not None + or port is not None + or parsed.path not in allowed_paths + or parsed.query + or parsed.fragment + or _CONSOLE_HOST_RE.fullmatch(host) is None + ): + return None + return f"https://{host}" + + +def _approved_account_facts_destination(environ: Mapping[str, str] | None = None) -> str | None: + env = os.environ if environ is None else environ + raw_origin = env.get(APPROVED_CONSOLE_BASE_URL_ENV) + if raw_origin is not None and raw_origin != "": + origin = _parse_console_origin(raw_origin, allowed_paths=_EXPLICIT_ORIGIN_PATHS) + else: + raw_fallback = env.get(EXECUTION_EVIDENCE_SYNC_URL_ENV) + origin = ( + _parse_console_origin(raw_fallback, allowed_paths=_FALLBACK_EVIDENCE_PATHS) + if raw_fallback is not None and raw_fallback != "" + else None + ) + if origin is None: + return None + return f"{origin}{ACCOUNT_FACTS_SYNC_PATH}" + + +def _validated_account_facts_destination(value: object) -> str | None: + if not isinstance(value, str) or not value or value != value.strip(): + return None + if any(ord(char) < 0x20 or ord(char) == 0x7F for char in value): + return None + try: + parsed = urllib.parse.urlsplit(value) + port = parsed.port + except ValueError: + return None + host = parsed.hostname or "" + if ( + parsed.scheme != "https" + or not host + or parsed.netloc != host + or parsed.username is not None + or parsed.password is not None + or port is not None + or parsed.path != ACCOUNT_FACTS_SYNC_PATH + or parsed.query + or parsed.fragment + or _CONSOLE_HOST_RE.fullmatch(host) is None + ): + return None + return f"https://{host}{ACCOUNT_FACTS_SYNC_PATH}" class DiagnosticFailure(Exception): @@ -292,7 +371,11 @@ def _effective_selector_configuration( return direct_configured, f"first_trade_account_{direct_source}" -def _account_data_configuration(revision: Mapping[str, Any]) -> dict[str, Any]: +def _account_data_configuration( + revision: Mapping[str, Any], + *, + approved_destination: str | None = None, +) -> dict[str, Any]: """Describe serving settings, without resolving secrets or claiming session health.""" containers = revision.get("containers") if not isinstance(containers, list) or len(containers) != 1: @@ -330,6 +413,11 @@ def flag(name: str) -> bool | None: destination = entry("FIRSTRADE_ACCOUNT_FACTS_SYNC_URL") destination_kind = source(destination) + expected_destination = ( + _validated_account_facts_destination(approved_destination) + if approved_destination is not None + else _approved_account_facts_destination() + ) binding_sources = [source(entry(name)) for name in ( "FIRSTRADE_ACCOUNT_FACTS_TARGET_ID", "FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID", "FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY", "FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_SCOPE", @@ -337,7 +425,7 @@ def flag(name: str) -> bool | None: return { "sync_enabled": flag("FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED"), "approved_destination_configured": ( - destination.get("value") == ACCOUNT_FACTS_DESTINATION + bool(expected_destination) and destination.get("value") == expected_destination if destination_kind == "literal" else None if destination_kind == "secret_reference" else False ), "binding_settings_configured": all(kind != "absent" for kind in binding_sources), @@ -356,6 +444,7 @@ def inspect_readiness( token: str, *, request_json: Callable[[str, str], Mapping[str, Any]] = _request_json, + approved_destination: str | None = None, ) -> dict[str, Any]: service_name = _safe_resource_part(service_name, SERVICE_NAME_RE) region = _safe_resource_part(region, REGION_RE) @@ -385,7 +474,9 @@ def inspect_readiness( selector_nonempty, effective_selector_source = _effective_selector_configuration( revision, (selector_configured, selector_source) ) - account_data_configuration = _account_data_configuration(revision) + account_data_configuration = _account_data_configuration( + revision, approved_destination=approved_destination + ) after = request_json(service_url, token) if after.get("name") != service_path: raise DiagnosticFailure("service_identity_mismatch") diff --git a/scripts/publish_runtime_daily.py b/scripts/publish_runtime_daily.py index 34c5bc1..1883387 100644 --- a/scripts/publish_runtime_daily.py +++ b/scripts/publish_runtime_daily.py @@ -14,7 +14,12 @@ from scripts import execution_report_heartbeat as heartbeat from scripts.project_runtime_daily import PLATFORM, project_runtime_daily -from firstrade_platform.application.account_facts_publisher import _APPROVED_SYNC_URL as _FACTS_URL +from firstrade_platform.application.account_facts_publisher import ( + ACCOUNT_FACTS_SYNC_PATH, + AccountFactsPublishError, + _CONSOLE_HOST_RE, + resolve_approved_console_origin, +) class _NoRedirect(HTTPRedirectHandler): @@ -58,13 +63,59 @@ def _read_reports(day, now, project): return [], "list_failed" +def _parse_facts_origin(raw: str) -> str: + if not isinstance(raw, str) or not raw or raw != raw.strip(): + raise ValueError("daily_origin_invalid") + if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in raw): + raise ValueError("daily_origin_invalid") + try: + parsed = urlsplit(raw) + port = parsed.port + except ValueError: + raise ValueError("daily_origin_invalid") from None + host = parsed.hostname or "" + if ( + parsed.scheme != "https" + or not host + or parsed.netloc != host + or parsed.username is not None + or parsed.password is not None + or port is not None + or parsed.path != ACCOUNT_FACTS_SYNC_PATH + or parsed.query + or parsed.fragment + or _CONSOLE_HOST_RE.fullmatch(host) is None + ): + raise ValueError("daily_origin_invalid") + return f"https://{host}" + + +def _approved_origin(env): + configured_origin = None + if env.get("QSL_CONSOLE_BASE_URL"): + try: + configured_origin = resolve_approved_console_origin(env) + except AccountFactsPublishError: + raise ValueError("daily_origin_invalid") from None + facts_origin = None + if env.get("FIRSTRADE_ACCOUNT_FACTS_SYNC_URL"): + facts_origin = _parse_facts_origin(env["FIRSTRADE_ACCOUNT_FACTS_SYNC_URL"]) + if configured_origin and facts_origin and configured_origin != facts_origin: + raise ValueError("daily_origin_invalid") + origin = configured_origin or facts_origin + if not origin: + raise ValueError("daily_origin_invalid") + return origin + + def _auth_config(env): token = env.get("EXECUTION_EVIDENCE_SYNC_TOKEN") url = urlsplit(env.get("EXECUTION_EVIDENCE_SYNC_URL") or "") if (not token or token != token.strip() or url.scheme != "https" or not url.hostname or url.username or url.password or url.query or url.fragment): raise ValueError("daily_config_invalid") - if url.netloc != urlsplit(_FACTS_URL).netloc: + expected_origin = _approved_origin(env) + if url.netloc != urlsplit(expected_origin).netloc: raise ValueError("daily_origin_invalid") return token, f"https://{url.netloc}" diff --git a/src/firstrade_platform/application/account_facts_publisher.py b/src/firstrade_platform/application/account_facts_publisher.py index b5d0e5d..6b2f21a 100644 --- a/src/firstrade_platform/application/account_facts_publisher.py +++ b/src/firstrade_platform/application/account_facts_publisher.py @@ -14,7 +14,15 @@ from firstrade_platform.application.account_facts_readonly import AccountFactsUnavailable -_APPROVED_SYNC_URL = "https://qsl-strategy-switch-console.pigbibi-e06.workers.dev/api/account-facts/sync" +ACCOUNT_FACTS_SYNC_PATH = "/api/account-facts/sync" +APPROVED_CONSOLE_BASE_URL_ENV = "QSL_CONSOLE_BASE_URL" +EXECUTION_EVIDENCE_SYNC_URL_ENV = "EXECUTION_EVIDENCE_SYNC_URL" +_EXPLICIT_ORIGIN_PATHS = frozenset({""}) +_FALLBACK_EVIDENCE_PATHS = frozenset({"", "/", "/api/execution-evidence/sync"}) +_CONSOLE_HOST_RE = re.compile( + r"(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}\Z", + re.ASCII, +) _TARGET_ID_RE = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?", re.ASCII) _ACCOUNT_KEY_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:-]*", re.ASCII) _ACCOUNT_SCOPE_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:-]*", re.ASCII) @@ -60,6 +68,49 @@ def _required_env(env: Mapping[str, str], key: str) -> str: return value +def _parse_approved_console_origin(raw: object, *, allowed_paths: frozenset[str]) -> str: + if not isinstance(raw, str) or not raw or raw != raw.strip(): + raise AccountFactsPublishError("destination_not_approved") + if any(ord(char) < 0x20 or ord(char) == 0x7F for char in raw): + raise AccountFactsPublishError("destination_not_approved") + try: + parsed = urlsplit(raw) + port = parsed.port + except ValueError: + raise AccountFactsPublishError("destination_not_approved") from None + host = parsed.hostname or "" + if ( + parsed.scheme != "https" + or not host + or parsed.netloc != host + or parsed.username is not None + or parsed.password is not None + or port is not None + or parsed.path not in allowed_paths + or parsed.query + or parsed.fragment + or _CONSOLE_HOST_RE.fullmatch(host) is None + ): + raise AccountFactsPublishError("destination_not_approved") + return f"https://{host}" + + +def resolve_approved_console_origin(env: Mapping[str, str]) -> str: + """Load and validate the approved HTTPS console origin from env.""" + raw_origin = env.get(APPROVED_CONSOLE_BASE_URL_ENV) + if raw_origin is not None and raw_origin != "": + return _parse_approved_console_origin(raw_origin, allowed_paths=_EXPLICIT_ORIGIN_PATHS) + raw_fallback = env.get(EXECUTION_EVIDENCE_SYNC_URL_ENV) + if raw_fallback is not None and raw_fallback != "": + return _parse_approved_console_origin(raw_fallback, allowed_paths=_FALLBACK_EVIDENCE_PATHS) + raise AccountFactsPublishError("destination_not_approved") + + +def resolve_approved_sync_url(env: Mapping[str, str]) -> str: + """Return the exact approved account-facts sync URL from protected config.""" + return f"{resolve_approved_console_origin(env)}{ACCOUNT_FACTS_SYNC_PATH}" + + def load_account_facts_publish_config( env: Mapping[str, str], *, @@ -70,15 +121,17 @@ def load_account_facts_publish_config( raise AccountFactsPublishError("disabled") sync_url = _required_env(env, "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL") + approved_sync_url = resolve_approved_sync_url(env) + approved_netloc = urlsplit(approved_sync_url).netloc try: parsed = urlsplit(sync_url) except ValueError: raise AccountFactsPublishError("destination_not_approved") from None if ( - sync_url != _APPROVED_SYNC_URL + sync_url != approved_sync_url or parsed.scheme != "https" - or parsed.netloc != "qsl-strategy-switch-console.pigbibi-e06.workers.dev" - or parsed.path != "/api/account-facts/sync" + or parsed.netloc != approved_netloc + or parsed.path != ACCOUNT_FACTS_SYNC_PATH or parsed.query or parsed.fragment or parsed.username diff --git a/tests/test_account_data_readiness.py b/tests/test_account_data_readiness.py index e51e72c..9d72789 100644 --- a/tests/test_account_data_readiness.py +++ b/tests/test_account_data_readiness.py @@ -99,10 +99,13 @@ def test_inspects_only_exact_project_region_service_and_serving_revision() -> No assert all(url.startswith("https://run.googleapis.com/v2/projects/firstradequant/") for url in urls) -def test_serving_facts_settings_are_redacted_and_do_not_prove_session_or_identity() -> None: +def test_serving_facts_settings_are_redacted_and_do_not_prove_session_or_identity(monkeypatch: pytest.MonkeyPatch) -> None: + console_origin = "https://console.example.test" + approved_destination = f"{console_origin}/api/account-facts/sync" + monkeypatch.setenv("QSL_CONSOLE_BASE_URL", console_origin) env = [ {"name": "FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED", "value": "true"}, - {"name": "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL", "value": readiness.ACCOUNT_FACTS_DESTINATION}, + {"name": "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL", "value": approved_destination}, {"name": "FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN", "valueSource": {"secretKeyRef": {"secret": SENTINEL, "version": "latest"}}}, {"name": "FIRSTRADE_REUSE_SESSION", "value": " true "}, {"name": "FIRSTRADE_PERSIST_SESSION_CACHE", "value": "true"}, @@ -125,7 +128,37 @@ def test_serving_facts_settings_are_redacted_and_do_not_prove_session_or_identit assert len(urls) == 3 assert all("run.googleapis.com/v2/" in url for url in urls) assert SENTINEL not in json.dumps(result) - assert readiness.ACCOUNT_FACTS_DESTINATION not in json.dumps(result) + assert approved_destination not in json.dumps(result) + assert "console.example.test" not in json.dumps(result) + + +@pytest.mark.parametrize("origin", [None, "", "http://console.example.test", "https://console.example.test/api/account-facts/sync", "https://console.example.test/extra"]) +def test_missing_or_invalid_approved_origin_fails_closed(monkeypatch: pytest.MonkeyPatch, origin: str | None) -> None: + monkeypatch.delenv("EXECUTION_EVIDENCE_SYNC_URL", raising=False) + if origin is None: + monkeypatch.delenv("QSL_CONSOLE_BASE_URL", raising=False) + else: + monkeypatch.setenv("QSL_CONSOLE_BASE_URL", origin) + result = readiness._account_data_configuration(_revision(env=[ + {"name": "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL", "value": "https://console.example.test/api/account-facts/sync"}, + ])) + assert result["approved_destination_configured"] is False + + +def test_evidence_url_fallback_extracts_origin_while_failing_closed_on_unexpected_paths(monkeypatch: pytest.MonkeyPatch) -> None: + revision = _revision(env=[ + {"name": "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL", "value": "https://console.example.test/api/account-facts/sync"}, + ]) + monkeypatch.setenv("QSL_CONSOLE_BASE_URL", "") + monkeypatch.setenv("EXECUTION_EVIDENCE_SYNC_URL", "https://console.example.test/api/execution-evidence/sync") + assert readiness._account_data_configuration(revision)["approved_destination_configured"] is True + + monkeypatch.setenv("QSL_CONSOLE_BASE_URL", "https://console.example.test/extra") + assert readiness._account_data_configuration(revision)["approved_destination_configured"] is False + + monkeypatch.setenv("QSL_CONSOLE_BASE_URL", "") + monkeypatch.setenv("EXECUTION_EVIDENCE_SYNC_URL", "https://console.example.test/unexpected") + assert readiness._account_data_configuration(revision)["approved_destination_configured"] is False @pytest.mark.parametrize("value", ["invalid-flag", None]) diff --git a/tests/test_account_facts_config_sync.py b/tests/test_account_facts_config_sync.py index 82cd263..cbd8a07 100644 --- a/tests/test_account_facts_config_sync.py +++ b/tests/test_account_facts_config_sync.py @@ -21,10 +21,15 @@ PROJECT_NUMBER = "1088907247379" +SYNTHETIC_CONSOLE_BASE_URL = "https://console.example.test" +SYNTHETIC_SYNC_URL = f"{SYNTHETIC_CONSOLE_BASE_URL}/api/account-facts/sync" + + def _desired(monkeypatch, **overrides): values = { "FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED": "false", - "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": "https://qsl-strategy-switch-console.pigbibi-e06.workers.dev/api/account-facts/sync", + "QSL_CONSOLE_BASE_URL": SYNTHETIC_CONSOLE_BASE_URL, + "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": SYNTHETIC_SYNC_URL, "FIRSTRADE_ACCOUNT_FACTS_TARGET_ID": "synthetic-target", "FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID": "b" * 64, "FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY": "synthetic-account-key", @@ -35,7 +40,10 @@ def _desired(monkeypatch, **overrides): } values.update(overrides) for name, value in values.items(): - monkeypatch.setenv(name, value) + if value is None: + monkeypatch.delenv(name, raising=False) + else: + monkeypatch.setenv(name, value) return desired_facts_config() @@ -97,6 +105,7 @@ def _desired_entries(desired): for name in ( "FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED", "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL", + "QSL_CONSOLE_BASE_URL", "FIRSTRADE_ACCOUNT_FACTS_TARGET_ID", "FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID", "FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY", @@ -125,12 +134,46 @@ def _secret_mapping(alias="facts-token-lookup", *, project_number=PROJECT_NUMBER def test_config_requires_all_fields_and_approved_destination(monkeypatch): monkeypatch.delenv("FIRSTRADE_ACCOUNT_FACTS_SYNC_URL", raising=False) + monkeypatch.delenv("EXECUTION_EVIDENCE_SYNC_URL", raising=False) with pytest.raises(ConfigSyncError, match="configuration_incomplete"): desired_facts_config() with pytest.raises(ConfigSyncError, match="destination_not_approved"): _desired(monkeypatch, FIRSTRADE_ACCOUNT_FACTS_SYNC_URL="https://example.invalid/api") + for bad_origin in (None, "", "http://console.example.test", "https://console.example.test/", "https://console.example.test/extra"): + with pytest.raises(ConfigSyncError, match="destination_not_approved"): + _desired(monkeypatch, QSL_CONSOLE_BASE_URL=bad_origin, EXECUTION_EVIDENCE_SYNC_URL=None) + + +def test_config_extracts_canonical_origin_from_evidence_fallback_and_rejects_invalid(monkeypatch, capsys): + from scripts import account_facts_config_sync as config_sync + + desired = _desired( + monkeypatch, + QSL_CONSOLE_BASE_URL="", + EXECUTION_EVIDENCE_SYNC_URL="https://console.example.test/api/execution-evidence/sync", + ) + assert desired["QSL_CONSOLE_BASE_URL"] == SYNTHETIC_CONSOLE_BASE_URL + assert desired["FIRSTRADE_ACCOUNT_FACTS_SYNC_URL"] == SYNTHETIC_SYNC_URL + + monkeypatch.setattr(config_sync.sys, "argv", ["account_facts_config_sync.py", "origin"]) + assert config_sync.main() == 0 + assert capsys.readouterr().out.strip() == SYNTHETIC_CONSOLE_BASE_URL + + with pytest.raises(ConfigSyncError, match="destination_not_approved"): + _desired( + monkeypatch, + QSL_CONSOLE_BASE_URL="https://console.example.test/extra", + EXECUTION_EVIDENCE_SYNC_URL="https://console.example.test/api/execution-evidence/sync", + ) + with pytest.raises(ConfigSyncError, match="destination_not_approved"): + _desired( + monkeypatch, + QSL_CONSOLE_BASE_URL="", + EXECUTION_EVIDENCE_SYNC_URL="https://console.example.test/unexpected", + ) + def test_only_exact_six_fields_and_secret_reference_change_on_no_traffic_candidate(monkeypatch): desired = _desired(monkeypatch) diff --git a/tests/test_account_facts_endpoint.py b/tests/test_account_facts_endpoint.py index 55e72e8..83a5f26 100644 --- a/tests/test_account_facts_endpoint.py +++ b/tests/test_account_facts_endpoint.py @@ -187,7 +187,8 @@ def flush(self): def _configure(monkeypatch, **overrides): values = { "FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED": "true", - "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": "https://qsl-strategy-switch-console.pigbibi-e06.workers.dev/api/account-facts/sync", + "QSL_CONSOLE_BASE_URL": "https://console.example.test", + "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": "https://console.example.test/api/account-facts/sync", "FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN": "synthetic-facts-token", "FIRSTRADE_ACCOUNT_FACTS_TARGET_ID": "firstrade-live-synthetic", "FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID": "a" * 64, diff --git a/tests/test_account_facts_publisher.py b/tests/test_account_facts_publisher.py index 2050e4a..86531f4 100644 --- a/tests/test_account_facts_publisher.py +++ b/tests/test_account_facts_publisher.py @@ -8,13 +8,19 @@ build_firstrade_account_snapshot, load_account_facts_publish_config, publish_firstrade_account_snapshot, + resolve_approved_console_origin, ) +SYNTHETIC_CONSOLE_BASE_URL = "https://console.example.test" +SYNTHETIC_SYNC_URL = f"{SYNTHETIC_CONSOLE_BASE_URL}/api/account-facts/sync" + + def config(**overrides): values = { "FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED": "true", - "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": "https://qsl-strategy-switch-console.pigbibi-e06.workers.dev/api/account-facts/sync", + "QSL_CONSOLE_BASE_URL": SYNTHETIC_CONSOLE_BASE_URL, + "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": SYNTHETIC_SYNC_URL, "FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN": "synthetic-facts-token", "FIRSTRADE_ACCOUNT_FACTS_TARGET_ID": "firstrade-live-synthetic", "FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID": "a" * 64, @@ -147,9 +153,17 @@ def test_available_cash_never_replaces_missing_exact_cash(missing_key): ("overrides", "reason"), [ ({"FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED": "false"}, "disabled"), - ({"FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": "http://qsl-strategy-switch-console.pigbibi-e06.workers.dev/api/account-facts/sync"}, "destination_not_approved"), - ({"FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": "https://other.example/api/account-facts/sync"}, "destination_not_approved"), - ({"FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": "https://qsl-strategy-switch-console.pigbibi-e06.workers.dev/api/account-facts/sync?next=other"}, "destination_not_approved"), + ({"QSL_CONSOLE_BASE_URL": ""}, "destination_not_approved"), + ({"QSL_CONSOLE_BASE_URL": "http://console.example.test"}, "destination_not_approved"), + ({"QSL_CONSOLE_BASE_URL": "https://console.example.test/api/account-facts/sync"}, "destination_not_approved"), + ({"QSL_CONSOLE_BASE_URL": "https://console.example.test?next=other"}, "destination_not_approved"), + ({"QSL_CONSOLE_BASE_URL": "https://user@console.example.test"}, "destination_not_approved"), + ({"QSL_CONSOLE_BASE_URL": "https://console.example.test:8443"}, "destination_not_approved"), + ({"QSL_CONSOLE_BASE_URL": "https://127.0.0.1"}, "destination_not_approved"), + ({"QSL_CONSOLE_BASE_URL": "https://localhost"}, "destination_not_approved"), + ({"FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": "http://console.example.test/api/account-facts/sync"}, "destination_not_approved"), + ({"FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": "https://other.example.test/api/account-facts/sync"}, "destination_not_approved"), + ({"FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": "https://console.example.test/api/account-facts/sync?next=other"}, "destination_not_approved"), ({"FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID": "A" * 64}, "source_binding_invalid"), ({"FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN": "same", "ACCOUNT_FACTS_SYNC_TOKEN": "same"}, "sync_token_not_dedicated"), ], @@ -159,6 +173,66 @@ def test_config_is_explicit_and_rejects_unapproved_or_aliased_values(overrides, load_account_facts_publish_config(config(**overrides)) +def test_config_fails_closed_when_approved_console_origin_is_absent(): + values = config() + values.pop("QSL_CONSOLE_BASE_URL") + with pytest.raises(AccountFactsPublishError, match="destination_not_approved"): + load_account_facts_publish_config(values) + + +@pytest.mark.parametrize( + "evidence_url", + [ + "https://console.example.test", + "https://console.example.test/", + "https://console.example.test/api/execution-evidence/sync", + ], +) +def test_origin_fallback_extracts_canonical_https_origin_from_evidence_url(evidence_url): + env = config(QSL_CONSOLE_BASE_URL="", EXECUTION_EVIDENCE_SYNC_URL=evidence_url) + assert resolve_approved_console_origin(env) == SYNTHETIC_CONSOLE_BASE_URL + cfg = load_account_facts_publish_config(env) + assert cfg.sync_url == SYNTHETIC_SYNC_URL + + +@pytest.mark.parametrize( + "overrides", + [ + { + "QSL_CONSOLE_BASE_URL": "https://console.example.test/extra", + "EXECUTION_EVIDENCE_SYNC_URL": "https://console.example.test/api/execution-evidence/sync", + }, + { + "QSL_CONSOLE_BASE_URL": "https://console.example.test/api/execution-evidence/sync", + "EXECUTION_EVIDENCE_SYNC_URL": "https://console.example.test/api/execution-evidence/sync", + }, + { + "QSL_CONSOLE_BASE_URL": "", + "EXECUTION_EVIDENCE_SYNC_URL": "https://console.example.test/unexpected", + }, + { + "QSL_CONSOLE_BASE_URL": "", + "EXECUTION_EVIDENCE_SYNC_URL": "http://console.example.test/api/execution-evidence/sync", + }, + { + "QSL_CONSOLE_BASE_URL": "", + "EXECUTION_EVIDENCE_SYNC_URL": "https://console.example.test/api/execution-evidence/sync?x=1", + }, + { + "QSL_CONSOLE_BASE_URL": "", + "EXECUTION_EVIDENCE_SYNC_URL": "https://user@console.example.test/api/execution-evidence/sync", + }, + { + "QSL_CONSOLE_BASE_URL": "", + "EXECUTION_EVIDENCE_SYNC_URL": "https://console.example.test:8443/api/execution-evidence/sync", + }, + ], +) +def test_origin_fallback_rejects_invalid_explicit_origin_or_disallowed_evidence_url(overrides): + with pytest.raises(AccountFactsPublishError, match="destination_not_approved"): + load_account_facts_publish_config(config(**overrides)) + + @pytest.mark.parametrize( "alias_name", [ diff --git a/tests/test_build_cloud_run_env_sync_plan.py b/tests/test_build_cloud_run_env_sync_plan.py index 04fa055..5855dd0 100644 --- a/tests/test_build_cloud_run_env_sync_plan.py +++ b/tests/test_build_cloud_run_env_sync_plan.py @@ -70,7 +70,8 @@ def test_build_cloud_run_env_sync_plan_legacy_mode_without_telegram(): def test_build_cloud_run_env_sync_plan_carries_balance_facts_config_but_not_token_value(): facts_config = { "FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED": "false", - "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": "https://qsl-strategy-switch-console.pigbibi-e06.workers.dev/api/account-facts/sync", + "QSL_CONSOLE_BASE_URL": "https://console.example.test", + "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": "https://console.example.test/api/account-facts/sync", "FIRSTRADE_ACCOUNT_FACTS_TARGET_ID": "synthetic-target", "FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID": "a" * 64, "FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY": "synthetic-account-key", @@ -125,7 +126,8 @@ def test_per_service_facts_config_fallback_applies_only_to_current_firstrade_tar {"defaults": {"NOTIFY_LANG": "en"}, "targets": targets} ), "FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED": "false", - "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": "https://qsl-strategy-switch-console.pigbibi-e06.workers.dev/api/account-facts/sync", + "QSL_CONSOLE_BASE_URL": "https://console.example.test", + "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": "https://console.example.test/api/account-facts/sync", "FIRSTRADE_ACCOUNT_FACTS_TARGET_ID": "synthetic-target", "FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID": "b" * 64, "FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY": "synthetic-account-key", @@ -143,6 +145,7 @@ def test_per_service_facts_config_fallback_applies_only_to_current_firstrade_tar by_service = {item["service_name"]: item for item in json.loads(result.stdout)["targets"]} facts_names = ( "FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED", + "QSL_CONSOLE_BASE_URL", "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL", "FIRSTRADE_ACCOUNT_FACTS_TARGET_ID", "FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID", @@ -155,6 +158,49 @@ def test_per_service_facts_config_fallback_applies_only_to_current_firstrade_tar assert name in by_service[sibling_service]["remove_env_vars"] +def test_sync_plan_extracts_canonical_origin_from_evidence_fallback_and_rejects_bad_urls(): + base_env = { + **os.environ, + "PLATFORM_CONFIG_JSON": '{"strategies":{}}', + "CLOUD_RUN_SERVICE": "firstrade-platform-service", + "NOTIFY_LANG": "en", + "RUNTIME_TARGET_JSON": runtime_target_json( + "tqqq_growth_income", + service_name="firstrade-platform-service", + ), + "FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED": "false", + "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": "https://console.example.test/api/account-facts/sync", + "QSL_CONSOLE_BASE_URL": "", + "EXECUTION_EVIDENCE_SYNC_URL": "https://console.example.test/api/execution-evidence/sync", + "FIRSTRADE_ACCOUNT_FACTS_TARGET_ID": "synthetic-target", + "FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID": "a" * 64, + "FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY": "synthetic-account-key", + "FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_SCOPE": "US", + } + ok = subprocess.run( + [sys.executable, str(SYNC_PLAN_SCRIPT_PATH), "--json"], + check=True, + capture_output=True, + text=True, + env=base_env, + ) + target = json.loads(ok.stdout)["targets"][0] + assert target["env"]["QSL_CONSOLE_BASE_URL"] == "https://console.example.test" + + for bad_patch in ( + {"QSL_CONSOLE_BASE_URL": "https://console.example.test/extra"}, + {"QSL_CONSOLE_BASE_URL": "", "EXECUTION_EVIDENCE_SYNC_URL": "https://console.example.test/unexpected"}, + ): + failed = subprocess.run( + [sys.executable, str(SYNC_PLAN_SCRIPT_PATH), "--json"], + check=False, + capture_output=True, + text=True, + env={**base_env, **bad_patch}, + ) + assert failed.returncode != 0 + + def test_build_cloud_run_env_sync_plan_requires_snapshot_for_snapshot_backed_profile(): env = { **os.environ, diff --git a/tests/test_project_runtime_daily.py b/tests/test_project_runtime_daily.py index dd85637..0c2bcb2 100644 --- a/tests/test_project_runtime_daily.py +++ b/tests/test_project_runtime_daily.py @@ -31,7 +31,6 @@ def test_publish_once_requires_exact_ack_and_never_retries(monkeypatch): from scripts import publish_runtime_daily as publisher monkeypatch.setattr(publisher, "_binding", lambda _env, _target: ("synthetic-key", "a" * 64, "b" * 64)) - monkeypatch.setattr(publisher, "_FACTS_URL", "https://example.test/api/account-facts/sync") report = {"platform": PLATFORM, "service_name": "synthetic-service", "strategy_profile": "synthetic-profile", "account_scope": "live", "run_id": "private-run", "started_at": "2026-10-29T18:00:00Z", "finished_at": "2026-10-29T18:01:00Z", "dry_run": False, "errors": [], "status": "ok", @@ -39,7 +38,8 @@ def test_publish_once_requires_exact_ack_and_never_retries(monkeypatch): "external_cash_flow_interval": {"account_scope_sha256": "a" * 64}} monkeypatch.setattr(publisher, "_read_reports", lambda *_args: ([report], None)) env = {"RUNTIME_TARGET_JSON": json.dumps({"service_name": "synthetic-service", "strategy_profile": "synthetic-profile", "account_scope": "live"}), - "EXECUTION_EVIDENCE_SYNC_TOKEN": "synthetic-token", "EXECUTION_EVIDENCE_SYNC_URL": "https://example.test/api/execution-evidence/sync", + "EXECUTION_EVIDENCE_SYNC_TOKEN": "synthetic-token", "EXECUTION_EVIDENCE_SYNC_URL": "https://console.example.test/api/execution-evidence/sync", + "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": "https://console.example.test/api/account-facts/sync", "RUNTIME_DAILY_BUSINESS_DATE": "2026-10-29"} class Response: status = 200 @@ -62,7 +62,6 @@ def test_matching_ack_is_only_success_and_nested_identity_mismatch_excluded(monk binding = "a" * 64 monkeypatch.setattr(publisher, "_binding", lambda _env, _target: ("synthetic-key", binding, "b" * 64)) - monkeypatch.setattr(publisher, "_FACTS_URL", "https://example.test/api/account-facts/sync") report = {"platform": PLATFORM, "service_name": "synthetic-service", "strategy_profile": "synthetic-profile", "account_scope": "live", "run_id": "private-run", "started_at": "2026-10-29T18:00:00Z", "finished_at": "2026-10-29T18:01:00Z", "dry_run": False, "errors": [], "status": "ok", @@ -70,7 +69,9 @@ def test_matching_ack_is_only_success_and_nested_identity_mismatch_excluded(monk "external_cash_flow_interval": {"account_scope_sha256": "a" * 64}} monkeypatch.setattr(publisher, "_read_reports", lambda *_args: ([report], None)) env = {"RUNTIME_TARGET_JSON": json.dumps({"service_name": "synthetic-service", "strategy_profile": "synthetic-profile", "account_scope": "live"}), - "EXECUTION_EVIDENCE_SYNC_TOKEN": "synthetic-token", "EXECUTION_EVIDENCE_SYNC_URL": "https://example.test/api/execution-evidence/sync", + "EXECUTION_EVIDENCE_SYNC_TOKEN": "synthetic-token", "EXECUTION_EVIDENCE_SYNC_URL": "https://console.example.test/api/execution-evidence/sync", + "QSL_CONSOLE_BASE_URL": "https://console.example.test", + "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": "https://console.example.test/api/account-facts/sync", "RUNTIME_DAILY_BUSINESS_DATE": "2026-10-29"} now = datetime(2026, 10, 29, 20, tzinfo=timezone.utc) class Response: @@ -101,9 +102,9 @@ def test_no_attributable_runs_or_wrong_origin_never_posts(monkeypatch): from scripts import publish_runtime_daily as publisher monkeypatch.setattr(publisher, "_binding", lambda _env, _target: ("synthetic-key", "a" * 64, "b" * 64)) - monkeypatch.setattr(publisher, "_FACTS_URL", "https://example.test/api/account-facts/sync") env = {"RUNTIME_TARGET_JSON": json.dumps({"service_name": "synthetic-service", "strategy_profile": "synthetic-profile", "account_scope": "live"}), - "EXECUTION_EVIDENCE_SYNC_TOKEN": "synthetic-token", "EXECUTION_EVIDENCE_SYNC_URL": "https://example.test/api/execution-evidence/sync", + "EXECUTION_EVIDENCE_SYNC_TOKEN": "synthetic-token", "EXECUTION_EVIDENCE_SYNC_URL": "https://console.example.test/api/execution-evidence/sync", + "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": "https://console.example.test/api/account-facts/sync", "RUNTIME_DAILY_BUSINESS_DATE": "2026-10-29"} now = datetime(2026, 10, 29, 20, tzinfo=timezone.utc) class Opener: @@ -116,9 +117,14 @@ def open(self, *_args, **_kwargs): monkeypatch.setattr(publisher, "_read_reports", lambda *_args: (reports, error)) assert publisher.publish_once(env, now=now, opener=opener) == "no_attributable_runs" assert opener.calls == 0 - env["EXECUTION_EVIDENCE_SYNC_URL"] = "https://untrusted.test/api/execution-evidence/sync" - with pytest.raises(ValueError, match="daily_origin_invalid"): - publisher.publish_once(env, now=now, opener=opener) + for bad_env in ( + {**env, "EXECUTION_EVIDENCE_SYNC_URL": "https://untrusted.test/api/execution-evidence/sync"}, + {k: v for k, v in env.items() if k != "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL"}, + {**env, "QSL_CONSOLE_BASE_URL": "https://other.example.test"}, + {**env, "QSL_CONSOLE_BASE_URL": "http://console.example.test"}, + ): + with pytest.raises(ValueError, match="daily_origin_invalid"): + publisher.publish_once(bad_env, now=now, opener=opener) assert opener.calls == 0 @@ -131,9 +137,9 @@ def test_unreadable_empty_source_keeps_safe_failure_category(monkeypatch, capsys "FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID": "a" * 64, "FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_SCOPE": "live", "EXECUTION_EVIDENCE_SYNC_TOKEN": "synthetic-token", - "EXECUTION_EVIDENCE_SYNC_URL": "https://example.test/api/execution-evidence/sync", + "EXECUTION_EVIDENCE_SYNC_URL": "https://console.example.test/api/execution-evidence/sync", + "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": "https://console.example.test/api/account-facts/sync", "RUNTIME_DAILY_BUSINESS_DATE": "2026-10-29"} - monkeypatch.setattr(publisher, "_FACTS_URL", "https://example.test/api/account-facts/sync") monkeypatch.setattr(publisher.os, "environ", env) monkeypatch.setattr(publisher.sys, "argv", ["publish_runtime_daily"]) monkeypatch.setattr(publisher, "build_opener", lambda *_: (_ for _ in ()).throw( @@ -165,7 +171,6 @@ def test_redirect_is_not_followed_and_unknown_is_not_retried(monkeypatch): from scripts import publish_runtime_daily as publisher monkeypatch.setattr(publisher, "_binding", lambda _env, _target: ("synthetic-key", "a" * 64, "b" * 64)) - monkeypatch.setattr(publisher, "_FACTS_URL", "https://example.test/api/account-facts/sync") report = {"platform": PLATFORM, "service_name": "synthetic-service", "strategy_profile": "synthetic-profile", "account_scope": "live", "run_id": "private-run", "started_at": "2026-10-29T18:00:00Z", "finished_at": "2026-10-29T18:01:00Z", "dry_run": False, "errors": [], "status": "ok", @@ -173,7 +178,8 @@ def test_redirect_is_not_followed_and_unknown_is_not_retried(monkeypatch): "external_cash_flow_interval": {"account_scope_sha256": "a" * 64}} monkeypatch.setattr(publisher, "_read_reports", lambda *_args: ([report], None)) env = {"RUNTIME_TARGET_JSON": json.dumps({"service_name": "synthetic-service", "strategy_profile": "synthetic-profile", "account_scope": "live"}), - "EXECUTION_EVIDENCE_SYNC_TOKEN": "synthetic-token", "EXECUTION_EVIDENCE_SYNC_URL": "https://example.test/api/execution-evidence/sync", + "EXECUTION_EVIDENCE_SYNC_TOKEN": "synthetic-token", "EXECUTION_EVIDENCE_SYNC_URL": "https://console.example.test/api/execution-evidence/sync", + "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": "https://console.example.test/api/account-facts/sync", "RUNTIME_DAILY_BUSINESS_DATE": "2026-10-29"} class Redirect: calls = 0 @@ -191,8 +197,9 @@ def test_auth_preflight_accepts_only_exact_safe_json_without_retry(monkeypatch): from urllib.error import HTTPError from scripts import publish_runtime_daily as publisher - monkeypatch.setattr(publisher, "_FACTS_URL", "https://example.test/api/account-facts/sync") - env = {"EXECUTION_EVIDENCE_SYNC_TOKEN": "synthetic-token", "EXECUTION_EVIDENCE_SYNC_URL": "https://example.test/api/execution-evidence/sync"} + env = {"EXECUTION_EVIDENCE_SYNC_TOKEN": "synthetic-token", + "EXECUTION_EVIDENCE_SYNC_URL": "https://console.example.test/api/execution-evidence/sync", + "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": "https://console.example.test/api/account-facts/sync"} class Opener: def __init__(self, code, body): self.code, self.body, self.calls = code, body, 0 def open(self, request, timeout): diff --git a/tests/test_publish_archived_account_history.py b/tests/test_publish_archived_account_history.py index b41433e..0d91fe5 100644 --- a/tests/test_publish_archived_account_history.py +++ b/tests/test_publish_archived_account_history.py @@ -26,9 +26,12 @@ }, separators=(",", ":")).encode()).hexdigest() +SYNTHETIC_CONSOLE_BASE_URL = "https://console.example.test" + + def config(): return AccountFactsPublishConfig( - "https://qsl-strategy-switch-console.pigbibi-e06.workers.dev/api/account-facts/sync", + f"{SYNTHETIC_CONSOLE_BASE_URL}/api/account-facts/sync", "synthetic-token", "synthetic-target", SOURCE, "synthetic-key", "live", ACCOUNT, position_currency="USD", ) @@ -111,6 +114,7 @@ def install_fakes(monkeypatch, *, mismatched_source=False, wrong_account=False, env = { "GCP_PROJECT_ID": "synthetic-project", "CLOUD_RUN_REGION": "synthetic-region", "CLOUD_RUN_SERVICE": "synthetic-service", "FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED": "true", + "QSL_CONSOLE_BASE_URL": SYNTHETIC_CONSOLE_BASE_URL, "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL": cfg.sync_url, "FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN": cfg.sync_token, "FIRSTRADE_ACCOUNT_FACTS_TARGET_ID": cfg.target_id, @@ -174,6 +178,14 @@ def test_publish_uses_history_ingress_after_identity_validation(monkeypatch): assert len(published) == 1 and published[0][1] == {"historical": True} +def test_publish_extracts_origin_from_evidence_url_when_console_base_url_unset(monkeypatch): + env, _, published = install_fakes(monkeypatch) + env["QSL_CONSOLE_BASE_URL"] = "" + env["EXECUTION_EVIDENCE_SYNC_URL"] = f"{SYNTHETIC_CONSOLE_BASE_URL}/api/execution-evidence/sync" + assert history.execute(DAY, publish=True, env=env)["status"] == "published" + assert len(published) == 1 + + @pytest.mark.parametrize("failure", ["source", "identity"]) def test_failed_source_or_native_identity_causes_zero_posts(monkeypatch, failure): env, reads, published = install_fakes(monkeypatch, mismatched_source=failure == "source", wrong_account=failure == "identity") diff --git a/tests/test_runtime_daily_natural_workflow.py b/tests/test_runtime_daily_natural_workflow.py index 2242b04..0ea9b8c 100644 --- a/tests/test_runtime_daily_natural_workflow.py +++ b/tests/test_runtime_daily_natural_workflow.py @@ -8,6 +8,8 @@ def test_natural_and_manual_daily_sources_use_only_masked_target_secret(): for workflow in (scheduled, manual): assert "RUNTIME_TARGET_JSON: ${{ secrets.RUNTIME_TARGET_JSON }}" in workflow assert "vars.RUNTIME_TARGET_JSON" not in workflow + assert "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL: ${{ vars.FIRSTRADE_ACCOUNT_FACTS_SYNC_URL }}" in workflow + assert "QSL_CONSOLE_BASE_URL: ${{ vars.QSL_CONSOLE_BASE_URL }}" in workflow assert "github.event_name == 'schedule'" in scheduled assert "github.run_attempt == 1" in scheduled assert "scripts.publish_runtime_daily" in scheduled diff --git a/tests/test_runtime_monitor_workflows.py b/tests/test_runtime_monitor_workflows.py index 8caeaf7..f0e8cd3 100644 --- a/tests/test_runtime_monitor_workflows.py +++ b/tests/test_runtime_monitor_workflows.py @@ -124,6 +124,8 @@ def test_metadata_only_dispatch_is_opt_in_and_skips_lifecycle_job() -> None: assert "scripts/inspect_account_data_readiness.py" in metadata_job assert "CLOUD_RUN_SERVICE: ${{ secrets.CLOUD_RUN_SERVICE }}" in metadata_job assert "CLOUD_RUN_REGION: ${{ vars.CLOUD_RUN_REGION }}" in metadata_job + assert "QSL_CONSOLE_BASE_URL: ${{ vars.QSL_CONSOLE_BASE_URL }}" in metadata_job + assert "EXECUTION_EVIDENCE_SYNC_URL: ${{ vars.EXECUTION_EVIDENCE_SYNC_URL }}" in metadata_job def test_lifecycle_publishes_read_only_observation_for_exact_service() -> None: diff --git a/tests/test_sync_cloud_run_env_workflow.py b/tests/test_sync_cloud_run_env_workflow.py index 58b7dab..f384341 100644 --- a/tests/test_sync_cloud_run_env_workflow.py +++ b/tests/test_sync_cloud_run_env_workflow.py @@ -55,12 +55,18 @@ def test_account_facts_configuration_is_an_isolated_zero_traffic_mode(): for name in ( "FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED", "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL", + "QSL_CONSOLE_BASE_URL", + "EXECUTION_EVIDENCE_SYNC_URL", "FIRSTRADE_ACCOUNT_FACTS_TARGET_ID", "FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID", "FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY", "FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_SCOPE", ): assert name in job + assert "QSL_CONSOLE_BASE_URL: ${{ vars.QSL_CONSOLE_BASE_URL }}" in job + assert "EXECUTION_EVIDENCE_SYNC_URL: ${{ vars.EXECUTION_EVIDENCE_SYNC_URL }}" in job + assert 'resolved_console_origin="$(python3 scripts/account_facts_config_sync.py origin)"' in job + assert "QSL_CONSOLE_BASE_URL=${resolved_console_origin}" in job assert "account-facts configuration readback is unavailable" in job assert "serving adoption remains separate" in job @@ -125,6 +131,8 @@ def test_sync_cloud_run_env_workflow_uses_sync_plan_script(): for name in ( "FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED", "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL", + "QSL_CONSOLE_BASE_URL", + "EXECUTION_EVIDENCE_SYNC_URL", "FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN_SECRET_NAME", ): assert f"{name}: ${{{{ vars.{name} }}}}" in workflow @@ -513,3 +521,75 @@ def test_readback_baseline_projections_include_array_members(): "spec.template.spec.containers[].env[].valueFrom.secretKeyRef", "bindings[].role", "bindings[].members", "bindings[].condition"): assert workflow.count(field) == 2 # baseline capture and comparison + + +def test_adopt_facts_revision_workflow_loads_approved_destination_from_vars(): + workflow = (Path(__file__).resolve().parents[1] / ".github/workflows/ft-adopt-facts-revision.yml").read_text() + assert "QSL_CONSOLE_BASE_URL: ${{ vars.QSL_CONSOLE_BASE_URL }}" in workflow + assert "EXECUTION_EVIDENCE_SYNC_URL: ${{ vars.EXECUTION_EVIDENCE_SYNC_URL }}" in workflow + assert "APPROVED_ACCOUNT_FACTS_SYNC_URL: ${{ vars.FIRSTRADE_ACCOUNT_FACTS_SYNC_URL }}" in workflow + assert "workers.dev" not in workflow + + match = re.search( + r"REVISION_JSON=\"\$\{rev_json\}\" EXPECTED_SHA=\"\$\{EXPECTED_SHA\}\" python3 - <<'PY'\n(.*?)\n PY", + workflow, + re.DOTALL, + ) + assert match is not None + script = "\n".join(line[10:] if line.startswith(" ") else line for line in match.group(1).splitlines()) + expected_sha = "a" * 40 + origin = "https://console.example.test" + sync_url = f"{origin}/api/account-facts/sync" + + def make_revision(*, rev_url=sync_url, rev_origin=origin): + env_rows = [ + {"name": "FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED", "value": "true"}, + {"name": "FIRSTRADE_ACCOUNT_FACTS_SYNC_URL", "value": rev_url}, + {"name": "FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN", "valueFrom": {"secretKeyRef": {"name": "sync-secret", "key": "latest"}}}, + {"name": "FIRSTRADE_ACCOUNT_FACTS_TARGET_ID", "value": "synthetic-target"}, + {"name": "FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID", "value": "b" * 64}, + {"name": "FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY", "value": "synthetic-key"}, + {"name": "FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_SCOPE", "value": "US"}, + ] + if rev_origin is not None: + env_rows.append({"name": "QSL_CONSOLE_BASE_URL", "value": rev_origin}) + return { + "metadata": {"labels": {"commit-sha": expected_sha}}, + "spec": {"containers": [{"env": env_rows}]}, + } + + base_env = { + "REVISION_JSON": json.dumps(make_revision()), + "EXPECTED_SHA": expected_sha, + "QSL_CONSOLE_BASE_URL": origin, + "EXECUTION_EVIDENCE_SYNC_URL": "", + "APPROVED_ACCOUNT_FACTS_SYNC_URL": sync_url, + } + ok = subprocess.run([sys.executable, "-c", script], env=base_env, capture_output=True, text=True, check=False) + assert ok.returncode == 0 and ok.stdout.strip() == "candidate_ok" + + for fallback_url in (origin, f"{origin}/api/execution-evidence/sync"): + ok_fallback = subprocess.run( + [sys.executable, "-c", script], + env={**base_env, "QSL_CONSOLE_BASE_URL": "", "EXECUTION_EVIDENCE_SYNC_URL": fallback_url}, + capture_output=True, + text=True, + check=False, + ) + assert ok_fallback.returncode == 0 and ok_fallback.stdout.strip() == "candidate_ok" + + for env_patch, expected_err in ( + ({"QSL_CONSOLE_BASE_URL": "", "EXECUTION_EVIDENCE_SYNC_URL": ""}, "approved_origin_invalid"), + ({"QSL_CONSOLE_BASE_URL": "http://console.example.test"}, "approved_origin_invalid"), + ({"QSL_CONSOLE_BASE_URL": "https://console.example.test/extra", "EXECUTION_EVIDENCE_SYNC_URL": f"{origin}/api/execution-evidence/sync"}, "approved_origin_invalid"), + ({"QSL_CONSOLE_BASE_URL": "", "EXECUTION_EVIDENCE_SYNC_URL": f"{origin}/unexpected"}, "approved_origin_invalid"), + ({"QSL_CONSOLE_BASE_URL": "https://[bad"}, "approved_origin_invalid"), + ({"QSL_CONSOLE_BASE_URL": "https://console.example.test:badport"}, "approved_origin_invalid"), + ({"APPROVED_ACCOUNT_FACTS_SYNC_URL": "https://other.example.test/api/account-facts/sync"}, "approved_sync_url_invalid"), + ({"REVISION_JSON": json.dumps(make_revision(rev_url="https://other.example.test/api/account-facts/sync"))}, "sync_url_invalid"), + ({"REVISION_JSON": json.dumps(make_revision(rev_origin=None))}, "console_origin_invalid"), + ({"REVISION_JSON": json.dumps(make_revision(rev_origin="https://other.example.test"))}, "console_origin_invalid"), + ): + failed = subprocess.run([sys.executable, "-c", script], env={**base_env, **env_patch}, capture_output=True, text=True, check=False) + assert failed.returncode != 0 + assert expected_err in failed.stderr