Skip to content

fix(ui): Propagate agent 401 as HTTP 401 for transparent token refresh - #1447

Merged
huang195 merged 5 commits into
rossoctl:mainfrom
huang195:fix/stream-401-propagation
May 4, 2026
Merged

huang195 merged 5 commits into
rossoctl:mainfrom
huang195:fix/stream-401-propagation

Conversation

@huang195

@huang195 huang195 commented May 4, 2026

Copy link
Copy Markdown
Member

Summary

  • Streaming chat endpoint now returns HTTP 401 (instead of HTTP 200 + SSE error) when the agent rejects a token due to audience mismatch
  • This enables the existing frontend retry logic (PR fix(ui): Retry streaming chat on 401 with force-refreshed token #1430) to fire correctly: force-refresh the token, which picks up the new agent's audience scope from Keycloak, then retry transparently
  • Removes dead _stream_a2a_response function replaced by _stream_from_response (owns an already-opened connection)

Problem

When a user deploys a new agent:

  1. client-registration creates an audience scope in Keycloak with the agent's SPIFFE ID
  2. The user's existing token (issued before the scope existed) lacks the agent's audience
  3. AuthBridge rejects with 401
  4. Backend caught this as HTTPStatusError, yielded data: {"error": "Agent error: 401"} inside an HTTP 200 stream
  5. Frontend retry logic checks response.status === 401 but sees 200 — never retries

Fix

Open the agent connection in the endpoint function before committing to StreamingResponse. If the agent returns 401, raise HTTPException(401) directly. The frontend's existing forceRefreshToken() fires, gets a new token with the correct audience, and retries — all transparent to the user.

Test plan

  • New unit tests: test_chat_stream_401.py (agent 401 → HTTP 401, connection error → HTTP 503)
  • Existing test suite passes (256 tests)
  • Manual: deploy weather-agent on fresh cluster, verify first chat attempt succeeds without re-login

Assisted-By: Claude (Anthropic AI) [email protected]

The streaming chat endpoint wrapped agent 401 responses inside SSE error
events (HTTP 200), preventing the frontend's existing retry logic (PR
rossoctl#1430) from triggering token refresh. This caused users to see "Agent
error: 401" and need to manually re-login after deploying a new agent.

Root cause: when a new agent is deployed, client-registration adds its
audience scope to Keycloak. Tokens issued before that point lack the
agent's SPIFFE ID in the aud claim. The frontend's forceRefreshToken()
correctly obtains a new token with the updated audience, but it only
fires on HTTP 401 — not on SSE error payloads.

Fix: open the agent connection before committing to StreamingResponse.
If the agent returns 401, raise HTTPException(401) so the frontend sees
a real HTTP 401 and retries with a refreshed token transparently.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>

return StreamingResponse(
_stream_a2a_response(agent_url, request.message, session_id, authorization, user.username),
_stream_from_response(client, response, session_id, user.username),
huang195 added 2 commits May 3, 2026 21:54
The test was failing in CI because:
1. Only load_incluster_config was mocked but load_kube_config also gets
   called as a fallback, causing ConfigException in CI (no kubeconfig)
2. ruff format --check failed due to import ordering and line length

Signed-off-by: Hai Huang <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
The k8s config mocks in the app fixture only cover import time. Since
KubernetesService is instantiated per-request via the get_kubernetes_service
dependency, override it with a MagicMock to avoid ConfigException in CI
where no kubeconfig exists.

Signed-off-by: Hai Huang <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
@huang195

huang195 commented May 4, 2026

Copy link
Copy Markdown
Member Author

/run-e2e

@github-actions github-actions Bot added the safe-to-test Maintainer reviewed - safe to run E2E tests label May 4, 2026
@github-actions

github-actions Bot commented May 4, 2026

Copy link
Copy Markdown

E2E HyperShift Tests Started

Triggered by: @huang195
Commit: ff5b0bba0b5f9c17098e8d6d9d30bc7046336a7e
Workflow Run: View logs

Tests are running on OpenShift 4.20.11. This typically takes 30-45 minutes.


To re-run tests after new commits, comment /run-e2e again.

@github-actions

github-actions Bot commented May 4, 2026

Copy link
Copy Markdown

E2E HyperShift Tests Passed

Commit: ff5b0bba0b5f9c17098e8d6d9d30bc7046336a7e
Result: All tests passed
Workflow Run: View logs

The safe-to-test label indicates this commit has been approved for E2E testing.


If you push new commits, the label will be removed and you'll need to comment /run-e2e again.

Comment thread kagenti/backend/app/routers/chat.py Outdated
detail = response.text[:500]
except Exception:
detail = str(response.status_code)
logger.error(f"Agent error: {response.status_code}: {detail}")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Consider sanitizing detail, or not using f-strings, to avoid log injection.

Address CodeQL findings:
- Replace f-string logger calls with %-formatting to prevent log injection
- Strip newlines from agent response text before logging
- Do not expose raw exception details in HTTPException (log server-side instead)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
@github-actions github-actions Bot removed the safe-to-test Maintainer reviewed - safe to run E2E tests label May 4, 2026
@github-actions

github-actions Bot commented May 4, 2026

Copy link
Copy Markdown

New Commits Detected

The safe-to-test label has been automatically removed because new commits were pushed.

New HEAD: 8504227

For maintainers: Please review the new changes and comment /run-e2e to trigger E2E tests.

Security checklist

Before running E2E tests, verify the PR does NOT contain:

  • Changes to .github/workflows/ that bypass security
  • Changes to .github/scripts/ that could exfiltrate secrets
  • curl, wget, or nc commands to external URLs in scripts
  • Base64 encoding of environment variables
  • Printing secrets to logs (echo $SECRET)
  • Suspicious package installations

This is an automated security measure to prevent TOCTOU attacks

Fixes ruff format --check failure and addresses CodeQL log injection
finding (agent_url is already sanitized via sanitize_log but CodeQL
cannot track through the call chain).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
},
}

logger.debug("Starting A2A stream to %s with session_id=%s", agent_url, session_id)
@huang195

huang195 commented May 4, 2026

Copy link
Copy Markdown
Member Author

/run-e2e

@github-actions github-actions Bot added the safe-to-test Maintainer reviewed - safe to run E2E tests label May 4, 2026
@github-actions

github-actions Bot commented May 4, 2026

Copy link
Copy Markdown

E2E HyperShift Tests Started

Triggered by: @huang195
Commit: 2a46a2d3186e5306e3d1d31c191de9ed63ea3093
Workflow Run: View logs

Tests are running on OpenShift 4.20.11. This typically takes 30-45 minutes.


To re-run tests after new commits, comment /run-e2e again.

@github-actions

github-actions Bot commented May 4, 2026

Copy link
Copy Markdown

E2E HyperShift Tests Passed

Commit: 2a46a2d3186e5306e3d1d31c191de9ed63ea3093
Result: All tests passed
Workflow Run: View logs

The safe-to-test label indicates this commit has been approved for E2E testing.


If you push new commits, the label will be removed and you'll need to comment /run-e2e again.

@huang195
huang195 merged commit f9d8465 into rossoctl:main May 4, 2026
22 checks passed
@huang195
huang195 deleted the fix/stream-401-propagation branch May 4, 2026 13:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

safe-to-test Maintainer reviewed - safe to run E2E tests

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants