Repository navigation
SCA-403: Record serving-backend provenance on desktop stable pointer - #12564
Conversation
|
Dart Analyze & Tests is red for a reason already on This PR does not touch any Dart/Flutter files. Identical analyzer-ratchet fingerprint: This PR ( Already failed on the home-refresh PR that landed as #12563 ( Later Not disabling, skipping, or |
There was a problem hiding this comment.
10 issues found across 15 files
Confidence score: 2/5
.github/workflows/desktop_promote_prod.ymlexecutes.github/scripts/check_desktop_backend_drift.pyfrom the user-selected checkout before validating the promotion ref, allowing an untrusted branch or tag to run arbitrary repository code in the promotion workflow — validate the ref before executing checkout-controlled scripts..github/workflows/desktop_promote_prod.ymlrecords health from the initial workflow step rather than the serving state when pointers transition, so promotion payloads can report stale backend status during deploy, manifest, CAS, or repair operations — fetch both health endpoints immediately before recording the transition..github/scripts/check_desktop_backend_drift.pycan fail on invalid UTF-8 and can render attacker-controlled commit subjects as Markdown or HTML, making drift reporting brittle and potentially unsafe — route decode failures through the unknown-backend path and escape every summary cell.- Backend validation remains inconsistent across
backend/routers/updates.py,backend/database/desktop_update_channels.py, andbackend/routers/desktop_core.py: malformed timestamps, empty optional values, malformed serving-backend data, missing fallback telemetry, and empty release SHA values can be accepted or handled incorrectly — enforce normalized schemas and consistent fail-closed/telemetry behavior before relying on these values.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="backend/routers/updates.py">
<violation number="1" location="backend/routers/updates.py:89">
P3: `release_channel` and `chat_contract_version` are `Optional[str]` with no request-level constraint, so an empty string passes Pydantic validation, but the DB layer's `_optional_text` then rejects `""` via `if isinstance(value, str) and value`, surfacing as HTTP 409 instead of a 422 at the boundary. Constrain them at the request model (e.g. `Field(min_length=1)`) so empty/blank values are rejected consistently with the malformed-`release_sha` case, which fails closed at 422.</violation>
<violation number="2" location="backend/routers/updates.py:124">
P2: `captured_at` is an API timestamp but is declared as a plain string and manually parsed. Use a timezone-aware Pydantic datetime type and normalize it at serialization so malformed timestamps are rejected and the API schema advertises the date-time contract.</violation>
</file>
<file name=".github/workflows/desktop_promote_prod.yml">
<violation number="1" location=".github/workflows/desktop_promote_prod.yml:59">
P1: Before `Validate stable promotion request` checks the dispatch ref, this step executes `.github/scripts/check_desktop_backend_drift.py` from the user-selected checkout. A branch or tag can therefore run arbitrary repository code; validate the ref using default-branch controls before executing any checked-out script.</violation>
<violation number="2" location=".github/workflows/desktop_promote_prod.yml:179">
P2: When a backend deploys while manifest, CAS, or repair steps run, this payload records the health snapshot from the first workflow step rather than the serving state at pointer transition. Fetch both health endpoints immediately before building the promotion payload so `captured_at` and the SHAs describe the same observation.</violation>
</file>
<file name="backend/database/desktop_update_channels.py">
<violation number="1" location="backend/database/desktop_update_channels.py:585">
P2: When a pointer contains malformed or unknown `serving_backends` data, `get_channel_release` forwards it without applying the fail-closed schema validator. Normalize this field on read so the resolver rejects the pointer and falls back instead of caching untrusted provenance.</violation>
</file>
<file name="backend/routers/desktop_core.py">
<violation number="1" location="backend/routers/desktop_core.py:42">
P3: Empty-string env values are handled inconsistently. `OMI_DESKTOP_BACKEND_RELEASE_SHA=""` is treated as present (`!= None`), producing `backend_release_sha: ""` and blocking the `OMI_BACKEND_RELEASE_SHA` fallback, whereas the fallback itself normalizes `""` to `None`. An empty desktop SHA would surface as a blank provenance identity instead of falling back. Normalize both via `value or None` (`if value is not None and value != ""`).</violation>
<violation number="2" location="backend/routers/desktop_core.py:47">
P2: This is a fail-open path (missing provenance returns null instead of erroring) but never calls `record_fallback`. The repo's fallback-telemetry contract requires fail-open branches to emit through `utils.observability.fallback.record_fallback`; keep the null-returning behavior, and call `record_fallback` with a `degraded`/`local_heal` outcome when the fallback is taken so ops can observe the silent degradation.</violation>
</file>
<file name=".github/scripts/check_desktop_backend_drift.py">
<violation number="1" location=".github/scripts/check_desktop_backend_drift.py:54">
P2: When a health response contains invalid UTF-8, `_load_json` raises instead of recording the backend as unknown. Catch the decode error with the existing malformed-payload path so informational drift reporting remains fail-open without `--strict`.</violation>
<violation number="2" location=".github/scripts/check_desktop_backend_drift.py:130">
P2: When a main commit subject contains Markdown table or HTML syntax, the promotion summary is malformed or renders attacker-controlled markup. Escape every cell value before joining the table, including commit subjects and `deployed_at`.</violation>
</file>
<file name=".github/checks-manifest.yaml">
<violation number="1" location=".github/checks-manifest.yaml:816">
P3: `desktop-backend-drift-cli` runs the script's `--self-test`, which the fixtures check already exercises because `test_check_desktop_backend_drift.py` invokes the same `--self-test` as a subprocess. The two checks therefore run the same predicate redundantly. Use `--help` as a loader smoke test for the CLI check (matching `stable-pointer-precondition-cli`) so the pair provides distinct coverage, or consolidate into a single check.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| run: | | ||
| set -euo pipefail | ||
| git fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main | ||
| python3 .github/scripts/check_desktop_backend_drift.py \ |
There was a problem hiding this comment.
P1: Before Validate stable promotion request checks the dispatch ref, this step executes .github/scripts/check_desktop_backend_drift.py from the user-selected checkout. A branch or tag can therefore run arbitrary repository code; validate the ref using default-branch controls before executing any checked-out script.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At .github/workflows/desktop_promote_prod.yml, line 59:
<comment>Before `Validate stable promotion request` checks the dispatch ref, this step executes `.github/scripts/check_desktop_backend_drift.py` from the user-selected checkout. A branch or tag can therefore run arbitrary repository code; validate the ref using default-branch controls before executing any checked-out script.</comment>
<file context>
@@ -48,7 +48,19 @@ jobs:
+ run: |
+ set -euo pipefail
+ git fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main
+ python3 .github/scripts/check_desktop_backend_drift.py \
+ --desktop-backend-health /tmp/desktop-backend-health.json \
+ --api-backend-health /tmp/api-backend-health.json \
</file context>
|
|
||
| desktop_backend: DesktopBackendServingObservation | ||
| api_backend: ApiBackendServingObservation | ||
| captured_at: str = Field(min_length=1) |
There was a problem hiding this comment.
P2: captured_at is an API timestamp but is declared as a plain string and manually parsed. Use a timezone-aware Pydantic datetime type and normalize it at serialization so malformed timestamps are rejected and the API schema advertises the date-time contract.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/routers/updates.py, line 124:
<comment>`captured_at` is an API timestamp but is declared as a plain string and manually parsed. Use a timezone-aware Pydantic datetime type and normalize it at serialization so malformed timestamps are rejected and the API schema advertises the date-time contract.</comment>
<file context>
@@ -76,13 +77,74 @@ class ClearCacheResponse(BaseModel):
+
+ desktop_backend: DesktopBackendServingObservation
+ api_backend: ApiBackendServingObservation
+ captured_at: str = Field(min_length=1)
+
+ @field_validator("captured_at")
</file context>
| value = health.get(key) | ||
| return value if isinstance(value, str) and value else None | ||
|
|
||
| desktop = json.load(open("/tmp/desktop-backend-health.json")) |
There was a problem hiding this comment.
P2: When a backend deploys while manifest, CAS, or repair steps run, this payload records the health snapshot from the first workflow step rather than the serving state at pointer transition. Fetch both health endpoints immediately before building the promotion payload so captured_at and the SHAs describe the same observation.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At .github/workflows/desktop_promote_prod.yml, line 179:
<comment>When a backend deploys while manifest, CAS, or repair steps run, this payload records the health snapshot from the first workflow step rather than the serving state at pointer transition. Fetch both health endpoints immediately before building the promotion payload so `captured_at` and the SHAs describe the same observation.</comment>
<file context>
@@ -151,11 +163,41 @@ jobs:
+ value = health.get(key)
+ return value if isinstance(value, str) and value else None
+
+ desktop = json.load(open("/tmp/desktop-backend-health.json"))
+ try:
+ api = json.load(open("/tmp/api-backend-health.json"))
</file context>
| "updated_at": pointer.get("updated_at"), | ||
| } | ||
| if "serving_backends" in pointer: | ||
| pointer_view["serving_backends"] = pointer["serving_backends"] |
There was a problem hiding this comment.
P2: When a pointer contains malformed or unknown serving_backends data, get_channel_release forwards it without applying the fail-closed schema validator. Normalize this field on read so the resolver rejects the pointer and falls back instead of caching untrusted provenance.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/database/desktop_update_channels.py, line 585:
<comment>When a pointer contains malformed or unknown `serving_backends` data, `get_channel_release` forwards it without applying the fail-closed schema validator. Normalize this field on read so the resolver rejects the pointer and falls back instead of caching untrusted provenance.</comment>
<file context>
@@ -483,16 +572,19 @@ def get_channel_release(platform: str, channel: str, *, firestore_client: Any =
+ "updated_at": pointer.get("updated_at"),
+ }
+ if "serving_backends" in pointer:
+ pointer_view["serving_backends"] = pointer["serving_backends"]
return {
- "pointer": {
</file context>
| pointer_view["serving_backends"] = pointer["serving_backends"] | |
| pointer_view["serving_backends"] = normalize_serving_backends(pointer["serving_backends"]) |
| # stamps OMI_BACKEND_RELEASE_SHA on the Cloud Run revision. Absent env | ||
| # stays null so callers never 500 for missing provenance. | ||
| fallback = os.getenv("OMI_BACKEND_RELEASE_SHA") | ||
| response["backend_release_sha"] = fallback or None |
There was a problem hiding this comment.
P2: This is a fail-open path (missing provenance returns null instead of erroring) but never calls record_fallback. The repo's fallback-telemetry contract requires fail-open branches to emit through utils.observability.fallback.record_fallback; keep the null-returning behavior, and call record_fallback with a degraded/local_heal outcome when the fallback is taken so ops can observe the silent degradation.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/routers/desktop_core.py, line 47:
<comment>This is a fail-open path (missing provenance returns null instead of erroring) but never calls `record_fallback`. The repo's fallback-telemetry contract requires fail-open branches to emit through `utils.observability.fallback.record_fallback`; keep the null-returning behavior, and call `record_fallback` with a `degraded`/`local_heal` outcome when the fallback is taken so ops can observe the silent degradation.</comment>
<file context>
@@ -39,6 +39,12 @@ def health_response() -> dict[str, str]:
+ # stamps OMI_BACKEND_RELEASE_SHA on the Cloud Run revision. Absent env
+ # stays null so callers never 500 for missing provenance.
+ fallback = os.getenv("OMI_BACKEND_RELEASE_SHA")
+ response["backend_release_sha"] = fallback or None
return response
</file context>
| ] | ||
| for row in rows: | ||
| behind = "unknown" if row.commits_behind is None else str(row.commits_behind) | ||
| subjects = "<br>".join(row.subjects) if row.subjects else ("unknown" if row.unknown else "none") |
There was a problem hiding this comment.
P2: When a main commit subject contains Markdown table or HTML syntax, the promotion summary is malformed or renders attacker-controlled markup. Escape every cell value before joining the table, including commit subjects and deployed_at.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At .github/scripts/check_desktop_backend_drift.py, line 130:
<comment>When a main commit subject contains Markdown table or HTML syntax, the promotion summary is malformed or renders attacker-controlled markup. Escape every cell value before joining the table, including commit subjects and `deployed_at`.</comment>
<file context>
@@ -0,0 +1,297 @@
+ ]
+ for row in rows:
+ behind = "unknown" if row.commits_behind is None else str(row.commits_behind)
+ subjects = "<br>".join(row.subjects) if row.subjects else ("unknown" if row.unknown else "none")
+ cells = [row.service, f"`{row.serving_sha}`", behind, subjects]
+ if include_deployed:
</file context>
| return {} | ||
| try: | ||
| loaded = json.loads(path.read_text(encoding="utf-8")) | ||
| except (OSError, json.JSONDecodeError): |
There was a problem hiding this comment.
P2: When a health response contains invalid UTF-8, _load_json raises instead of recording the backend as unknown. Catch the decode error with the existing malformed-payload path so informational drift reporting remains fail-open without --strict.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At .github/scripts/check_desktop_backend_drift.py, line 54:
<comment>When a health response contains invalid UTF-8, `_load_json` raises instead of recording the backend as unknown. Catch the decode error with the existing malformed-payload path so informational drift reporting remains fail-open without `--strict`.</comment>
<file context>
@@ -0,0 +1,297 @@
+ return {}
+ try:
+ loaded = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return {}
+ return loaded if isinstance(loaded, dict) else {}
</file context>
| except (OSError, json.JSONDecodeError): | |
| except (OSError, UnicodeError, json.JSONDecodeError): |
| value = os.getenv(environment_name) | ||
| if value is not None: | ||
| response[response_field] = value | ||
| if "backend_release_sha" not in response: |
There was a problem hiding this comment.
P3: Empty-string env values are handled inconsistently. OMI_DESKTOP_BACKEND_RELEASE_SHA="" is treated as present (!= None), producing backend_release_sha: "" and blocking the OMI_BACKEND_RELEASE_SHA fallback, whereas the fallback itself normalizes "" to None. An empty desktop SHA would surface as a blank provenance identity instead of falling back. Normalize both via value or None (if value is not None and value != "").
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/routers/desktop_core.py, line 42:
<comment>Empty-string env values are handled inconsistently. `OMI_DESKTOP_BACKEND_RELEASE_SHA=""` is treated as present (`!= None`), producing `backend_release_sha: ""` and blocking the `OMI_BACKEND_RELEASE_SHA` fallback, whereas the fallback itself normalizes `""` to `None`. An empty desktop SHA would surface as a blank provenance identity instead of falling back. Normalize both via `value or None` (`if value is not None and value != ""`).</comment>
<file context>
@@ -39,6 +39,12 @@ def health_response() -> dict[str, str]:
value = os.getenv(environment_name)
if value is not None:
response[response_field] = value
+ if "backend_release_sha" not in response:
+ # Shared Python backend publishes the same /health via this router and
+ # stamps OMI_BACKEND_RELEASE_SHA on the Cloud Run revision. Absent env
</file context>
| lanes: ["local", "ci"] | ||
| reason: "#10163 mutation-sensitive Stable retry and default-channel feed fixtures" | ||
| - id: desktop-backend-drift-cli | ||
| command: ["python3", ".github/scripts/check_desktop_backend_drift.py", "--self-test"] |
There was a problem hiding this comment.
P3: desktop-backend-drift-cli runs the script's --self-test, which the fixtures check already exercises because test_check_desktop_backend_drift.py invokes the same --self-test as a subprocess. The two checks therefore run the same predicate redundantly. Use --help as a loader smoke test for the CLI check (matching stable-pointer-precondition-cli) so the pair provides distinct coverage, or consolidate into a single check.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At .github/checks-manifest.yaml, line 816:
<comment>`desktop-backend-drift-cli` runs the script's `--self-test`, which the fixtures check already exercises because `test_check_desktop_backend_drift.py` invokes the same `--self-test` as a subprocess. The two checks therefore run the same predicate redundantly. Use `--help` as a loader smoke test for the CLI check (matching `stable-pointer-precondition-cli`) so the pair provides distinct coverage, or consolidate into a single check.</comment>
<file context>
@@ -812,6 +812,16 @@ checks:
lanes: ["local", "ci"]
reason: "#10163 mutation-sensitive Stable retry and default-channel feed fixtures"
+ - id: desktop-backend-drift-cli
+ command: ["python3", ".github/scripts/check_desktop_backend_drift.py", "--self-test"]
+ triggers: [".github/workflows/desktop_promote_prod.yml", ".github/scripts/check_desktop_backend_drift.py", ".github/scripts/test_check_desktop_backend_drift.py", ".github/checks-manifest.yaml"]
+ lanes: ["local", "ci"]
</file context>
| command: ["python3", ".github/scripts/check_desktop_backend_drift.py", "--self-test"] | |
| command: ["python3", ".github/scripts/check_desktop_backend_drift.py", "--help"] |
| model_config = ConfigDict(extra="forbid") | ||
|
|
||
| release_sha: Optional[str] = None | ||
| release_channel: Optional[str] = None |
There was a problem hiding this comment.
P3: release_channel and chat_contract_version are Optional[str] with no request-level constraint, so an empty string passes Pydantic validation, but the DB layer's _optional_text then rejects "" via if isinstance(value, str) and value, surfacing as HTTP 409 instead of a 422 at the boundary. Constrain them at the request model (e.g. Field(min_length=1)) so empty/blank values are rejected consistently with the malformed-release_sha case, which fails closed at 422.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/routers/updates.py, line 89:
<comment>`release_channel` and `chat_contract_version` are `Optional[str]` with no request-level constraint, so an empty string passes Pydantic validation, but the DB layer's `_optional_text` then rejects `""` via `if isinstance(value, str) and value`, surfacing as HTTP 409 instead of a 422 at the boundary. Constrain them at the request model (e.g. `Field(min_length=1)`) so empty/blank values are rejected consistently with the malformed-`release_sha` case, which fails closed at 422.</comment>
<file context>
@@ -76,13 +77,74 @@ class ClearCacheResponse(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ release_sha: Optional[str] = None
+ release_channel: Optional[str] = None
+ chat_contract_version: Optional[str] = None
+ health_url: str = Field(min_length=1)
</file context>
| release_channel: Optional[str] = None | |
| release_channel: Optional[str] = Field(default=None, min_length=1) |
67ba925 to
09c327d
Compare
|
Rebased onto Desktop Swift Static & Test Contracts failed after This PR still does not change Swift production sources. The job ran because Not updating the Swift test-quality baseline in this PR. Not merging past the red check. |
api.omi.me/health is served by desktop_core and previously only published OMI_DESKTOP_BACKEND_RELEASE_SHA. Read the Cloud Run revision stamp as a fallback and fail open to null so promotion can record real provenance. Co-authored-by: Cursor <[email protected]> Co-authored-by: multica-agent <[email protected]>
Persist the live desktop-backend and API health identities on promote and repoint, keep them off the immutable manifest, and print a read-only drift table at promotion time so lag is visible without a new block. Co-authored-by: Cursor <[email protected]> Co-authored-by: multica-agent <[email protected]>
Document that the pointer records observed backends rather than a compatibility guarantee, and how to read the promotion drift table. Co-authored-by: Cursor <[email protected]> Co-authored-by: multica-agent <[email protected]>
The Stable pointer provenance and drift table are operator-facing, not a user-visible app change, so the unreleased fragment is kind none. Co-authored-by: Cursor <[email protected]> Co-authored-by: multica-agent <[email protected]>
Pre-push exports GIT_DIR for the outer checkout, so the fixture repo inherited that namespace and failed to commit. Strip GIT_* and disable hooks/gpgsign in the self-test. Co-authored-by: Cursor <[email protected]> Co-authored-by: multica-agent <[email protected]>
ratchet above its ceiling. Those reads are static wiring, not API behavior, so they need the local source-inspection escape. Co-authored-by: Cursor <[email protected]> Co-authored-by: multica-agent <[email protected]>
Align the public-web regression assertion with the current prompt contract and include the pinned Redis client in the Firestore contention harness's uv environment. Failure-Class: none
ac9affc to
2978bc7
Compare
…ren (#13850) Git exports GIT_DIR to hooks; from a linked worktree it is the absolute path of .git/worktrees/<name>. scripts/pre-push passed it to every check it ran, so agents-md-lean's self-test `git init <fixture>` reinitialized the real repository instead: git guessed it bare and wrote core.bare=true into the config every worktree shares. With extensions.worktreeConfig on, that shared value also applies to linked worktrees, so the fixture's ls-files failed and the push of #11183 was refused with "ignored worktree copies must not be discovered". Four earlier fixes scrubbed the variable one caller at a time (#11413, #11709, #11795, #12564). Clear it once at the top of the gate, after it changes to the work tree root, and drop the two Flutter-phase copies it makes redundant. test-pre-push-worktree-fallback.sh ran the gate with a bogus bare GIT_DIR and relied on the gate still using it to fail at the base-ref lookup. The gate now uses the work tree, which has origin/main, so the harness names a base branch no repository has to keep failing fast at the same step. Verification: - Real `git push` from a disposable linked worktree, real pre-push hook, the checker from origin/main: hook env GIT_DIR=<sbx>/main/.git/worktrees/wt; shared core.bare false -> true; with extensions.worktreeConfig=true the exact #11183 AssertionError. A push from the main worktree exports no GIT_DIR and is unaffected. - scripts/test-pre-push-git-env.sh passes with the fix and fails with the gate from origin/main and with only the new unset removed (core.bare=false -> core.bare=true in the fixture's shared config). - All 13 manifest checks triggered by scripts/pre-push pass through run_checks.py --lane local; pre-push-worktree-fallback is Windows-only in the manifest and passes when run directly on macOS. Failure-Class: new Co-authored-by: Claude Opus 5 <[email protected]>
Summary
Stable desktop promotion, the shared Python backend, and
desktop-backendstill move independently. Nothing recorded which backend revisions a given app build was actually validated against. Observed 2026-09-01 while promoting Desktop 0.12.254 (workflow run https://github.com/BasedHardware/omi/actions/runs/33547696232):61dfd4d2e, which predates 20+ backend commits then onmain.desktop-backendprod/healthreportedbackend_release_sha36c467fd2b…(deployed 2026-08-25) whilemainhad newer desktop-backend commits.mainat 15:35Z the same day.This change records serving-backend provenance on the Stable pointer (not the immutable release manifest) and prints a read-only drift table at promotion time.
Product invariants
Design
register_release_manifestrejects metadata changes under an existing release ID. Provenance is an observation about this pointer transition, not about the signed artifact.--strictis passed, and the promotion workflow does not pass--strict./healthalready comes fromdesktop_coreonapi.omi.me. Cloud Run already stampsOMI_BACKEND_RELEASE_SHA; health now reads it (fail-opennullwhen absent) without inventing a second identity field.Closes SCA-403
Test plan
python3 .github/scripts/check_desktop_backend_drift.py --self-test--checkfor public and app-client specs (unchanged; admin promote route is not in those surfaces).scripts/pr-preflight --lane local— 123 checks passed.Failure-Class: none
🤖 Generated with Claude Code