Skip to content

fix(portal): /auth/exchange runs again — settings_service was used, never imported (#2689) - #2690

Merged
vybe merged 2 commits into
devfrom
fix/2689-portal-exchange-settings-import
Sep 11, 2026
Merged

vybe merged 2 commits into
devfrom
fix/2689-portal-exchange-settings-import

Conversation

@dolho

@dolho dolho commented Sep 10, 2026

Copy link
Copy Markdown
Contributor

Fixes #2689.

The bug

portal_auth_exchange read the sliding-session idle window through a name the module does not import:

idle_s, _ = settings_service.get_portal_session_policy()   # NameError

grep -n settings_service src/backend/client_portal/router.py returned exactly one line — the call itself. So every request to the ent#163 trusted-issuer seam — how a licensee runs their own customer portal against Trinity while keeping their own IdP — raised NameError and answered 500.

Present on dev and on main (line 308 there). Released, not a dev-only regression. Introduced by ent#375 (#2099), which added the idle-window read to the response.

Blast radius, measured

Every other auth path on the same stack in the same minute:

platform admin login (POST /api/token)       -> 200
platform JWT works (GET /api/users/me)       -> 200
portal OTP request                           -> 200
portal session token works (/my-agents)      -> 200
platform email-code verify                   -> alive
THE BROKEN ONE: /auth/exchange               -> 500

Login, the Workspace, MCP keys and agent auth were all fine. And the failure is reachable only with a valid portal_delegate key — every other principal is refused 403 by the scope fence before reaching line 350 — so it is not externally probeable, and it is total for exactly the callers the route exists for. Which is why nobody had hit it: minting one of those keys is the first thing that reaches the line.

The fix

Reuse dependencies._portal_session_policy() instead of re-importing settings_service here.

dependencies.py performs the identical read correctly, and for two reasons that are both load-bearing:

  • the import is function-local, because settings_service imports db and a module-level import here would make a cycle out of one settings read;
  • it is wrapped in a degrade to the shipped policy, because this is an auth path and a settings hiccup must not 500 it.

The router copied the call and neither property. A second copy of that call would be a second chance to omit the degrade — and on an auth route the degrade is the half that matters. Importing an underscore-private name across modules follows existing practice in this tree (from ._common import _norm_ts, from services.git_service import _detect_git_dir, from services.template_service import _is_platform_injected).

Two lines of code; the rest of the diff is why.

Why eight tests missed it

test_ent163_portal_delegated_identity.py and test_163_portal_delegate_scope.py carry 8 tests between them — the mint, the access rule, scope fencing, disjoint identities, revocation. Every one of them goes through service.portal_exchange(...). None executes the route handler, and the NameError is in the handler body three lines after the service returns. A test that never runs the code under test cannot fail when that code is broken.

Proven rather than asserted — with the broken line reinstated:

FAILED tests/unit/test_2689_portal_exchange_route_executes.py::test_the_route_answers_instead_of_raising
FAILED tests/unit/test_2689_portal_exchange_route_executes.py::test_expires_in_is_the_real_idle_window
FAILED tests/unit/test_2689_portal_exchange_route_executes.py::test_the_settings_read_cannot_500_an_auth_path
3 failed, 29 passed

Only the three new tests fail. All 26 pre-existing ones still pass.

The new test

tests/unit/test_2689_portal_exchange_route_executes.py — 5 tests that drive the handler:

  • the route answers at all (the regression);
  • expires_in is the real idle window, compared against _portal_session_policy() rather than a literal, so the policy stays single-sourced instead of gaining a second home in a test;
  • a raising settings backend degrades instead of 500ing the auth path;
  • the delegate-scope 403 and the no-share 403 — gates the route already owned, previously asserted only against the service, now exercised where a caller actually meets them.

Its docstring states the narrow contract on purpose: it asserts almost nothing the other files already own. Its job is to be the test that goes red when the endpoint cannot answer.

Systemic check

An AST scan across src/backend for the same shape — a module calling .method() on a service singleton (settings_service, platform_audit_service, idempotency_service, rate_limiter, docker_service, heartbeat_service, capacity_manager, effect_guard) that it never binds — found no other instance.

Testing

  • tests/unit/test_2689_portal_exchange_route_executes.py — 5 new tests, each proven load-bearing by reinstating the defect.
  • The two existing ent#163 files re-run green (26 tests).
  • Full backend unit suite green.

Related to #2689

🤖 Generated with Claude Code

https://claude.ai/code/session_01RSjVEjay9ztC1oDXXkh9uN

…ever imported (#2689)

`portal_auth_exchange` read the sliding-session idle window through a name
the module does not import:

    idle_s, _ = settings_service.get_portal_session_policy()

`grep -n settings_service src/backend/client_portal/router.py` returned
exactly one line — the call. So every request to the ent#163 trusted-issuer
seam raised `NameError` and answered 500. Present on `dev` AND on `main`
(line 308 there): released, not a dev-only regression.

Introduced by ent#375 (#2099), which added the idle-window read to the
response. `dependencies.py` performs the identical read correctly, and for
two reasons that are both load-bearing: the import is function-local
because `settings_service` imports `db` and a module-level import would
make a cycle, and it is wrapped in a degrade to the shipped policy because
this is an auth path and a settings hiccup must not 500 it. The router
copied the call and neither property.

The fix reuses that reader rather than re-importing `settings_service`
here. A second copy of the call would be a second chance to omit the
degrade — and the degrade is the half that matters on an auth route.
Importing an underscore-private name across modules follows existing
practice (`from ._common import _norm_ts`, `from services.git_service
import _detect_git_dir`, `from services.template_service import
_is_platform_injected`).

Blast radius, measured on a live stack in one minute: platform login,
platform JWT, the portal OTP flow, portal session tokens, MCP keys and
agent auth all answered normally; only this route was down. The failure is
reachable only WITH a valid `portal_delegate` key — every other principal
is refused 403 by the scope fence before reaching the line — so it is not
externally probeable, and it is total for exactly the callers the route
exists for.

WHY EIGHT TESTS MISSED IT. `test_ent163_portal_delegated_identity.py` and
`test_163_portal_delegate_scope.py` cover the mint, the access rule, scope
fencing, disjoint identities and revocation — all through
`service.portal_exchange(...)`. None executes the ROUTE HANDLER, and the
NameError is in the handler body three lines after the service returns.
Proven rather than asserted: with the broken line reinstated, only the
three new tests fail and all 26 pre-existing ones still pass.

`tests/unit/test_2689_portal_exchange_route_executes.py` drives the handler.
It pins that the route answers at all, that `expires_in` is the real idle
window (compared against `_portal_session_policy()`, not a literal, so the
policy stays single-sourced), and that a raising settings backend degrades
instead of 500ing. It also re-pins the two gates the route already owned —
the delegate-scope 403 and the no-share 403 — which were previously
asserted only against the service.

An AST scan for the same shape (a module using a service singleton it never
binds) across `src/backend` found no other instance.

Related to #2689

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01RSjVEjay9ztC1oDXXkh9uN
Self-review of the fix above. Reusing `dependencies._portal_session_policy`
was right; importing it at MODULE SCOPE was not.

Both module-scope forms capture at import time — a `from`-import binds the
function object, `import dependencies as _deps` binds the module object —
and either goes stale if `dependencies` is re-imported after this module.
That is not hypothetical in this repo: `tests/unit/conftest.py` lists
`dependencies` in `_POP_PREFIXES`, and an autouse fixture evicts it from
`sys.modules` before AND after every unit test, deliberately, to stop
cross-file stub pollution.

Measured with the first version of this fix in place: a test's
`import dependencies` produced a DIFFERENT module object than the one
`client_portal/router.py` had captured, so patching the live module returned
(111, 222) while the route went on returning the shipped 604800. With the
`from`-import form the same thing happened one level tighter — the router
held the original function object and never saw the patch at all.

No production consequence: nothing pops modules at runtime, and the route
answers correctly either way. The consequence is that the route becomes
UNTESTABLE from the outside — which is exactly how the defect this PR fixes
reached `main`, so shipping the fix in a form with that property would be
tone-deaf.

The import moves inside the handler. It resolves through `sys.modules` at
call time and cannot diverge, and it is the same shape `dependencies.py`
already uses one level down (function-local, for the import cycle).

The late-binding guard test added alongside it is REMOVED rather than kept
green by weakening it: the harness's own eviction makes that assertion
unreachable here, and a test that fails for harness reasons teaches the next
reader the wrong lesson. The file now says so where the guard would have
been, so nobody adds a flaky one back.

The mutation check still holds: reinstating the original broken line fails
three of the five new tests and none of the 26 pre-existing ent#163 ones.

Related to #2689

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01RSjVEjay9ztC1oDXXkh9uN
@dolho

dolho commented Sep 10, 2026

Copy link
Copy Markdown
Contributor Author

Review — self-review, one finding, fixed in 127f7ebc

I wrote this PR, so this is not an approval (GitHub won't let it be one, and it shouldn't be). It is the review pass, and it found something worth changing.

Finding: the fix shipped with a second capture bug

Reusing dependencies._portal_session_policy was the right call. Importing it at module scope was not.

Both module-scope forms capture at import time — a from-import binds the function object, import dependencies as _deps binds the module object — and either goes stale if dependencies is re-imported afterwards. That is not hypothetical here: tests/unit/conftest.py lists dependencies in _POP_PREFIXES, and an autouse fixture evicts it from sys.modules before and after every unit test, deliberately, to stop cross-file stub pollution.

Measured with the first version in place:

DBG deps id = 129605896814656   router._deps id = 129605907711376   same: False
DBG deps()          = (111, 222)
DBG router._deps()  = (604800, 2592000)
DBG expires_in      = 604800

A test's import dependencies gets a different module object than the one the router captured. Patch the live module and the route goes on returning the shipped default. With the from-import form the same thing happens one level tighter — the router holds the original function object and never sees the patch at all.

No production consequence — nothing pops modules at runtime and the route answers correctly either way. The consequence is that the route becomes untestable from the outside, which is precisely how the defect this PR fixes reached main. Shipping the fix in a form with that property would have been tone-deaf.

The import moves inside the handler: it resolves through sys.modules at call time and cannot diverge, and it is the same shape dependencies.py already uses one level down (function-local, for the import cycle).

And the guard test is gone, on purpose

I added a late-binding guard, watched it fail for harness reasons, and removed it rather than weaken it until it passed. The eviction fixture makes that assertion unreachable in this suite; a test that goes red because of the harness teaches the next reader the wrong lesson. The file now carries a comment where the guard would have been, saying why, so nobody adds a flaky one back.

What I checked and did not change

  • Scope of the outage — re-verified on a live stack: platform login, platform JWT, portal OTP, portal session tokens, MCP keys and agent auth all fine; only this route was down. And it is reachable only with a valid portal_delegate key, since every other principal is refused 403 before the line. Not externally probeable; total for its actual callers.
  • The mutation check still holds after the change — reinstating the original broken line fails 3 of the 5 new tests and 0 of the 26 pre-existing ent#163 tests.
  • expires_in is compared against _portal_session_policy(), not a literal. Deliberate: a literal would make the test a second source of truth for a policy that has exactly one reader.
  • The degrade test patches one level deeper (settings_service.get_portal_session_policy), so it is unaffected by the module eviction — robust by construction rather than by luck.
  • AST scan across src/backend for the same shape (a module calling a method on a service singleton it never binds) — no other instance.

Not approving

Author and reviewer are the same person here. This needs a second pair of eyes on one question in particular: is a function-local import of an underscore-private name from dependencies the shape we want in a router? The alternatives are a public wrapper in dependencies (rename touches 5 call sites and a fixture that patches by name) or duplicating the read here (rejected — it duplicates the degrade, which is the load-bearing half). I think the current form is right, but it is the one judgement call in the diff.

🤖 Generated with Claude Code

https://claude.ai/code/session_01RSjVEjay9ztC1oDXXkh9uN

@vybe vybe 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.

merge-train: batch validated on train/20260911-0925 (#2701)

@vybe
vybe merged commit 8088f89 into dev Sep 11, 2026
25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants