Skip to content

fix(test-page): per-user test API keys and stale key prevention#910

Open
AnoshanJ wants to merge 4 commits into
wso2:mainfrom
AnoshanJ:fix/api-test-key
Open

fix(test-page): per-user test API keys and stale key prevention#910
AnoshanJ wants to merge 4 commits into
wso2:mainfrom
AnoshanJ:fix/api-test-key

Conversation

@AnoshanJ
Copy link
Copy Markdown
Contributor

@AnoshanJ AnoshanJ commented May 19, 2026

Problem

Three intermittent issues were observed in the agent Try-It (test) page:

  1. Multi-user 401s — The backend stored a single console-test key row per agent per environment. When two users (or two browser tabs) opened the same agent's test page, each IssueTestAPIKey call rotated that shared row, invalidating the other session's cached key and causing 401s.

  2. Stale key on tab refocus — When a user switched away, opening two tabs for the same agent try out view and came back, the test key was getting rotated, leaving a window where a rotated key could cause a 401.

  3. Message history bleed on agent switch — Navigating from Agent A to Agent B in the sidebar reused the same AgentChat component instance (React reconciliation), so the previous agent's messages, errors, and endpoint state leaked into the new agent's view.

Summary by CodeRabbit

  • New Features

    • Test API keys are now issued and managed individually per user.
    • Test API key data automatically refreshes when your browser window regains focus.
  • Improvements

    • Enhanced authentication validation for test API key requests.
    • Improved test component rendering stability.

Review Change Stack

AnoshanJ added 3 commits May 19, 2026 12:26
Each call to IssueTestAPIKey now derives the key name from a truncated
SHA-256 of the caller's JWT sub claim (console-test-<12 hex chars>).
This gives every user their own DB row per agent, so concurrent sessions
across users no longer rotate each other's keys.

- models: APIKeyTestKeyName → APIKeyTestKeyPrefix ("console-test-")
- services: add testKeyName(userSub) helper; update IssueTestAPIKey
  signature and body; tighten CreateAPIKey guard to strings.HasPrefix
- controllers: extract claims.Sub in IssueTestAPIKey handler and pass
  it to the service; return 401 when claims are absent

Signed-off-by: Anoshan Jayahanthan <101160077+AnoshanJ@users.noreply.github.com>
When a user switches tabs and comes back, the test key is re-fetched
immediately instead of waiting for the 9-minute refetchInterval. This
catches cases where another session rotated the key while the tab was
in the background, avoiding a 401 on the next send.

Signed-off-by: Anoshan Jayahanthan <101160077+AnoshanJ@users.noreply.github.com>
…rendering

Signed-off-by: Anoshan Jayahanthan <101160077+AnoshanJ@users.noreply.github.com>
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 19, 2026

📝 Walkthrough

Walkthrough

The PR implements per-user test API key isolation by deriving unique key names from JWT subject hashes, replacing a single global test key name. The service layer includes a new hashing helper, interface updates, and validation to reserve prefix-based names. The controller extracts JWT claims and passes the user subject. Frontend improvements enable cache refresh on window focus and proper component lifecycle management.

Changes

Per-User Test API Key Isolation

Layer / File(s) Summary
Test Key Naming Contract
agent-manager-service/models/apikey.go
Replace APIKeyTestKeyName constant with APIKeyTestKeyPrefix to support per-user test key derivation based on JWT subject hashing.
Service Implementation and Validation
agent-manager-service/services/agent_apikey_service.go
Add crypto/sha256 and encoding/hex imports; introduce helper to hash userSub into stable key names; update AgentAPIKeyServiceInterface.IssueTestAPIKey signature to accept userSub; modify CreateAPIKey to reserve any names starting with the test prefix; rework IssueTestAPIKey to use per-user keyName for DB lookups, broadcaster events, and response.
Controller JWT Integration
agent-manager-service/controllers/agent_apikey_controller.go
Import jwtassertion and update IssueTestAPIKey endpoint to extract JWT token claims from request context, return 401 if claims.Sub is empty, and pass claims.Sub to the service.
Frontend Cache and Component Updates
console/workspaces/libs/api-client/src/hooks/agent-api-keys.ts, console/workspaces/pages/test/src/Test.Component.tsx
Enable refetchOnWindowFocus: true for the test agent API key query to refresh credentials on window focus; add key={agentId} to AgentChat component to ensure React remounting on agent changes.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • rasika2012
  • RAVEENSR
  • a5anka

Poem

🐰 Per-user test keys now bloom,
Each user gets their own room,
No more global conflicts arise,
JWT subjects are the prize.
Fresh on focus, components remount,
A solid change, none in doubt! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main changes: per-user test API keys and prevention of stale key issues, directly matching the core problems addressed in the PR.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The PR description comprehensively covers all template sections with detailed problem statement, solution summary, implementation approach, and test plan.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
agent-manager-service/controllers/agent_apikey_controller.go (1)

