Skip to content

ECOPROJECT-4721 | fix: Validate JWT source_id in agent handlers#1213

Merged
openshift-merge-bot[bot] merged 1 commit into
kubev2v:mainfrom
AvielSegev:fix/ECOPROJECT-4721-agent-jwt-validation
Jun 2, 2026
Merged

ECOPROJECT-4721 | fix: Validate JWT source_id in agent handlers#1213
openshift-merge-bot[bot] merged 1 commit into
kubev2v:mainfrom
AvielSegev:fix/ECOPROJECT-4721-agent-jwt-validation

Conversation

@AvielSegev

@AvielSegev AvielSegev commented Jun 1, 2026

Copy link
Copy Markdown
Collaborator

Summary

Fixes critical security vulnerability where agent API handlers ignored JWT source_id claim, allowing cross-tenant access.

Changes

  • Added JWT source_id validation in UpdateSourceInventory and UpdateAgentStatus handlers
  • Both handlers now verify the JWT source_id matches the target source and return 403 if not
  • Updated tests to use AgentJWT in context and added new authorization tests

Security Impact

Prevents:

  • Cross-tenant write access with any valid agent token
  • Overwriting victim inventory
  • Planting malicious credential URLs
  • Corrupting migration assessments

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Agent authentication is now configurable via feature flag with automatic fallback mode when disabled
  • Security & Authorization

    • Enforced agent-based authorization across API endpoints, requiring agent authentication and source ID ownership verification
    • Agents can only access and modify resources associated with their assigned source ID, preventing cross-source access

@AvielSegev AvielSegev requested a review from a team as a code owner June 1, 2026 11:30
@AvielSegev AvielSegev requested review from amalimov and nirarg and removed request for a team June 1, 2026 11:30
@coderabbitai

coderabbitai Bot commented Jun 1, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@AvielSegev, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 38 minutes and 38 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 1666cb08-f14c-48ce-b4de-8df0cc7695e0

📥 Commits

Reviewing files that changed from the base of the PR and between f5f099b and e2d5955.

📒 Files selected for processing (6)
  • internal/api_server/agentserver/server.go
  • internal/auth/agent_authenticator.go
  • internal/auth/agent_authenticator_test.go
  • internal/auth/none_agent_authenticator.go
  • internal/handlers/v1alpha1/agent.go
  • internal/handlers/v1alpha1/agent_test.go
📝 Walkthrough

Walkthrough

Agent authentication is refactored from conditional middleware registration into a feature-flagged factory pattern; a new "none" authenticator handles disabled scenarios. Handler endpoints enforce source ownership via authorization checks that return 403 on mismatch. Tests migrate to AgentJWT contexts and validate both successful operations and authorization rejection.

Changes

Agent Authentication and Authorization

Layer / File(s) Summary
Feature-Flagged Authentication Architecture
internal/api_server/agentserver/server.go, internal/auth/agent_authenticator.go
The server no longer conditionally registers agent authentication middleware; instead, NewAgentAuthenticator accepts an enabled flag and returns either a production authenticator or a none authenticator, moving enablement logic into the factory.
None Authenticator Implementation
internal/auth/none_agent_authenticator.go
A new NoneAgentAuthenticator middleware decodes sourceId from JSON request bodies and injects an AgentJWT with issuer "none" and org "internal" into the request context for downstream handlers.
Handler-Level Source Ownership Authorization
internal/handlers/v1alpha1/agent.go
UpdateSourceInventory and UpdateAgentStatus extract agent identity from context and reject (403) requests when the agent's SourceID does not match the target resource's source identifier.
Agent Authenticator Tests
internal/auth/agent_authenticator_test.go
Tests are updated to call NewAgentAuthenticator(enabled bool, store) and cover both production and none authenticator paths; a new test verifies the none authenticator middleware accepts JSON sourceId requests.
Handler Authorization Tests
internal/handlers/v1alpha1/agent_test.go
All agent and source update tests switch from User to AgentJWT contexts; two new negative tests verify 403 rejection and confirm storage state remains unchanged when agent source ownership validation fails.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 A rabbit hops through feature gates,
No auth or full—both paths await!
Source IDs guard each handler's door,
With tests that check what came before.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title clearly identifies the main change: validating JWT source_id in agent handlers to fix a security vulnerability.
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.

✏️ 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.

@AvielSegev AvielSegev force-pushed the fix/ECOPROJECT-4721-agent-jwt-validation branch 2 times, most recently from c87fba0 to 29e0ec6 Compare June 1, 2026 11:33
@AvielSegev

Copy link
Copy Markdown
Collaborator Author

/hold

@AvielSegev AvielSegev force-pushed the fix/ECOPROJECT-4721-agent-jwt-validation branch 8 times, most recently from 682f244 to 7d4c8e0 Compare June 1, 2026 12:12
@AvielSegev

Copy link
Copy Markdown
Collaborator Author

/hold remove

@AvielSegev AvielSegev force-pushed the fix/ECOPROJECT-4721-agent-jwt-validation branch 3 times, most recently from 0536d2c to f5f099b Compare June 1, 2026 13:17

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🤖 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 `@internal/auth/agent_authenticator_test.go`:
- Around line 163-185: Update the test for NewNoneAgentAuthenticator's
Authenticator middleware to assert that the middleware sets an AgentJWT with the
expected SourceID in the request context and that the request body remains
readable for downstream handlers: modify the inner handler returned by serveHTTP
(used with noneAuthenticator.Authenticator) to retrieve the AgentJWT from
r.Context(), verify its SourceID equals "test-source-123", then attempt to read
the request body (e.g., ioutil.ReadAll or io.ReadAll) and validate the body
content matches the original JSON; keep the test's HTTP setup and assertions but
replace the simple 200-only handler with these context and body checks.

In `@internal/auth/none_agent_authenticator.go`:
- Around line 27-33: Validate that req.SourceID is non-empty before constructing
the AgentJWT: in the middleware/function that builds the AgentJWT (the block
creating AgentJWT with ExpireAt/IssueAt/Issuer/OrgID/SourceID), check
req.SourceID (or req.SourceId) and return a clear error response (e.g., a 400
Bad Request or a descriptive error) when it's empty or missing so you don't
produce an AgentJWT with an empty SourceID; include a concise error message like
"missing sourceId" and update any callers to handle that error path.
- Around line 22-25: The request body is consumed by json.NewDecoder when
decoding req, breaking downstream handlers; fix Authenticate/ServeHTTP in
none_agent_authenticator.go by reading and buffering the entire body (e.g.,
ioutil.ReadAll or io.ReadAll into bodyBytes), decode from a bytes.Reader or a
copy of those bytes to populate req, then restore r.Body by assigning r.Body =
io.NopCloser(bytes.NewReader(bodyBytes)) before calling next.ServeHTTP so
downstream handlers (e.g., UpdateSourceInventory, UpdateAgentStatus) can re-read
the payload; preserve the existing error handling (http.Error on decode failure)
and only restore/forward the body when decoding succeeds.

In `@internal/handlers/v1alpha1/agent.go`:
- Around line 85-90: The handler dereferences request.Body (and uses
request.Body.SourceId) before validating it, which can panic on empty requests;
add a nil-check and validation at the start of UpdateAgentStatus (before calling
auth.MustHaveAgent or any request.Body.SourceId access) and return a
400/UpdateAgentStatus400JSONResponse with a clear message when request.Body is
nil or missing SourceId; then proceed to compare agentJWT.SourceID to
request.Body.SourceId and return the existing UpdateAgentStatus403JSONResponse
only after the body is validated.
🪄 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: ASSERTIVE

Plan: Pro

Run ID: b5731741-f593-4632-8f88-5c2314c227aa

📥 Commits

Reviewing files that changed from the base of the PR and between ef51457 and f5f099b.

📒 Files selected for processing (6)
  • internal/api_server/agentserver/server.go
  • internal/auth/agent_authenticator.go
  • internal/auth/agent_authenticator_test.go
  • internal/auth/none_agent_authenticator.go
  • internal/handlers/v1alpha1/agent.go
  • internal/handlers/v1alpha1/agent_test.go

Comment thread internal/auth/agent_authenticator_test.go
Comment thread internal/auth/none_agent_authenticator.go Outdated
Comment thread internal/auth/none_agent_authenticator.go
Comment thread internal/handlers/v1alpha1/agent.go
@AvielSegev

Copy link
Copy Markdown
Collaborator Author

/hold cancel

Signed-off-by: Aviel Segev <asegev@redhat.com>
@AvielSegev AvielSegev force-pushed the fix/ECOPROJECT-4721-agent-jwt-validation branch from f5f099b to e2d5955 Compare June 1, 2026 13:39

@nirarg nirarg left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

/approve

@openshift-ci

openshift-ci Bot commented Jun 2, 2026

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: nirarg

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@openshift-ci openshift-ci Bot added the approved label Jun 2, 2026
@AvielSegev

Copy link
Copy Markdown
Collaborator Author

/retest

@nirarg

nirarg commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator

/lgtm

@openshift-ci openshift-ci Bot added the lgtm label Jun 2, 2026
@openshift-merge-bot openshift-merge-bot Bot merged commit fd21a23 into kubev2v:main Jun 2, 2026
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants