Skip to content

HYPERFLEET-492 - refactor: replace OCM auth client with JWT-based auth#120

Open
kuudori wants to merge 1 commit intoopenshift-hyperfleet:mainfrom
kuudori:HYPERFLEET-492
Open

HYPERFLEET-492 - refactor: replace OCM auth client with JWT-based auth#120
kuudori wants to merge 1 commit intoopenshift-hyperfleet:mainfrom
kuudori:HYPERFLEET-492

Conversation

@kuudori
Copy link
Copy Markdown
Contributor

@kuudori kuudori commented Apr 30, 2026

Summary

  • HYPERFLEET-492

Test Plan

  • Unit tests added/updated
  • make test-all passes
  • make lint passes
  • Helm chart changes validated with make test-helm (if applicable)
  • Deployed to a development cluster and verified (if Helm/config changes)
  • E2E tests passed (if cross-component or major changes)

Summary by CodeRabbit

  • New Features

    • Standalone JWT authentication with RS256 verification and JWKS rotation support.
    • Cluster/NodePool lifecycle: adapters are hard-deleted once finalized and child resources are gone; finalized status now indicates WaitingForChildResources when applicable.
  • Removed

    • OpenShift Cluster Manager (OCM) SDK/CLI integration and related mocks.
  • Documentation

    • Updated docs and guides to reflect JWT-based authentication and removed OCM configuration/instructions.

@openshift-ci openshift-ci Bot requested review from Mischulee and vkareh April 30, 2026 18:43
@openshift-ci
Copy link
Copy Markdown

openshift-ci Bot commented Apr 30, 2026

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please assign tirthct for approval. For more information see the Code Review Process.

The full list of commands accepted by this bot can be found 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

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 30, 2026

Walkthrough

This pull request removes OCM/OCM SDK integration and related configuration/flags/mocks, replaces OCM-based authentication with a new JWKS-backed JWT middleware (RS256, issuer/audience validation, JWKS rotation), upgrades golang-jwt to v5 and adds keyfunc/jwkset, refactors environment/client initialization to stop creating OCM clients, updates server wiring to use the new JWT handler, adjusts config structs/flags/tests and test helpers to use a local TestAccount for JWT generation, and updates docs and CHANGELOG accordingly.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant JWTHandler
    participant Parser as JWT Parser
    participant JWKS as JWKS Provider
    participant MainHandler

    Client->>JWTHandler: HTTP Request (Authorization: Bearer <token>)
    alt Public Path (regex match)
        JWTHandler->>MainHandler: Forward Request
        MainHandler->>Client: Response
    else Protected Path
        JWTHandler->>JWTHandler: Validate header format
        alt Missing/Malformed
            JWTHandler->>Client: 401 Unauthorized
        else Well-formed Bearer
            JWTHandler->>Parser: Parse & validate token (RS256, exp, issuer, audience)
            Parser->>JWKS: Resolve key by kid (fetch/rotate if needed)
            alt Key resolution or parse error
                Parser->>JWTHandler: Validation Error
                JWTHandler->>Client: 401 Unauthorized
            else Validation success
                JWTHandler->>JWTHandler: Store *jwt.Token in context
                JWTHandler->>MainHandler: Forward Request (with token context)
                MainHandler->>Client: Response
            end
        end
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 31.82% 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 title directly and accurately describes the main change: replacing OCM authentication client with JWT-based authentication, which is the primary refactoring objective across the entire changeset.
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

Review rate limit: 9/10 reviews remaining, refill in 6 minutes.

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

Copy link
Copy Markdown

@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: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
docs/logging.md (1)

535-538: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Remove stale OCM environment variable references.

The test examples still reference OCM_ENV=integration_testing, but the OCM integration has been removed from the codebase per this PR's objectives. These environment variable references should be removed to align with the JWT-based authentication changes and prevent user confusion.

📝 Proposed fix to remove OCM_ENV references
 # Run tests with debug logging
-HYPERFLEET_LOGGING_LEVEL=debug OCM_ENV=integration_testing go test ./test/integration/...
+HYPERFLEET_LOGGING_LEVEL=debug go test ./test/integration/...
 
 # Run tests without OTel