262-266: 💤 Low value

Stale docstring: no longer uses a single fixed key name.

The comment still references "the single short-lived test API key" and "scoped to the fixed name 'console-test'", but the implementation now issues per-user keys derived from the JWT subject.

📝 Suggested update
 // IssueTestAPIKey handles POST /api/v1/orgs/{orgName}/projects/{projName}/agents/{agentName}/environments/{envID}/api-keys/test
 //
-// Issues (or rotates) the single short-lived test API key for the agent.
-// Used by the console Try-It flow. The key is test-scoped, scoped to the
-// fixed name "console-test", and never appears in the user-facing list.
+// Issues (or rotates) a short-lived test API key for the calling user.
+// Used by the console Try-It flow. Each user gets their own key (derived
+// from their JWT subject), so concurrent sessions don't invalidate each
+// other. Test keys never appear in the user-facing list.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@agent-manager-service/controllers/agent_apikey_controller.go` around lines
262 - 266, The docstring for IssueTestAPIKey is stale: it still says "single
short-lived test API key" and "scoped to the fixed name 'console-test'"; update
the comment in agent_apikey_controller.go for the IssueTestAPIKey handler to
state that it issues short-lived, per-user test API keys derived from the JWT
subject (rather than a single fixed key name), and adjust any wording about
scoping/visibility to reflect the current behavior (per-user console test keys
and how they appear in listings).
console/workspaces/libs/api-client/src/hooks/agent-api-keys.ts (1)

102-105: ⚡ Quick win

Update comment to reflect actual timing: 9 minutes, not 10.

The comment mentions "10-minute test API key" but the code uses 9 minutes for both staleTime and refetchInterval (lines 123-124).

📝 Suggested documentation fix
-// useTestAgentAPIKey issues (or rotates) a 10-minute test API key for the
+// useTestAgentAPIKey issues (or rotates) a 9-minute test API key for the
 // agent's Try-It flow. Each refetch rotates the same logical row on the
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@console/workspaces/libs/api-client/src/hooks/agent-api-keys.ts` around lines
102 - 105, The top comment above the useTestAgentAPIKey hook incorrectly states
"10-minute test API key" while the actual configuration uses 9 minutes; update
that comment to say "9-minute test API key" (or otherwise match the 9-minute
timing) so it reflects the values used for staleTime and refetchInterval in the
hook; locate the comment block above the useTestAgentAPIKey function and adjust
the wording to match the staleTime/refetchInterval constants used in the hook.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@console/workspaces/libs/api-client/src/hooks/agent-api-keys.ts`:
- Line 125: The query option refetchOnWindowFocus is set to true but the PR
description specifies "always"; update the useQuery call (the hook in
agent-api-keys.ts, e.g., the useAgentApiKeys/query options where
refetchOnWindowFocus is set) to use refetchOnWindowFocus: "always" so the query
refetches on every window focus regardless of staleness; if the intended
behavior was actually to only refetch when stale, instead update the PR
description to state `true` and explain the 9-minute staleness behavior.

---

Nitpick comments:
In `@agent-manager-service/controllers/agent_apikey_controller.go`:
- Around line 262-266: The docstring for IssueTestAPIKey is stale: it still says
"single short-lived test API key" and "scoped to the fixed name 'console-test'";
update the comment in agent_apikey_controller.go for the IssueTestAPIKey handler
to state that it issues short-lived, per-user test API keys derived from the JWT
subject (rather than a single fixed key name), and adjust any wording about
scoping/visibility to reflect the current behavior (per-user console test keys
and how they appear in listings).

In `@console/workspaces/libs/api-client/src/hooks/agent-api-keys.ts`:
- Around line 102-105: The top comment above the useTestAgentAPIKey hook
incorrectly states "10-minute test API key" while the actual configuration uses
9 minutes; update that comment to say "9-minute test API key" (or otherwise
match the 9-minute timing) so it reflects the values used for staleTime and
refetchInterval in the hook; locate the comment block above the
useTestAgentAPIKey function and adjust the wording to match the
staleTime/refetchInterval constants used in the hook.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ec5628fe-0dc5-4627-b553-125aa8670bc1

📥 Commits

Reviewing files that changed from the base of the PR and between 23940a2 and 8b9bffe.

📒 Files selected for processing (5)
  • agent-manager-service/controllers/agent_apikey_controller.go
  • agent-manager-service/models/apikey.go
  • agent-manager-service/services/agent_apikey_service.go
  • console/workspaces/libs/api-client/src/hooks/agent-api-keys.ts
  • console/workspaces/pages/test/src/Test.Component.tsx

Comment thread console/workspaces/libs/api-client/src/hooks/agent-api-keys.ts Outdated
Signed-off-by: Anoshan Jayahanthan <101160077+AnoshanJ@users.noreply.github.com>
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.

1 participant