Skip to content

fix: owner-gate remaining MCP/config mutations - #5161

Closed
atomsbaza wants to merge 2 commits into
kirodotdev:mainfrom
atomsbaza:investigate/issue-5014
Closed

atomsbaza wants to merge 2 commits into
kirodotdev:mainfrom
atomsbaza:investigate/issue-5014

Conversation

@atomsbaza

@atomsbaza atomsbaza commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

The dashboard still exposes MCP and configuration mutation routes that can write machine-global state, restart sessions, install or remove capabilities, or change gateway behavior. The routes this PR targets did not share one owner authorization boundary, so the protection could drift between handlers. Several owner-denial helpers also duplicated the same identity rule in different modules.

Why it matters

MCP and dashboard configuration writes affect the host and future sessions, not only the requesting tab. An app-scoped token or an authenticated non-owner must not be able to trigger those side effects. Authorization must happen before JSON parsing, locks, resolver work, process spawning, or any other mutation side effect. One route is deliberately outside that ordering: PATCH /api/config/kirocrew reads the requested direction first, because main lets any authenticated dashboard user turn the billed usage scrape OFF (test_a_non_owner_may_still_switch_the_billing_off), and a gate placed before the parse could not tell that disable from an enable. The parse is the only thing that precedes the gate there; no lock, resolver, spawn or write does.

What changed

  • One shared owner boundary. Centralize the owner predicate and denial response in the shared dashboard handler module; the response is 403 with machine-readable code owner_only.
  • Enumerate the invariant. Gate all 20 targeted mutation routes across MCP sync/apply/toggle/custom/discovery/server/probe/measure/quarantine, MCP gateway control, config, and theme operations. Six further mutating routes in the same registrar (dashboard config write, onboarding import, OAuth relay, connections mint/cancel) already reach the same gate on main (connections.py:190,341,572, files.py:6182, onboarding_import.py:595,618); what they lack is a place in the registrar-walk invariant this PR adds, so a future ungated sibling there would not be caught. That test-coverage gap is what migrate the 7 remaining inline owner-denial sequences to require_owner_dashboard_request #6224 tracks.
  • Preserve the internal-auth contract. X-Internal-Secret remains an explicit opt-in exception only for MCP server registration (PUT/DELETE /api/mcp/servers/{name}); it does not bypass the other mutation routes.
  • Remove drift. Replace duplicated owner-denial helpers with the shared boundary while preserving compatibility exports used by existing callers and tests.
  • Test the ordering guarantee. Walk the real route registrar and send requests without JSON bodies, proving non-owner and app-token requests receive 403 owner_only before a handler can return a body-parse error or perform a side effect.

Tests

  • Targeted authorization/config suite: 702 passed, 6 deselected.
  • Route invariant test: 4 passed.
  • Fixture regression group: 146 passed.
  • Additional probe/theme/gateway route tests: 65 passed.
  • Compatibility regression for MCP sync handlers: 66 passed.
  • py_compile passed for all changed Python files.
  • git diff --check passed.

The final targeted run deselected 6 environment-only test nodes. The broader relevant run had 3 environment-only failures: two pip-channel checks because the uv-created environment has no pip module, and one optional STT capability check because voice/Transcribe dependencies were not installed. Formatting/lint executables (black, isort, flake8, and ruff) were unavailable in the isolated worktree environment.

Review and CI status

The local diff was reviewed and the available targeted validation passed. No separate model-pinned review is claimed here. Upstream automated checks for this fork PR are currently held by GitHub action_required approval for the fork workflows; this is an execution-permission blocker, not a source-test failure. After an upstream maintainer approves and runs the workflows, CI and review results should be evaluated for the current head revision.

Scope

Backend-only authorization and regression coverage. No frontend behavior changes and no screenshot evidence is applicable.

Closes #5014

Pattern harvest

Rule candidate: semgrep / review-prompt — when an authorization predicate is re-stated per handler it drifts, so a registrar's mutating routes should share one owner boundary that runs before body parsing, lock acquisition, or any other side effect, and the invariant should be pinned by a test that walks the real route table rather than by a hand-kept list of route names.

Section appended by a maintainer to satisfy the PR Hygiene gate, which began requiring a Pattern harvest section on fix: PRs after this PR was opened. No other part of this description, and nothing on the branch, was touched.

@atomsbaza
atomsbaza requested a review from a team August 23, 2026 04:40
@github-actions github-actions Bot added fork Pull request from a fork (external contributor) readiness: action required A blocking check or review needs attention labels Aug 23, 2026
@bolichen97

Copy link
Copy Markdown
Contributor

👋 Hi! This PR's description is missing some required sections from our PR template. Workflow runs won't be auto-approved until the description is updated.

Missing sections:

  • ## Problem / Motivation
  • ## Why it matters
  • ## What changed
  • ## Tests

Please update your PR description to include these sections, then push or re-save the description. The workflows will be approved on the next cycle.

@iamwhatever

Copy link
Copy Markdown
Contributor

👋 Hi! This PR's description is missing some required sections from our PR template. Workflow runs won't be auto-approved until the description is updated.

Missing sections:

  • ## Problem / Motivation
  • ## What changed
  • ## Tests

Please update your PR description to include these sections, then push or re-save the description. The workflows will be approved on the next cycle.

@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Aug 23, 2026
@atomsbaza
atomsbaza force-pushed the investigate/issue-5014 branch 2 times, most recently from 716d7d5 to b824cff Compare August 23, 2026 12:49
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention merge conflict Branch has merge conflicts with its base — author must resolve before merge and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Aug 23, 2026
@bolichen97
bolichen97 enabled auto-merge (squash) August 24, 2026 06:57
@iamwhatever iamwhatever added the needs-pr-triage PR scanner: awaiting automated triage label Aug 26, 2026
@bolichen97 bolichen97 added the drive-to-green PR claimed by drive-to-green pipeline label Aug 26, 2026
@bolichen97

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew [operator: bolichen97#66809557]: This PR has been inactive with a blocked CI state. I've assessed the blockers and they appear resolvable — I'll push fixes directly to this branch as a co-author.

Assessment: The branch is behind main with merge conflicts (mergeable_state=dirty), and Backend Lint fails on one mechanical F401 — source_providers.py still imports is_owner_dashboard_request from _shared after the local copy was removed, but no longer references it (the centralization is correct; the import is just orphaned). Plan: rebase onto latest main, resolve conflicts guided by the PR's intent (one shared owner-gate boundary in _shared, taking main's handler/test structure + this PR's gating logic), drop the unused import, and run local gates before force-pushing. All other CI (Backend/Frontend/Coverage/Build tests) passed on the pre-conflict head. No design or scope change.

If you'd prefer I don't touch this PR, add the pr-no-autofix label.

@bolichen97 bolichen97 removed the needs-pr-triage PR scanner: awaiting automated triage label Aug 26, 2026
@bolichen97
bolichen97 force-pushed the investigate/issue-5014 branch from b824cff to 6adfb57 Compare August 27, 2026 04:26
@bolichen97

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew [operator: bolichen97#66809557]

Rebased this PR onto current main (was CONFLICTING) and pushed 6adfb57d3 (was b824cffa6). What changed and why:

Conflict resolution — main's structure + this PR's consolidation, guard semantics untouched:

  • Main added stale_owner_session_response / STALE_OWNER_SESSION_CODE (401 stale_session_reauth relabel for signed pre-owner bootstrap sessions) after this PR's base, and every owner-gate deny site on main runs it. To keep that behavior at the call sites this PR migrates, require_owner_dashboard_request now runs the same relabel on its deny path (lazy import from source_providers to avoid the import cycle). Relabel-only: it runs strictly after the deny decision and never grants — the fail-closed semantics of the guard are unchanged.
  • source_providers.py: kept main's stale_owner_session_response machinery in place; removed the moved is_owner_dashboard_request / _LOCAL_DASHBOARD_OWNER_SUBJECTS definitions per this PR, importing them from _shared instead. is_owner_dashboard_request is kept as a # noqa: F401 compatibility re-export because 10+ untouched modules (chat_handlers, prompts, secrets, tailnet_mobile, handlers_cloud, …) import it from here. _LOCAL_DASHBOARD_OWNER_SUBJECTS is genuinely used in-file (stale relabel + source-owner gate) — this resolves the F401 blocker flagged pre-rebase.
  • agents.py / mcp_apps.py: took this PR's side (delete _require_owner / the inline gate in favor of the shared guard); the stale relabel those main-side versions carried is preserved via the shared guard above.

Rebase-integration fixes:

  • test_dashboard_handlers_core_coverage.py: TestFallbackModelPatch was added on main after this PR's base and built a bare app for the now-owner-gated PATCH /api/config/kirocrew; gave it the same _owner_identity middleware + state pattern this PR established for the sibling classes.
  • test_stale_owner_session_signal.py: migrated test_agents_gate_labels_stale_bootstrap_denial from the deleted agents._require_owner to the shared guard (same contract, same assertions).
  • error-code-baseline.json: regenerated with python test/test_error_code_contract.py --update — missing_code 1357 → 1355 (this PR's guard adds code fields where the old inline gates had none).

Local gates: isort / flake8 / black-baseline clean; mypy clean on the touched files; 1090 targeted tests pass (all 24 test files this PR touches + the stale-signal and error-code contract suites).

Single commit preserved (original authorship kept, Kiro Crew co-author trailer added).

@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Aug 27, 2026
@bolichen97
bolichen97 force-pushed the investigate/issue-5014 branch from 6adfb57 to 608d606 Compare August 27, 2026 04:42
@github-actions github-actions Bot added the readiness: action required A blocking check or review needs attention label Aug 29, 2026
@bolichen97

Copy link
Copy Markdown
Contributor

I re-read the complete current 26-file diff after the head changed from 48111dd9 to 9a0d9ca3. Please rebase this PR onto current main and reduce it to residual-only scope.

Already merged coverage:

Keep the distinct residual: owner gates for the remaining MCP/custom/discovery/gateway/config mutations (including probe/measure/quarantine/sync/toggle/remove/apply, custom add/update, discovery install, gateway enable/stub/resolve refresh, and config/theme writes), plus the route-walk and route-specific authorization tests. Dropping the already-merged helper and agent-spec portions will make the security delta reviewable without losing those uncovered routes.

@bolichen97

Copy link
Copy Markdown
Contributor

Audit note — part of this has already landed; the rest has not

This PR is not a duplicate and is not finished by anything on main. The audit checked it part by part against main, and some of what it does is already there. Flagging it so a reviewer does not have to rediscover the overlap, and so the PR is not mistaken for fully-covered work.

Already landed

Only ONE claimed reference really landed and touches this work: #6245 -- the issue/PR reference check row 6245 PR closed 2026-08-28T06:10:12Z, and the landed-commit index for main line 848 f38562c96b659ba0975d5b1bb3f86596992f1e64 2026-08-27 refactor(dashboard): migrate inline owner-denial sequences to shared helper (#6245). Confirmed merged. #5011 also landed (the issue/PR reference check: PR closed 2026-08-22T07:39:58Z; landed as ab437bc) but the initial scan correctly scored it ADJACENT/coverage NONE and I confirm it covers none of this PR's routes. the initial scan claims that COLLAPSE now that the issue/PR reference check is populated (it was 0 bytes in the initial scan): #5014 (the PR body's 'Closes #5014') is an ISSUE, open -- 5014 ISSUE open -- so it cannot cover code; #6224 (the body's deferral target) is an ISSUE, closed -- 6224 ISSUE closed -- also not a PR. Neither was ever asserted as a coverage source, but the initial scan left both 'UNVERIFIED as to kind' and now they are settled. The three remaining the initial scan relations -- #7308, #6307, #7393 -- are all still-OPEN PRs (7308 PR open, 6307 PR open, 7393 PR open), so none of them covers anything; the initial scan had already scored all three coverage NONE, so there is no merged-vs-open error to correct here.

Which parts main already has

Only the shared boundary this PR builds ON, not any route it gates. #6245 (f38562c) landed: (1) require_owner_dashboard_request and _owner_denial_response in src/kiro_crew/dashboard/handlers/_shared.py (main lines 1890 and 1937; git log origin/main -S'async def require_owner_dashboard_request' -- .../_shared.py names f38562c as the sole commit) -- so the body's bullet 'One shared owner boundary. Centralize the owner predicate and denial response' and the 403 + code: owner_only shape are already on main; (2) test/dashboard_owner_helpers.py (added by f38562c), the as_owner/NoConfiguredOwner fixtures that make this PR's 13 hand-rolled _owner_identity middlewares and MagicMock claim stubs redundant; (3) test/test_agent_config_owner_gate_invariant.py (added by f38562c), the registrar-wide walk whose _KNOWN_UNGATED_ROUTES debt list enumerates EXACTLY this PR's 20 routes plus 4 others, with _MAX_KNOWN_UNGATED_ROUTES = 24; (4) the six sibling mutations the PR body still defers to #6224 -- require_owner_dashboard_request(request, ...) is on main at connections.py:185 (mcp_oauth_relay), :336 (connections_mint), :485 (connections_cancel), :668 (connections_premint) and files.py:3682 (dashboard_config.write), with the two onboarding-import routes recorded as _PRE_OWNER_EXCLUSIONS; that paragraph of the body is stale; (5) handlers/agents.py:150 _require_owner already delegates to the shared guard on main, which makes this PR's test/test_stale_owner_session_signal.py retarget cosmetic rather than load-bearing.

What is still genuinely yours

The entire security payload -- 20 route gates, the guard extension, the kiro_prerequisite migration, and the new invariant test -- is absent from main. (a) ZERO of the 20 routes is gated: git grep 'require_owner_dashboard_request|is_owner_dashboard_request' origin/main -- handlers/mcp.py handlers/mcp_custom.py handlers/mcp_discover.py handlers/core.py returns NOTHING, and main's api_mcp_probe / api_mcp_sync / api_mcp_toggle / api_theme_config(PUT) / api_kirocrew_config(PUT) / api_kirocrew_config_patch all fall straight through to body = await request.json() or their first side effect. Every one of the 19 new operation labels is absent from src/ (mcp.probe, mcp.measure, mcp.quarantine_clear, mcp.sync, mcp.apply, mcp.toggle, mcp.toggle_tool, mcp.toggle_all, mcp.remove, mcp.server_detail, mcp.custom_add, mcp.custom_update, mcp.discover_install, mcp_gateway.enable, mcp_gateway.set_stub, mcp_gateway.resolve_refresh, config.theme.write -> 0 files each; config.update and config.patch DO appear in core.py at 1259/1396/1413/1441 and 1859 but only as pre-existing SEL operation= labels inside the handlers' own _deny/_log_sel, never as an owner gate). main's OWN test file names these 20 as debt: _KNOWN_UNGATED_ROUTES documents them as 'candidates for future owner-gating work'. (b) The guard's three new keyword params are unlanded -- main's signature is exactly async def require_owner_dashboard_request(request: web.Request, operation: str); allow_internal_auth -> 0 hits in src/, and main's guard hardcodes resources="non_owner_block" and passes no error= to the SEL record or to _owner_denial_response. So the X-Internal-Secret opt-in for PUT/DELETE /api/mcp/servers/{name} has no mechanism on main. (c) handlers/kiro_prerequisite.py on main still carries its module-local _LOCAL_DASHBOARD_OWNER_SUBJECTS (line 23), _is_dashboard_owner (line 66) and _dashboard_owner_only (line 78, with operation="kiro_prerequisite_access"), called at lines 117/124/147/209 -- the migration is unlanded. (d) test/test_mcp_config_endpoints_owner_auth.py does not exist on main (git ls-tree origin/main <path> -> empty), so the 4 tests pinning the 20-route set, the auth-before-body-parse ordering, app-token refusal, and the internal-auth exception being limited to server registration are all new. (e) Three residual redundancies against #6245 that a rebase must resolve rather than land: the PR adds a byte-identical second copy of is_owner_dashboard_request + _LOCAL_DASHBOARD_OWNER_SUBJECTS into _shared.py while source_providers.py:6048/:5993 keeps the original AND stays the guard's own lazy import (the PR does not touch source_providers.py); it hand-rolls owner-identity scaffolding in 13 test files instead of using the landed test/dashboard_owner_helpers.py; and it never prunes its 20 now-gated routes from main's _KNOWN_UNGATED_ROUTES nor lowers _MAX_KNOWN_UNGATED_ROUTES from 24 to 4, which that test's own docstring requires ('lower _MAX_KNOWN_UNGATED_ROUTES to the new size to keep the ratchet tight').

Suggested action: REBASE — the remainder is real work; rebase onto the landed part rather than closing.


From a repository-wide duplicate/overlap audit of every pull request open against main (2026-09-02, 330 PRs, one reviewer per PR). Each PR was read as its full merge-base diff plus its description and every comment and review, then compared against each candidate PR's own diff and against origin/main at 1a765b88ceb7. This PR is not being closed — the note is informational. If the reading is wrong, please correct the reasoning rather than just the conclusion.

@bolichen97

Copy link
Copy Markdown
Contributor

Open PR relationship audit

This is a consolidated, point-in-time code-level audit note. It compares complete merge-base diffs and current/merged code; it does not treat a shared topic as duplication or partial coverage as completion.

Relationship findings

  • PR #7308 is OVERLAPPING relative to this PR. The goals differ or the implementations can complement each other; this is not a duplicate claim. Recommended action for PR #7308: CONTINUE_DEVELOPMENT. Same nine handlers, same lines, complementary goals. Neither should be closed; sequence them and have the second author rebase onto the first. Files: src/kiro_crew/dashboard/handlers/mcp.py.
  • PR #7393 is OVERLAPPING relative to this PR. The goals differ or the implementations can complement each other; this is not a duplicate claim. Recommended action for PR #7393: REBASE. Same campaign, no code conflict, but they entrench two different owner-gate spellings and error codes. Worth one maintainer decision on whether the skills family should land on the shared _shared.py boundary; that decision should not block 7393, since 5161 gives the skills routes no coverage at all. Files: src/kiro_crew/dashboard/handlers/_shared.py.
  • This PR is PARTIALLY_COVERED with PR #6245. Coverage is explicitly incomplete; this finding is not a completion or closure claim. Recommended action for PR #5161: REBASE. Main landed the boundary this PR builds on, not any route it gates. Rebasing onto f38562c lets the PR drop the duplicated predicate, reuse test/dashboard_owner_helpers.py, and prune its 20 entries from _KNOWN_UNGATED_ROUTES while keeping the whole security payload. Files: src/kiro_crew/dashboard/handlers/_shared.py, src/kiro_crew/dashboard/handlers/mcp.py, test/test_mcp_config_endpoints_owner_auth.py.

No PR, Issue, label, branch, or review state was changed by the relationship-note portion of this audit.

@bolichen97

Copy link
Copy Markdown
Contributor

Rebased onto main 9af9543b0 by a maintainer as part of the 2026-09-08 open-PR audit (was 880 commits behind).

Conflict resolutions:

Rebase follow-ups: kiro_prerequisite.api_kiro_prerequisite_update_cli is new on main and called the _dashboard_owner_only helper you removed, so it now uses the shared guard; test_stt_config_field_types.py and test_config_agent_fields_redaction.py are new on main and hit now-gated routes, so they get owner claims via main's dashboard_owner_helpers.

Gates run locally on changed files: black (8 files remain in .github/black-baseline.txt, unchanged), isort, flake8, and pytest across the 25 affected test files (all green).

Please review the resolutions. A maintainer push makes the maintainer the last pusher, so a second approver is needed under the repo's last-push rule. Reply if anything looks wrong.

Note, not changed here: main's test_agent_config_owner_gate_invariant.py still lists all 20 of these routes in _KNOWN_UNGATED_ROUTES with the ceiling at 20. Now that they are gated, that debt list and its ceiling can be shrunk in this PR.

@iamwhatever

Copy link
Copy Markdown
Contributor

Rebased onto current main by a maintainer and force-pushed to this branch (investigate/issue-5014), head is now 0ae017957addfda3478f9d9f9899c99c12355681. Nothing about what the PR does was changed: the diff against main is 25 files, +485/-88, versus +486/-88 before the rebase (the one-line difference is the conflict resolution below).

Conflict resolved

One conflict, in src/kiro_crew/dashboard/handlers/kiro_prerequisite.py, in the probe-failure backstop of the status handler. main had since added a probe_error= kwarg to _not_ready_snapshot(...) and still called this module's local _is_dashboard_owner(request); this PR called the shared is_owner_dashboard_request(request) without the kwarg. Resolution keeps both sides' intent:

        snapshot = _not_ready_snapshot(
            bool(service.initial_setup_complete),
            probe_error=f"{type(exc).__name__}: {exc}"[:400],
        )
    if is_owner_dashboard_request(request):

That is, main's probe_error= line is kept verbatim, and the call goes to the shared predicate. This PR turns _is_dashboard_owner in this file into a thin alias over is_owner_dashboard_request for sibling modules that import it by name, so the file that defines the alias should not route its own call through it.

_dashboard_owner_only is gone from this file, which is this PR's own doing (replaced by the shared require_owner_dashboard_request); a symbol check against main on every touched source file shows no other function dropped, and nothing anywhere still references the removed helper.

Verification run before the push

  • git diff --stat origin/main...HEAD: 25 files changed, 485 insertions, 88 deletions.
  • Symbol check on each touched non-test source file (def names on main minus def names at head): empty apart from the deliberate _dashboard_owner_only removal above.
  • The 19 test files this PR touches: 1032 passed, 0 failed.
  • test/test_agent_config_owner_gate_invariant.py: 4 passed.
  • isort --check-only, flake8, mypy src/kiro_crew/ (1673 files), scripts/check_black_formatting.py, scripts/check_comment_history.py and scripts/check_changelog_history.py against origin/main: all clean. The six touched files black would reformat are all already listed in .github/black-baseline.txt, so they are pre-existing and the gate passes.

One thing for a follow-up, not fixed here

After the rebase is_owner_dashboard_request is defined twice, with byte-equivalent bodies:

  • src/kiro_crew/dashboard/handlers/_shared.py:58 (added by this PR)
  • src/kiro_crew/dashboard/handlers/source_providers.py:6587 (already on main)

_shared.py is the right home: source_providers imports from _shared, while _shared's import of source_providers on main is deferred inside a function to avoid the cycle. Collapsing the copies is deliberately left out of this PR to keep the rebase behaviour-neutral, and wants its own change.

@iamwhatever

Copy link
Copy Markdown
Contributor

The 10 red backend shards are this PR, and four of them need an owner-gate decision

Shards 1, 3, 4, 5, 7 fail on both 3.12 and Windows — the same five file-shards on each platform, which is what a stable path-hash shard assignment (scripts/ci_file_shards.py) gives for a platform-independent failure. All of it reproduces on Linux/3.12 locally at head 0ae017957, so none of this is a Windows divergence.

Four distinct causes.

1. The _is_dashboard_owner alias is not behaviour-preserving (shard 3, 19 tests)

test/test_agent_sdk_backend_install.py — owner requests now get 403, and _deny_non_owner._audit shows up where the test expects its own offloaded callable:

FAILED ...::TestEndpointPayloadShape::test_owner_gets_one_row_per_backend_in_the_pinned_shape - assert 403 == 200
FAILED ...::TestRecheckEndpoint::test_the_successful_mutation_is_audited - AssertionError: assert 'denied' == 'success'
FAILED ...::TestRecheckEndpoint::test_the_clear_runs_before_the_probe - AssertionError: assert [] == ['clear', 'probe']

The predicate this PR removed read the app claim with .get:

return request.get("app") == "" and (...)

The shared is_owner_dashboard_request it now aliases reads it with in + []:

if "app" not in request or request["app"] != "" or not caller:
    return False

On a real web.Request those are identical. On the MagicMock request this test file builds, only req.get is overridden, so "app" not in request falls through to MagicMock.__contains__, which answers False — every owner is refused.

Smallest behaviour-preserving repair, in _shared.is_owner_dashboard_request:

if request.get("app") != "" or not caller:
    return False

Equivalent on real requests (missing key -> None != "" -> refuse), and it restores the 19 tests. Not pushed, because the rest below changes what the right shape is.

2. The new gate 500s where the test app has no state (shards 5 and 7, 27 tests)

test/test_config_live.py (6) and test/test_decisions_config_api.py (21) get 500 where they expect 200/400:

File "src/kiro_crew/dashboard/handlers/core.py", line 1561, in api_kirocrew_config
File "src/kiro_crew/dashboard/handlers/_shared.py", line 2637, in require_owner_dashboard_request
File "src/kiro_crew/dashboard/handlers/source_providers.py", line 6589, in is_owner_dashboard_request
KeyError: 'state'

request.app["state"] is unguarded. On main nothing reached it from these routes; this PR adds the gate to api_kirocrew_config PUT and api_kirocrew_config_patch, and both suites drive apps that never register state. Guarding the lookup turns the 500 into a 403 — it does not make these tests pass, because their requests carry no owner identity. Either those ~27 tests learn one, or these two routes are not blanket-gated.

3. Blanket-gating api_kirocrew_config_patch breaks a deliberate carve-out (shard 4)

FAILED test/test_usage_scrape_editable.py::test_a_non_owner_may_still_switch_the_billing_off - {"error": "owner authorization required", "code": "owner_only"}

That test's docstring is "Stopping spend is never gated: the narrower choice always composes." main already gates this route owner-only for exactly one field in exactly one direction:

# ── Enabling the billed credit-meter fallback is owner-only ──
if path_key == "dashboard.usage_text_scrape_enabled" and value is True:
    denial = await require_owner_dashboard_request(request, "config.patch.usage_text_scrape")

The new gate at the top of the handler makes that field-level check redundant and removes the asymmetry. Whether every config PATCH becomes owner-only, or the gate keeps a carve-out for narrowing a value, is a product call rather than a test repair — which is why nothing is pushed here.

4. The error-code ratchet is stale (shard 1, both platforms)

FAILED test/test_error_code_contract.py::test_baseline_is_not_stale

python test/test_error_code_contract.py --update re-snapshots it, but the counts move with the decision in 2 and 3, so it belongs last.

Also worth noting: _shared.is_owner_dashboard_request is a verbatim copy of source_providers.is_owner_dashboard_request, and require_owner_dashboard_request still imports the source_providers one. The consolidation currently leaves two copies of the predicate it was meant to unify.

Coverage Gate is failing on unrelated PRs too and is out of scope here.

@iamwhatever

Copy link
Copy Markdown
Contributor

Shard reds cleared, one left for a product ruling

Head 72146d1ea (2 commits, +504/-95). 93 of 97 lanes green.

Fixed — the 10 red backend shards came from three consequences of one change, not ten defects:

Was red Count Cause Fix
test_agent_sdk_backend_install 16 (403 for an owner) The gate moved to _shared with its app-claim test re-spelled as "app" not in request. That is equivalent on a real request, and not on this file's _request() stub, which overrides only .get — as the predicate it was written against required. is_owner_dashboard_request reads the claim with .get again. An absent claim answers None, which already is not "" and so already denies, without asking every caller to stub __contains__.
test_decisions_config_api, test_config_live 25 (500, KeyError: 'state') Both register the now-gated config routes on a bare web.Application: no state key, no owner claim, so the gate answered before the contract under test. Both fixtures go through dashboard_owner_helpers.as_owner, which exists for exactly this case and is what the other 20 fixtures in this PR already use.
test_error_code_contract::test_baseline_is_not_stale 1 Dropping the codeless 403 from kiro_prerequisite.py took its missing_code to 0, leaving the ratchet looser than the code. Regenerated with --update: missing_code 1118 → 1117, _compliant 2132 → 2212.

Verified locally: 4475 passed across the 61 test files that reference the owner predicate. test_instances.py::TestSshTunnelMultiplexing fails identically on origin/main (no usable ssh on that host). Backend Tests (Windows) (5) failed once on test_decisions_end_to_end — a file with no reference to the gate — and passed on a bare re-roll.

Still red, deliberately: a product decision

test/test_usage_scrape_editable.py::test_a_non_owner_may_still_switch_the_billing_off is the only remaining test failure, on Linux, Windows and macOS shard 4. It is untouched: not deleted, skipped, xfailed or rewritten, and no carve-out was added to the gate.

Its docstring pins "stopping spend is never gated". This PR's blanket owner gate on PATCH /api/config/kirocrew contradicts that directly. The question is not which side has the bug — it is which rule the product wants:

  • every config write is owner-only, and the spend-off carve-out is retired (update the test), or
  • the carve-out survives, and the gate needs an explicit exemption for switching billing off (update the handler).

Coverage Gate is purely downstream of this (backend-test=failure -- failing closed) and clears on its own once the ruling lands.

@iamwhatever

Copy link
Copy Markdown
Contributor

The shard-4 red is not from this PR

Backend Tests (3.12, 4), Backend Tests (Windows) (4) and the downstream Coverage Gate are failing on a main-inherited test, not on anything in this diff.

Failing test

test/test_pending_boundary_consumer_semantics.py::test_running_and_turn_running_slot_readers_are_enumerated

What differs. The test AST-scans src/kiro_crew/dashboard/ for direct reads of slot.running / slot.turn_running and asserts an exact site set. On current main the actual set has one site the expected set lacks, and lacks four the expected set has:

Left (actual) contains 1 more item:
  ('chat_handlers.py', '_switch_target_busy'): frozenset({'running'})
Right (expected) contains 4 more items:
  ('chat_handlers.py', 'api_chat_slot_agent'):            frozenset({'running'})
  ('chat_handlers.py', 'api_chat_slot_model'):            frozenset({'running'})
  ('chat_handlers.py', 'api_chat_slot_reasoning_effort'): frozenset({'running'})
  ('chat_handlers.py', 'api_chat_slot_workspace'):        frozenset({'running'})

The four handlers still exist and still refuse a switch mid-turn. Only the attribution moved: their inline slot.running read was hoisted into a shared helper, so the scanner now credits the helper instead of each caller.

Introducing commit. af0f1867808351cb2390b9ba7e078b4dbd8e8881 — "fix(dashboard): refuse a slot switch while a sibling alias cold-starts" — added _switch_target_busy to chat_handlers.py. The test's expected set was not updated.

The enumeration test itself is newer than that refactor (2515d7b07be391a4584b9a7485fffe93c59620c0), and was written against a pre-refactor base, so it was red from birth on main. Verified: it fails at that very commit, with no PR involved.

Reproduced on pristine main, no PR merge ref, at 0a80050938cfac1cc90e239a8ad02910ec4dbe07:

git worktree add --detach /tmp/probe origin/main
cd /tmp/probe
PYTHONPATH="$PWD/src" python -m pytest \
  test/test_pending_boundary_consumer_semantics.py -q -p no:cacheprovider -n0
# 1 failed, 8 passed

Tracking / fix. Already filed and already being fixed — nothing is needed from this PR:

I applied 12718 and 12715 to a pristine main worktree in turn; each takes the file to 9 passed.

Please ignore the shard-4 / Coverage Gate red here. It clears on this PR once a fix lands on main and the branch is rebased. No push to this PR is required.

@iamwhatever

Copy link
Copy Markdown
Contributor

Ruling: the spend-off carve-out stays

test_usage_scrape_editable.py::test_a_non_owner_may_still_switch_the_billing_off was
the one red left on this PR. It is the spec, not a defect, so it was not edited,
skipped, or xfailed.

Why. main gates dashboard.usage_text_scrape_enabled deliberately and
asymmetrically: the per-field gate in api_kirocrew_config_patch fires only on
value is True, under a comment that says so in as many words — "turning billing OFF
must never require authorization. Refusing that would leave someone able to see spend
they cannot stop, and the narrower choice always composes." The two telemetry writes
right below it are shaped the same way. This PR's route-level
require_owner_dashboard_request(request, "config.patch") sat above all of that and
reversed it for every field at once, including the disable. That was incidental to the
PR's goal, not part of it.

What changed. api_kirocrew_config_patch now reads the requested direction before
authorizing, and skips the route-level gate for exactly one write:
dashboard.usage_text_scrape_enabled = false. Everything else this PR gates stays
gated, including the matching enable, which main's own per-field gate further
down already refuses through the same shared helper — so the enable is still
403 owner_only and nothing is written.

A bodyless or unparseable request names no direction, so it is not the carve-out and
is still refused before any field is validated. That is what
test_every_targeted_mutation_rejects_non_owner_before_body_parse asks for, and it
still passes.

No new helper, flag, or config knob: the gated half calls this PR's own shared
require_owner_dashboard_request. Diff cost is +18/−2 on
src/kiro_crew/dashboard/handlers/core.py.

Scope note for a reviewer. The carve-out is drawn at the billed field only. The
telemetry.beacon_enabled and telemetry.enabled disables, which main also left
ungated for the composability reason quoted above, are now owner-only under this PR's
route-level gate. That is a privacy-preference asymmetry rather than a spend one, and
narrowing it was left in place deliberately — say the word if you want it drawn the
same way as the billed field.

Verification. 1286 passed across the 21 test files this PR touches plus
test_usage_scrape_editable.py and test_agent_sdk_backend_install.py. mypy,
flake8, black and isort clean on core.py. The error-code ratchet regenerates
byte-identical, so the gate change moves no count.

A maintainer can reverse this ruling — it defaults to the documented design, it is not
a preference of mine. If the blanket gate is what you want, the test's docstring and
main's comment are the two things that would need to change with it.

@iamwhatever

Copy link
Copy Markdown
Contributor

Your shard-1 red is not from this PR. origin/main itself is red on one stale test:

test/test_mcp_debug.py::TestTheRouteAuthorizationMatrix::test_the_three_diag_routes_relay_501_until_diag_lands
  AssertionError: api_debug_processes

It landed in #12731 asserting the three diag routes answer 501 "until diag lands";
#12745 then landed diag/procs.py, so api_debug_processes answers instead and the
premise died. It takes down Backend Tests (3.12, 1), (Windows) (1), (macOS) (2)
and cascades into Coverage Gate on every open PR.

Fix is up at #12865 (test-only, +47/-6). No action needed here — once it merges,
rebase and the shard goes green. Not rerunning anything on this PR.

@iamwhatever

Copy link
Copy Markdown
Contributor

Rebased onto main (64f3b5811) to pick up #12865, which fixed the stale test_mcp_debug 501-until-diag test that was this PR's only remaining red. A rerun could not pick it up — a rerun replays the recorded merge sha — so a rebase was the only route.

No code change. Shape is identical: 28 files, +522/-97, 2 commits, no deletions, both authors preserved. The one conflict was error-code-baseline.json (main's ratchet moved); resolved by taking main's side and regenerating with python test/test_error_code_contract.py --update, nothing else — missing_code 1115 → 1114 (this PR's kiro_prerequisite.py entry), _compliant 2234 → 2274 (main's own movement).

@iamwhatever

Copy link
Copy Markdown
Contributor

On the fenced GPT finding at core.py:2696 (spend-off carve-out)

The finding is accurate about the behaviour and is not a defect this PR introduced. It
is main's own standing product ruling, carried forward deliberately.

main already lets a non-owner PATCH dashboard.usage_text_scrape_enabled to false.
Its per-field gate is written to fire on the ENABLE only
(src/kiro_crew/dashboard/handlers/core.py:2839 on main), and the comment above it
states the reasoning verbatim:

Only the ENABLE is gated, exactly like the two telemetry writes below: turning billing
OFF must never require authorization. Refusing that would leave someone able to see
spend they cannot stop, and the narrower choice always composes.

And main pins it with a test this PR does not touch:
test/test_usage_scrape_editable.py:145,
test_a_non_owner_may_still_switch_the_billing_off — "Stopping spend is never gated: the
narrower choice always composes."

So the carve-out at the new route-level owner gate (core.py:2694-2699 on this head) is
what keeps that contract intact. Removing it would make the route refuse the disable,
turning main's green test red and reversing a documented decision — the opposite of this
PR's stated intent, which is to reach the owner gate the way its existing callers already
did.

Note on process: this is a fork PR, so the GPT lane consumes no /ai-review override
and re-rolls fresh on every push. Nothing here is re-rollable into green, and no code
change is appropriate. Reversing the spend-off carve-out is a product ruling, so it needs
a maintainer decision rather than a review round.

This head is a rebase onto 64f3b5811 to pick up #12865; it carries no code change.

@iamwhatever

Copy link
Copy Markdown
Contributor
  • Fixed in the description: the six siblings are gated on base; the gap is test coverage span=25b0c55b3355

The lane is right and the claim was stale. Checked each site on origin/main
(64f3b5811) — all six already call require_owner_dashboard_request:

site on main operation
handlers/connections.py:190 mcp_oauth_relay
handlers/connections.py:341 connections_mint
handlers/connections.py:572 connections_cancel
handlers/files.py:6182 dashboard_config.write
handlers/onboarding_import.py:595 onboarding import
handlers/onboarding_import.py:618 onboarding import

So "remain outside this boundary" was true when it was written and is not true now.
Corrected in the description: those routes reach the gate, and what they lack is a place in
the registrar-walk invariant this PR adds — so a future ungated sibling there would not be
caught. That test-coverage gap is what #6224 now names.

Description-only; no code change on this head.

@iamwhatever

Copy link
Copy Markdown
Contributor
  • Fixed in the description: the pre-gate parse on one route is now stated, not claimed away span=124d3b84a6fa

Accurate finding. api_kirocrew_config_patch does read the body before the owner gate, so
the unqualified "Authorization must happen before JSON parsing" over-claimed.

The parse has to come first there, and only there: main lets ANY authenticated dashboard
user turn the billed usage scrape OFF — its per-field gate fires on the ENABLE only
(handlers/core.py:2839 on main) and test_a_non_owner_may_still_switch_the_billing_off
(test/test_usage_scrape_editable.py:145) pins it. A gate placed before the parse cannot
tell that disable from an enable, so it would refuse the disable and turn that green test
red.

Description now scopes the ordering claim to exclude PATCH /api/config/kirocrew and says
what does and does not precede the gate there: the parse only — no lock, resolver, spawn or
write. An unparseable or bodyless request names no direction and is still refused before any
field is validated (handlers/core.py:2696).

Description-only; no code change on this head.

@iamwhatever

Copy link
Copy Markdown
Contributor
  • Accepted and deferred: 7 test files duplicate dashboard_owner_helpers.as_owner span=00992e9b2a42

Confirmed, with the file list. test/dashboard_owner_helpers.py:47 defines as_owner, and
each of these seven carries its own inline owner-shaping helper instead of importing it:
test_api_server.py, test_config_patch.py,
test_dashboard_handlers_core_coverage.py, test_mcp_custom_api.py,
test_mcp_discover_api.py, test_tailnet_governance.py, test_mcp_quarantine.py — one
each, seven copies of the same two facts (app claim empty, caller equals
state.owner_id).

Deferred rather than done on this head, for the reason the earlier rounds deferred the
inline denial sequences and the ungated siblings: this head exists to REMOVE a duplicate
(_shared.is_owner_dashboard_request, now gone — one def is_owner_dashboard_request
remains under src/, in source_providers.py:6600) and to rebase onto 64f3b5811 for
#12865. Rewriting seven unrelated test modules' fixtures in the same push would re-grow the
diff this round was opened to shrink, and would touch files whose only stake in this PR is
the owner fixture they already needed.

Added to #6224 alongside the other test-side consolidations. The duplication is inert — all
seven agree with as_owner today; the cost is drift if the owner shape ever changes, which
is exactly what one import would prevent.

@iamwhatever

Copy link
Copy Markdown
Contributor
  • Accepted as a justified rider: code: owner_only + the 401 stale relabel on the prerequisite denials span=521763eff0c4

Agreed with the lane's own reading — harm-free, and kept deliberately.

Base answered the kiro-prerequisite denials as a plain 403 with no machine-readable code. This
head routes them through the one shared gate, and that gate's tail is
_owner_denial_response, which adds the owner_only code and relabels a signed pre-owner
bootstrap subject to 401. Both come from reaching the shared gate rather than from any new
decision here — dropping them would mean giving this one module a private denial tail, which
is the duplication this PR exists to remove.

The user-visible text is unchanged, which is load-bearing: dashboard owner required is
asserted as rendered text by website/src/test/KiroPrerequisiteGate.test.tsx:565 and pinned
in a response body by test/test_skill_trust_store.py:1824. The added code is additive for
every existing consumer, and the baseline regeneration in this PR drives the
kiro_prerequisite.py missing_code bucket to zero as a direct consequence.

No change made; recorded as an accepted consequence of the consolidation.

@iamwhatever

Copy link
Copy Markdown
Contributor

Rebased onto main (76ce559ac)

Head is now 131aa34629, still 2 commits. Shape moved from 29 files / +506-95 to 20 files / +370-103, and the shrink is the point: main landed most of this PR's own boundary while the branch sat.

9 conflicts, not 4. main has been gating these routes itself, so every conflict was "main's gate vs this PR's gate" rather than a route change:

File Resolution
handlers/mcp.py kept main — it now gates all 13 mutating routes (mcp_probe, measure, quarantine_clear, sync, toggle, toggle_tool, toggle_all, remove, server_detail, apply, mcp_gateway.enable/set_stub/resolve_refresh). Byte-identical to main.
handlers/mcp_custom.py kept main — custom_add / custom_update already gated. Byte-identical to main.
test_gateway_appkit_endpoints.py kept main — its own owner-claims fixture for the registration transport.
test_handlers_mcp_coverage.py kept main — owner_claims(req) helper replaces this PR's inline claims dict.
test_mcp_apply.py kept main — same helper.
test_mcp_custom_api.py kept main — same helper.
test_mcp_gateway_control_plane.py kept main — same helper.
test_mcp_mutation_identifiers.py kept main — NoConfiguredOwner() state stand-in.
test_mcp_quarantine.py kept main — as_owner(app) wrapper.

Newly gated routes: none. test_mcp_config_endpoints_owner_auth.py walks the real agent_config registrar and asserts the found set equals its 20-entry expectation; it passes unchanged, so main registered no new mutating route in core.py / mcp.py / mcp_custom.py / mcp_discover.py since this branch was cut. What remains genuinely ungated on main, and is what this PR now carries: POST /api/mcp/discover/install, PUT/PATCH /api/config/kirocrew, PUT /api/config/theme, plus issue #5014's task 2 (converging _dashboard_owner_only onto the shared helper).

Retrospective on the usage_text_scrape_enabled carve-out

The asymmetry is deliberate and load-bearing: 10a8953f8a introduced it with the reasoning "the enable goes through the shared owner gate while the disable stays open to anyone: someone who can see spend must always be able to stop it", docs/feature-map/README.md records the field as "owner-only to enable", and test_a_non_owner_may_still_switch_the_billing_off pins the open disable. The carve-out stays, and the route gate keeps its early position: moving it below the per-field branch would be ~4 lines smaller but would run allowlist validation and the shutil.which PATH probe for dashboard.terminal.shell on a non-owner's input before the 403.

Two review findings from this revision, both applied

  • First Principles — require_owner_dashboard_request gained error=/resources= kwargs that only kiro_prerequisite.py passed, all three sites identically, to reproduce its own pre-convergence wording. Both kwargs are gone; _shared.py is now byte-identical to main, the three call sites are plain, and KiroPrerequisiteGate.test.tsx models the message the backend actually sends.
  • Design Review — the per-field enable gate sat behind the route gate and could no longer fire, while its comment still documented the pre-gate "any authenticated caller" bar. That branch is removed and the rationale now lives on the gate that enforces it, so there is one authorization record for this field instead of two that can drift.

Verification

--diff-filter=D empty · exactly one def is_owner_dashboard_request under src/ (source_providers.py:6600) · merge-base symbol diff loses only _dashboard_owner_only and _audit · test_usage_scrape_editable.py byte-identical to main · error-code ratchet regenerated and moves DOWN (missing_code 1115 → 1114, kiro_prerequisite.py drops out) · isort / flake8 / mypy / black-baseline / comment-history clean · 1257 backend tests and the 57 KiroPrerequisiteGate frontend tests pass.

The remaining red lanes on this head are GitHub App installation rate-limit casualties, not verdicts — each failing check-run says "could not run", and the underlying jobs die on API rate limit exceeded for installation while resolving the PR. They need a re-roll once the installation window resets.

@github-actions

github-actions Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

UX Review (Fable 5, fork) — 🟡 CONCERNS

UX-level review of 269ebd18c0388fa3e6e3bb2e1f6380d2a5050b85 via the fork AI-review pipeline — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

UX-Verdict: CONCERNS

Non-owner dashboard sessions now lose theme/language/onboarding writes silently — picks appear to work, revert on reload, and first-run replays every session.

Watch

  • The new gate on PUT /api/config/theme (core.py: require_owner_dashboard_request(request, "config.theme.write")) 403s callers the PR itself says exist ("an allow-listed messaging user holds one"), but the frontend writes fire-and-forget: persistTheme (useTheme.tsx:672–680) has no onError, and LanguageProvider.tsx:255 swallows failures. Server boot data overrides the local cache, so a non-owner's theme/language choice reverts on every reload, and onboarded: true / privacy_acked: true never persist — the first-run privacy dialog replays each session with no explanation. Low frequency (non-owner sessions only) × friction-to-loop impact × every session for those users. Smallest fix: surface the 403 via ErrorNotice on these writes, or have the client treat owner_only as "don't re-prompt".

Suggestions

  • The shared denial string owner authorization required (now returned by 20 routes) asserts what's missing but offers no action; append the next step, e.g. "owner authorization required — sign in from the owner account".

[UX-REVIEWED] 269ebd1

atomsbaza and others added 2 commits September 24, 2026 09:24
Rebase-integration fixes by Kiro Crew (original change by PISIT KOOLPLUKPOL):
- keep main's stale_owner_session_response relabel on the shared guard's
  deny path (lazy import; relabel-only, never grants)
- re-export is_owner_dashboard_request from source_providers for its
  existing importers; keep _LOCAL_DASHBOARD_OWNER_SUBJECTS from _shared
- give rebase-added TestFallbackModelPatch the owner-identity app pattern
- migrate the agents stale-label test to the shared guard
- regenerate error-code-baseline.json (missing_code 1285 -> 1284)

Co-authored-by: Kiro Crew <noreply@kirodotdev.github.io>
The gate moved to _shared with its app-claim test re-spelled as a
membership check. That is equivalent on a real request and not on the
request stubs the suite already had, so three separate reds fell out of
one change:

- test_agent_sdk_backend_install (16 tests, 403 instead of 400/200):
  its _request() stub overrides only .get, as the predicate it was
  written against required, so "app" not in request answered False and
  every owner call was denied. The predicate reads the claim with .get
  again -- an absent claim answers None, which already is not "" and so
  already denies, without asking every caller to stub __contains__.

- test_decisions_config_api and test_config_live (25 tests, 500 from
  KeyError: 'state'): both register the now-gated config routes on a
  bare web.Application, which carries no state and no owner claim.
  Both fixtures go through dashboard_owner_helpers.as_owner, which is
  what the repo already uses for this exact case.

- error-code-baseline.json: dropping the codeless 403 from
  kiro_prerequisite took its missing_code to 0, so the ratchet was
  looser than the code. Regenerated with --update.

Fourth red, and the only behavioural one: the blanket config.patch gate
removed an asymmetry main deliberately drew at that route.
test_usage_scrape_editable.py::test_a_non_owner_may_still_switch_the_
billing_off pins "stopping spend is never gated" -- main gates only
`dashboard.usage_text_scrape_enabled = True`, because refusing the
disable would leave someone able to SEE billed spend they cannot stop.
Gating the route as a whole silently reversed that.

api_kirocrew_config_patch now reads the requested direction before
authorizing, and skips the route-level gate for exactly that one
spend-off write. Everything else the route accepts stays owner-only,
including the matching ENABLE, which main's own per-field gate further
down already refuses with the same shared helper. A bodyless or
unparseable request names no direction, so it is not the carve-out and
is still refused before any field is validated -- which is what
test_every_targeted_mutation_rejects_non_owner_before_body_parse asks
for.

Verified: 1286 passed across the 21 files this PR touches plus
test_usage_scrape_editable.py and test_agent_sdk_backend_install.py;
mypy, flake8, black and isort clean on core.py; the error-code ratchet
regenerates byte-identical, so the gate change moves no count.

Co-authored-by: Kiro Crew <noreply@kirodotdev.github.io>

@bolichen97 bolichen97 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Request changes: merging this head into current main breaks 3 backend tests, and the PATCH carve-out now targets a key main deleted

Every comment in this thread was written before PR #12918 (merged 2026-09-24 07:35Z) and PR #12927 (merged 16:57Z). Both changed tests that call the routes this PR gates. The head merges into origin/main c66f95b without a textual conflict. On the merged tree, though, these tests fail, and they pass on pristine main:

  1. test/test_usage_scrape_editable.py:77 test_the_config_patch_refuses_the_key was rewritten by PR #12918. It sends a PATCH through a bare web.Application() with value: True, so the route gate at core.py:2745-2746 runs:
    if not (path_key == "dashboard.usage_text_scrape_enabled" and value is False):
        denied = await require_owner_dashboard_request(request, "config.patch")
    is_owner_dashboard_request then reads request.app["state"] and raises KeyError. The test gets a 500 instead of the 400 it expects.
  2. test/test_api_theme_config.py:205 and :225 were added by PR #12927. They call api_theme_config with a bare MagicMock(spec=web.Request). The new gate at core.py:633 answers 403 before the handler runs. One test expects 200 and the other expects HTTPBadRequest.

This PR's CI ran against a merge ref from before those merges, and a job rerun replays that recorded SHA. If this merges on the current green, those backend shards and Coverage Gate will fail on main and on every open PR. The damage stops at CI: production always sets app["state"], so users get the intended owner-only gate.

  1. PR #12918 also removed dashboard.usage_text_scrape_enabled from main, so the carve-out is dead code. The key is gone from _EDITABLE_CONFIG on main, and main's test checks that it stays gone. The comment at core.py:2725-2744 cites test_a_non_owner_may_still_switch_the_billing_off, which no longer exists. This is not a security hole: a non-owner PATCH of that key to false skips the gate but then gets 400 "field not editable", so nothing is written. It is, however, the only reason the PATCH gate still runs after request.json().

Smallest fix:

  • Rebase onto current main.
  • Give the three tests an owner identity. Use dashboard_owner_helpers.as_owner(app) for the TestClient test. Use owner_claims(req), or this file's _owner_request(), for the two MagicMock tests.
  • Delete the carve-out and its comment, and move the PATCH owner gate ahead of the body parse.

From a full open-PR audit against origin/main c66f95b (2026-09-25); findings were checked by independent reviewers reading the code. Reply here if this is wrong.

@iamwhatever

Copy link
Copy Markdown
Contributor

Thanks for this, @atomsbaza — the owner-gate fix is valuable. Since your branch is on a fork, I've opened an in-repo replacement, #14300, rebased onto current main and driven to green (all review lanes + PR Readiness pass), crediting you as co-author. It also drops the config.patch carve-out that had gone dead on main (the usage_text_scrape_enabled key was removed there). Closing this in favor of #14300, which Closes #5014. Your branch is left untouched.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fork Pull request from a fork (external contributor)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Owner-gate the remaining mutating MCP/config routes and converge the three denial-helper spellings

4 participants