-HYPERFLEET_TRACING_ENABLED=false OCM_ENV=integration_testing go test ./...
+HYPERFLEET_TRACING_ENABLED=false go test ./...
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/logging.md` around lines 535 - 538, The doc snippets still export the
removed environment variable OCM_ENV (e.g., "OCM_ENV=integration_testing") in
the test command examples; remove all occurrences of the
OCM_ENV=integration_testing token from the examples in docs/logging.md (and any
other similar command examples) so the lines read only the remaining env vars
(e.g., HYPERFLEET_LOGGING_LEVEL=debug go test ... and
HYPERFLEET_TRACING_ENABLED=false go test ...); search for the symbol OCM_ENV in
the file and delete those assignments to avoid referencing the removed OCM
integration.
🧹 Nitpick comments (1)
test/helper.go (1)

577-589: ⚡ Quick win

Include audience claim in helper JWTs when configured.

Line 579 mirrors configured issuer, but helper tokens ignore configured audience. When server.jwt.audience is set, these tokens won’t match middleware expectations.

Proposed update
 func (helper *Helper) CreateJWTString(account *TestAccount) string {
 	claims := jwt.MapClaims{
 		"iss":        helper.Env().Config.Server.JWT.IssuerURL,
 		"username":   strings.ToLower(account.Username),
 		"first_name": account.FirstName,
 		"last_name":  account.LastName,
 		"typ":        "Bearer",
 		"iat":        time.Now().Unix(),
 		"exp":        time.Now().Add(1 * time.Hour).Unix(),
 	}
+	if aud := helper.Env().Config.Server.JWT.Audience; aud != "" {
+		claims["aud"] = aud
+	}
 	if account.Email != "" {
 		claims["email"] = account.Email
 	}

As per coding guidelines, "Focus on major issues impacting performance, readability, maintainability and security. Avoid nitpicks and avoid verbosity."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/helper.go` around lines 577 - 589, The CreateJWTString helper currently
sets "iss" but omits the configured audience; update Helper.CreateJWTString to
read the configured audience (helper.Env().Config.Server.JWT.Audience) and, when
non-empty, set claims["aud"] = that value so generated test JWTs include the
expected audience claim and will match middleware validation; locate this change
inside the CreateJWTString method where claims are built and add the conditional
audience assignment.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@CHANGELOG.md`:
- Around line 12-13: Update the placeholder PR links in CHANGELOG.md that point
to "/pull/TBD" (e.g., the JWT auth entry and the Hard deletion entry and the
other occurrences at lines referenced) by replacing "TBD" with the actual PR
numbers for those changes; search for the "/pull/TBD" pattern in CHANGELOG.md
and substitute each with the correct numeric PR identifier so the links resolve
correctly and repeat for the occurrences noted (lines ~32-33 and ~45).

In `@docs/development.md`:
- Around line 121-125: Split the single blocking code block into two separate
terminal examples so readers can run the server and then call the API: create a
"Terminal 1" code block containing only the blocking command `make run` to start
the server, and create a "Terminal 2" code block containing the `curl -H
"Authorization: Bearer ${TOKEN}"
http://localhost:8000/api/hyperfleet/v1/clusters` command; ensure the text
labels clarify that Terminal 1 must be running before executing Terminal 2.

In `@pkg/config/flags.go`:
- Around line 32-33: Add documentation entries for the two new CLI flags added
via cmd.Flags().String for "--server-jwt-issuer-url" and "--server-jwt-audience"
to the configuration reference (docs/config.md): describe each flag, show the
default values (defaults.JWT.IssuerURL and defaults.JWT.Audience), indicate that
issuer URL is used for token validation and audience is optional, and add them
to the CLI flags table so operators can discover and configure server JWT
validation.

---

Outside diff comments:
In `@docs/logging.md`:
- Around line 535-538: The doc snippets still export the removed environment
variable OCM_ENV (e.g., "OCM_ENV=integration_testing") in the test command
examples; remove all occurrences of the OCM_ENV=integration_testing token from
the examples in docs/logging.md (and any other similar command examples) so the
lines read only the remaining env vars (e.g., HYPERFLEET_LOGGING_LEVEL=debug go
test ... and HYPERFLEET_TRACING_ENABLED=false go test ...); search for the
symbol OCM_ENV in the file and delete those assignments to avoid referencing the
removed OCM integration.

---

Nitpick comments:
In `@test/helper.go`:
- Around line 577-589: The CreateJWTString helper currently sets "iss" but omits
the configured audience; update Helper.CreateJWTString to read the configured
audience (helper.Env().Config.Server.JWT.Audience) and, when non-empty, set
claims["aud"] = that value so generated test JWTs include the expected audience
claim and will match middleware validation; locate this change inside the
CreateJWTString method where claims are built and add the conditional audience
assignment.
🪄 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: Organization UI

Review profile: CHILL

Plan: Enterprise

Run ID: a150046b-e9c4-44a3-97cd-a4d7d090571c

📥 Commits

Reviewing files that changed from the base of the PR and between f0ca89d and bc2e1ba.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (35)
  • CHANGELOG.md
  • Makefile
  • PREREQUISITES.md
  • cmd/hyperfleet-api/environments/e_development.go
  • cmd/hyperfleet-api/environments/e_integration_testing.go
  • cmd/hyperfleet-api/environments/e_production.go
  • cmd/hyperfleet-api/environments/e_unit_testing.go
  • cmd/hyperfleet-api/environments/framework.go
  • cmd/hyperfleet-api/environments/framework_test.go
  • cmd/hyperfleet-api/environments/types.go
  • cmd/hyperfleet-api/server/api_server.go
  • configs/config.yaml.example
  • docs/authentication.md
  • docs/config.md
  • docs/development.md
  • docs/logging.md
  • go.mod
  • pkg/auth/authz_middleware.go
  • pkg/auth/context.go
  • pkg/auth/jwt_handler.go
  • pkg/auth/jwt_handler_test.go
  • pkg/client/ocm/authorization.go
  • pkg/client/ocm/authorization_mock.go
  • pkg/client/ocm/client.go
  • pkg/config/config.go
  • pkg/config/dump.go
  • pkg/config/flags.go
  • pkg/config/helpers_test.go
  • pkg/config/loader.go
  • pkg/config/loader_test.go
  • pkg/config/ocm.go
  • pkg/config/server.go
  • pkg/logger/ocm_bridge.go
  • test/helper.go
  • test/mocks/ocm.go
💤 Files with no reviewable changes (16)
  • pkg/config/helpers_test.go
  • PREREQUISITES.md
  • configs/config.yaml.example
  • pkg/client/ocm/authorization_mock.go
  • pkg/auth/authz_middleware.go
  • pkg/logger/ocm_bridge.go
  • cmd/hyperfleet-api/environments/e_integration_testing.go
  • pkg/config/ocm.go
  • cmd/hyperfleet-api/environments/e_development.go
  • cmd/hyperfleet-api/environments/e_unit_testing.go
  • cmd/hyperfleet-api/environments/framework_test.go
  • pkg/config/config.go
  • pkg/config/loader_test.go
  • pkg/client/ocm/client.go
  • pkg/client/ocm/authorization.go
  • test/mocks/ocm.go

Comment thread CHANGELOG.md Outdated
Comment thread docs/development.md
Comment thread pkg/config/flags.go
Comment thread pkg/config/server.go
Remove the OCM client dependency and replace authentication with a
self-contained JWT handler using JWKS endpoint validation.

- Add pkg/auth/jwt_handler.go with RS256 JWT validation via JWKS
- Add pkg/auth/jwt_handler_test.go with full handler test coverage
- Remove pkg/client/ocm/ (authorization, authorization_mock, client)
- Remove pkg/config/ocm.go and OCM-specific config flags
- Remove pkg/logger/ocm_bridge.go (OCM SDK log adapter)
- Remove test/mocks/ocm.go (no longer needed)
- Update pkg/auth/authz_middleware.go to use new JWT handler
- Update pkg/auth/context.go to remove OCM identity types
- Update environments to drop OCM env var requirements
- Update go.mod/go.sum: add MicahParks/jwkset, keyfunc; remove ocm-sdk-go
- Update docs/authentication.md, docs/config.md to reflect new auth setup
- Update configs/config.yaml.example with JWT/JWKS config fields
Copy link
Copy Markdown

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/authentication.md`:
- Around line 35-52: The docs still reference JWT_ISSUER / JWT_AUDIENCE and
AUTH_ENABLED but the app loader expects HYPERFLEET_SERVER_JWT_* env vars; update
the Production Mode section and examples to use HYPERFLEET_SERVER_JWT_ENABLED,
HYPERFLEET_SERVER_JWT_ISSUER_URL, and HYPERFLEET_SERVER_JWT_AUDIENCE (and
replace any AUTH_ENABLED mentions with HYPERFLEET_SERVER_JWT_ENABLED), ensure
the example curl/launch commands and the "JWT Authentication" paragraph reflect
these exact env var names and mention RS256 verification remains in use so
operators can configure auth correctly.
🪄 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: Organization UI

Review profile: CHILL

Plan: Enterprise

Run ID: 98e77616-8752-421c-a705-3ede03ff6493

📥 Commits

Reviewing files that changed from the base of the PR and between bc2e1ba and 30e2172.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (35)
  • CHANGELOG.md
  • Makefile
  • PREREQUISITES.md
  • cmd/hyperfleet-api/environments/e_development.go
  • cmd/hyperfleet-api/environments/e_integration_testing.go
  • cmd/hyperfleet-api/environments/e_production.go
  • cmd/hyperfleet-api/environments/e_unit_testing.go
  • cmd/hyperfleet-api/environments/framework.go
  • cmd/hyperfleet-api/environments/framework_test.go
  • cmd/hyperfleet-api/environments/types.go
  • cmd/hyperfleet-api/server/api_server.go
  • configs/config.yaml.example
  • docs/authentication.md
  • docs/config.md
  • docs/development.md
  • docs/logging.md
  • go.mod
  • pkg/auth/authz_middleware.go
  • pkg/auth/context.go
  • pkg/auth/jwt_handler.go
  • pkg/auth/jwt_handler_test.go
  • pkg/client/ocm/authorization.go
  • pkg/client/ocm/authorization_mock.go
  • pkg/client/ocm/client.go
  • pkg/config/config.go
  • pkg/config/dump.go
  • pkg/config/flags.go
  • pkg/config/helpers_test.go
  • pkg/config/loader.go
  • pkg/config/loader_test.go
  • pkg/config/ocm.go
  • pkg/config/server.go
  • pkg/logger/ocm_bridge.go
  • test/helper.go
  • test/mocks/ocm.go
💤 Files with no reviewable changes (16)
  • cmd/hyperfleet-api/environments/e_unit_testing.go
  • cmd/hyperfleet-api/environments/e_integration_testing.go
  • pkg/client/ocm/authorization_mock.go
  • cmd/hyperfleet-api/environments/e_development.go
  • PREREQUISITES.md
  • cmd/hyperfleet-api/environments/framework_test.go
  • pkg/config/loader_test.go
  • pkg/logger/ocm_bridge.go
  • pkg/client/ocm/authorization.go
  • pkg/config/helpers_test.go
  • configs/config.yaml.example
  • pkg/config/ocm.go
  • pkg/client/ocm/client.go
  • test/mocks/ocm.go
  • pkg/auth/authz_middleware.go
  • pkg/config/config.go
✅ Files skipped from review due to trivial changes (2)
  • cmd/hyperfleet-api/environments/e_production.go
  • docs/logging.md
🚧 Files skipped from review as they are similar to previous changes (3)
  • Makefile
  • cmd/hyperfleet-api/environments/framework.go
  • CHANGELOG.md

Comment thread docs/authentication.md
Comment on lines +35 to +52
## Production Mode (JWT Auth)

Production deployments use JWT-based authentication integrated with OpenShift Cluster Manager (OCM).
Production deployments use JWT-based authentication with a configurable issuer.

### Usage

```bash
# Start service with authentication
make run

# Login to OCM
ocm login --token=${OCM_ACCESS_TOKEN} --url=http://localhost:8000

# Access API with authentication
ocm get /api/hyperfleet/v1/clusters
# Access API with a valid JWT
curl -H "Authorization: Bearer ${TOKEN}" \
http://localhost:8000/api/hyperfleet/v1/clusters
```

### JWT Authentication

HyperFleet API validates JWT tokens issued by Red Hat SSO.
HyperFleet API validates JWT tokens using RS256 signature verification.
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Use HYPERFLEET_SERVER_JWT_* names consistently in production auth docs.

This page still references JWT_ISSUER / JWT_AUDIENCE (and AUTH_ENABLED in the env example), but the loader binds server.jwt.* via HYPERFLEET_SERVER_JWT_ENABLED, HYPERFLEET_SERVER_JWT_ISSUER_URL, and HYPERFLEET_SERVER_JWT_AUDIENCE. As written, operators can follow this doc and still fail to configure auth correctly.

Suggested doc fix
-2. Issuer - Matches configured `JWT_ISSUER`
-3. Audience - Matches configured `JWT_AUDIENCE`
+2. Issuer - Matches configured `HYPERFLEET_SERVER_JWT_ISSUER_URL`
+3. Audience - Matches configured `HYPERFLEET_SERVER_JWT_AUDIENCE`

-# Development (no auth)
-export AUTH_ENABLED=false
+# Development (no auth)
+export HYPERFLEET_SERVER_JWT_ENABLED=false

-# Production (with auth)
-export AUTH_ENABLED=true
-export JWT_ISSUER=https://sso.redhat.com/auth/realms/redhat-external
-export JWT_AUDIENCE=https://api.openshift.com
+# Production (with auth)
+export HYPERFLEET_SERVER_JWT_ENABLED=true
+export HYPERFLEET_SERVER_JWT_ISSUER_URL=https://sso.redhat.com/auth/realms/redhat-external
+export HYPERFLEET_SERVER_JWT_AUDIENCE=https://api.openshift.com
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/authentication.md` around lines 35 - 52, The docs still reference
JWT_ISSUER / JWT_AUDIENCE and AUTH_ENABLED but the app loader expects
HYPERFLEET_SERVER_JWT_* env vars; update the Production Mode section and
examples to use HYPERFLEET_SERVER_JWT_ENABLED, HYPERFLEET_SERVER_JWT_ISSUER_URL,
and HYPERFLEET_SERVER_JWT_AUDIENCE (and replace any AUTH_ENABLED mentions with
HYPERFLEET_SERVER_JWT_ENABLED), ensure the example curl/launch commands and the
"JWT Authentication" paragraph reflect these exact env var names and mention
RS256 verification remains in use so operators can configure auth correctly.

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