Skip to content

HYPERFLEET-1370 - refactor: introduce typed container for API server dependencies - #309

Open
kuudori wants to merge 1 commit into
openshift-hyperfleet:mainfrom
kuudori:HYPERFLEET-1370-refactor-typed-container
Open

HYPERFLEET-1370 - refactor: introduce typed container for API server dependencies#309
kuudori wants to merge 1 commit into
openshift-hyperfleet:mainfrom
kuudori:HYPERFLEET-1370-refactor-typed-container

Conversation

@kuudori

@kuudori kuudori commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Replace plugin-based route registration (plugins/entities, adapterStatus, generic, resources) with a typed Container (cmd/hyperfleet-api/container) that lazily constructs and caches DAOs, services, and handlers via constructor injection
  • Refactor APIServer to take injected cfg and handler via its constructor instead of reaching into the global environments.Environment() singleton
  • Split router middleware into public (/openapi, /openapi.html, metadata) vs protected (auth + schema validation + transaction) subrouters, so public docs endpoints are never wrapped by auth/transaction middleware
  • Simplify JWTHandler to a multi-issuer, mux.MiddlewareFunc-based design, dropping the old PublicPaths/Next self-contained handler
  • Add a TODO(HYPERFLEET-1371) marking the remaining environments.Environment() callers (health_server.go, metrics_server.go) for follow-up once the environments/ package is removed

Test plan

  • make verify-all (go vet, gofmt, unit tests) passes
  • TestNewRouter_PublicVsProtectedMiddleware (new) verifies public routes bypass both apiMiddleware and protectedMiddleware, while registered routes are gated by both — confirmed it fails against the pre-fix router wiring and passes against the fix
  • TestContainerCachesDAOsAndServices updated to use BeIdenticalTo for genuine pointer-identity caching checks
  • Existing integration tests (test/integration/clusters_test.go, test/integration/openapi_test.go) continue to cover the public/protected boundary end-to-end under the default JWT-enabled config

@openshift-ci
openshift-ci Bot requested review from ldornele and tirthct July 23, 2026 14:56
@openshift-ci

openshift-ci Bot commented Jul 23, 2026

Copy link
Copy Markdown

[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 vkareh 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

coderabbitai Bot commented Jul 23, 2026

Copy link
Copy Markdown
📝 Walkthrough

Summary by CodeRabbit

  • New Features

    • Added configuration-driven registration for entity and generic resource routes.
    • Added managed services, schema validation, optional JWT authentication, and configurable HTTP/TLS settings.
    • Improved graceful API server startup and shutdown.
    • Metadata and public OpenAPI endpoints bypass authentication middleware.
  • Documentation

    • Updated setup and architecture guidance for resource configuration and API startup.
  • Tests

    • Added coverage for HTTP/TLS serving, middleware behavior, dependency caching, and lazy initialization.

Walkthrough

The API now uses a sequential dependency container for DAOs, services, schema validation, and JWT handling. Startup composes middleware and entity routes through BuildAPIServer and NewRouterFromConfig. APIServer uses injected configuration and handlers. JWT validation uses middleware instead of a downstream handler. Plugin registration and environment-based service lookup were removed. Tests and documentation now use the new wiring.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant runServe
  participant Container
  participant BuildAPIServer
  participant Router
  participant APIServer
  runServe->>Container: create and initialize dependencies
  runServe->>BuildAPIServer: provide container services and configuration
  BuildAPIServer->>Router: compose middleware and register entity routes
  BuildAPIServer->>APIServer: inject Router and server configuration
  APIServer-->>runServe: start and stop API server
  runServe->>Container: close cached resources
Loading

Suggested reviewers: ldornele, tirthct


Important

Pre-merge checks failed

Please resolve all errors before merging. Addressing warnings is optional.

❌ Failed checks (1 error, 1 warning)

Check name Status Explanation Resolution
Sec-02: Secrets In Log Output ❌ Error CWE-532: request_logging_middleware.go logs all headers via slog.Any; MaskHeaders returns raw headers when masking is disabled, so Authorization tokens can reach logs. Never log raw headers. Redact Authorization and other credential headers unconditionally before slog.Any, or omit headers from request logs.
Docstring Coverage ⚠️ Warning Docstring coverage is 12.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (9 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: introducing a typed container for API server dependencies.
Description check ✅ Passed The description directly covers the container refactor, dependency injection, middleware changes, JWT changes, and test plan.
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.
No Hardcoded Secrets ✅ Passed No hardcoded secrets, credential URLs, or private-key markers were added; generated TLS keys and Basic/HMAC values are test fixtures. No changed config contains secret data (CWE-798).
No Weak Cryptography ✅ Passed No banned MD5, DES, RC4, SHA-1, ECB, custom cipher, or secret comparison was found; JWT validation uses library RS256 allowlisting, and crypto use is TLS/RSA test setup.
No Injection Vectors ✅ Passed No changed production file adds CWE-89 query construction, CWE-78 command execution, CWE-79 template.HTML, or CWE-502 YAML unmarshalling; added fmt.Sprintf calls format logs or startup errors only.
No Privileged Containers ✅ Passed No prohibited privilege settings appear in the PR patch or production Helm templates; Dockerfile USER root is limited to make installation and explicitly switches to non-root.
No Pii Or Sensitive Data In Logs ✅ Passed No CWE-532 finding: added logs contain startup errors, schema paths, and bind addresses; request-header logging and masking are unchanged, with no added PII, bodies, or session IDs.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
✨ Simplify code
  • Create PR with simplified code

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

@hyperfleet-ci-bot

hyperfleet-ci-bot Bot commented Jul 23, 2026

Copy link
Copy Markdown

Risk Score: 5 — risk/high

Signal Detail Points
PR size 1798 lines (>500) +2
Sensitive paths cmd/ +2
Test coverage Missing tests for: cmd/hyperfleet-api cmd/hyperfleet-api/servecmd pkg/config pkg/handlers plugins/adapterStatus plugins/entities plugins/generic plugins/resources test test/factories test/integration +1

Computed by hyperfleet-risk-scorer

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

🧹 Nitpick comments (2)
cmd/hyperfleet-api/server/api_server_test.go (1)

111-115: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

InsecureSkipVerify disables cert-chain/hostname validation (CWE-295).

Flagged by both OpenGrep and ast-grep. You already generate the self-signed cert in writeSelfSignedCert — build an x509.CertPool from it and set RootCAs instead of skipping verification entirely, and add MinVersion: tls.VersionTLS13.

🔒 Proposed fix
+	certPool := x509.NewCertPool()
+	certPEM, err := os.ReadFile(certFile)
+	Expect(err).NotTo(HaveOccurred())
+	Expect(certPool.AppendCertsFromPEM(certPEM)).To(BeTrue())
+
 	client := &http.Client{
 		Transport: &http.Transport{
-			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
+			TLSClientConfig: &tls.Config{RootCAs: certPool, MinVersion: tls.VersionTLS13},
 		},
 	}
🤖 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 `@cmd/hyperfleet-api/server/api_server_test.go` around lines 111 - 115, Update
the HTTP client TLS configuration in the test to avoid InsecureSkipVerify: build
an x509.CertPool from the certificate generated by writeSelfSignedCert, assign
it to RootCAs, and set MinVersion to tls.VersionTLS13 while preserving trusted
self-signed certificate validation.

Source: Linters/SAST tools

pkg/auth/jwt_handler.go (1)

106-155: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Middleware is near the QUAL-03 branching/length threshold.

5+ distinct branch points (empty header, non-Bearer scheme, parse failure w/ expired precedence, terminal expired/invalid, no-credentials) in one closure. Extract the per-validator match loop into a helper (e.g. matchValidator(r *http.Request) (*jwt.Token, config.JWTIssuerConfig, error, bool)) returning either a matched token or the sticky "expired" error, keeping Middleware itself as thin dispatch + handleError calls.

As per path instructions, "Functions >50 lines or >5 branching paths — flag for decomposition."

🤖 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 `@pkg/auth/jwt_handler.go` around lines 106 - 155, Decompose the validator
iteration from JWTHandler.Middleware into a helper such as matchValidator that
evaluates headers and parsers, returns the matched token and issuer
configuration, or the sticky expired/validation error plus whether a non-Bearer
header was seen. Keep Middleware focused on invoking the helper, dispatching
successful requests, and preserving the existing handleError behavior and error
precedence.

Source: Path instructions

🤖 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 `@cmd/hyperfleet-api/server/routes.go`:
- Around line 48-54: Make authentication outermost on protected routes: in
cmd/hyperfleet-api/server/routes.go:48-54, register protectedMiddleware before
apiMiddleware so JWT and caller identity run before schema validation or
db.TransactionMiddleware. In cmd/hyperfleet-api/container/container.go:163-180,
adjust the middleware grouping consistently so transaction/schema middleware is
excluded from unauthenticated paths while authenticated requests still reach
db.TransactionMiddleware.

In `@test/integration/resource_helpers.go`:
- Line 15: Update the integration setup around test.RegisterIntegration(t) to
preserve and check its returned error before dereferencing h.Container. Fail the
test immediately with the original error when registration fails, then continue
to ResourceService only for a successful registration; ensure all error returns
in this setup are checked.

---

Nitpick comments:
In `@cmd/hyperfleet-api/server/api_server_test.go`:
- Around line 111-115: Update the HTTP client TLS configuration in the test to
avoid InsecureSkipVerify: build an x509.CertPool from the certificate generated
by writeSelfSignedCert, assign it to RootCAs, and set MinVersion to
tls.VersionTLS13 while preserving trusted self-signed certificate validation.

In `@pkg/auth/jwt_handler.go`:
- Around line 106-155: Decompose the validator iteration from
JWTHandler.Middleware into a helper such as matchValidator that evaluates
headers and parsers, returns the matched token and issuer configuration, or the
sticky expired/validation error plus whether a non-Bearer header was seen. Keep
Middleware focused on invoking the helper, dispatching successful requests, and
preserving the existing handleError behavior and error precedence.
🪄 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: Central YAML (base), Organization UI (inherited)

Review profile: CHILL

Plan: Enterprise

Run ID: 63920e6b-ce80-41f8-aa45-a382cb43ee94

📥 Commits

Reviewing files that changed from the base of the PR and between 913cd01 and 24bb5ee.

📒 Files selected for processing (24)
  • cmd/hyperfleet-api/container/container.go
  • cmd/hyperfleet-api/container/container_test.go
  • cmd/hyperfleet-api/main.go
  • cmd/hyperfleet-api/servecmd/cmd.go
  • cmd/hyperfleet-api/server/api_server.go
  • cmd/hyperfleet-api/server/api_server_test.go
  • cmd/hyperfleet-api/server/routes.go
  • cmd/hyperfleet-api/server/routes_entities.go
  • cmd/hyperfleet-api/server/routes_entities_test.go
  • cmd/hyperfleet-api/server/routes_test.go
  • cmd/hyperfleet-api/server/server.go
  • pkg/auth/jwt_handler.go
  • pkg/auth/jwt_handler_test.go
  • pkg/config/server.go
  • pkg/handlers/resource_handler.go
  • plugins/CLAUDE.md
  • plugins/adapterStatus/plugin.go
  • plugins/generic/plugin.go
  • plugins/resources/plugin.go
  • test/factories/clusters.go
  • test/factories/factory.go
  • test/factories/node_pools.go
  • test/helper.go
  • test/integration/resource_helpers.go
🔗 Linked repositories identified

CodeRabbit considers these linked repositories for cross-repo context during reviews:

  • openshift-hyperfleet/architecture (manual)
  • openshift-hyperfleet/hyperfleet-api (manual)
  • openshift-hyperfleet/hyperfleet-sentinel (manual)
  • openshift-hyperfleet/hyperfleet-adapter (manual)
  • openshift-hyperfleet/hyperfleet-broker (manual)
💤 Files with no reviewable changes (5)
  • plugins/CLAUDE.md
  • plugins/resources/plugin.go
  • plugins/generic/plugin.go
  • plugins/adapterStatus/plugin.go
  • cmd/hyperfleet-api/main.go

Comment thread cmd/hyperfleet-api/server/routes.go Outdated
Comment thread test/integration/resource_helpers.go
@kuudori
kuudori force-pushed the HYPERFLEET-1370-refactor-typed-container branch from 24bb5ee to b06edbb Compare July 23, 2026 16:04
@Ruclo

Ruclo commented Jul 24, 2026

Copy link
Copy Markdown

@kuudori The container abstraction is nice but wouldn't it make more sense to have it store only the dependencies ? so without APIServer, JWTHandler and SchemaValidator ? The APIServer could be created somewhere in cmd/hyperfleet-api/server/. What do you think?

@kuudori
kuudori force-pushed the HYPERFLEET-1370-refactor-typed-container branch 3 times, most recently from 6731593 to 7a66fdb Compare July 28, 2026 19:37

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

🤖 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 `@CLAUDE.md`:
- Around line 125-126: Update the “Public routes” startup wiring documentation
to state explicitly that protected routes require authentication and schema
validation, while transaction middleware applies only to POST, PUT, PATCH, and
DELETE requests; preserve the public-route bypass behavior.
🪄 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: Central YAML (base), Organization UI (inherited)

Review profile: CHILL

Plan: Enterprise

Run ID: 15497cbf-a357-48a9-b0e0-a629554ac3dd

📥 Commits

Reviewing files that changed from the base of the PR and between 6731593 and 7a66fdb.

📒 Files selected for processing (33)
  • AGENTS.md
  • CLAUDE.md
  • CONTRIBUTING.md
  • README.md
  • cmd/hyperfleet-api/container/auth.go
  • cmd/hyperfleet-api/container/container.go
  • cmd/hyperfleet-api/container/container_test.go
  • cmd/hyperfleet-api/container/daos.go
  • cmd/hyperfleet-api/container/services.go
  • cmd/hyperfleet-api/container/validation.go
  • cmd/hyperfleet-api/main.go
  • cmd/hyperfleet-api/servecmd/api_server.go
  • cmd/hyperfleet-api/servecmd/cmd.go
  • cmd/hyperfleet-api/server/api_server.go
  • cmd/hyperfleet-api/server/api_server_test.go
  • cmd/hyperfleet-api/server/routes.go
  • cmd/hyperfleet-api/server/routes_entities.go
  • cmd/hyperfleet-api/server/routes_entities_test.go
  • cmd/hyperfleet-api/server/routes_test.go
  • cmd/hyperfleet-api/server/server.go
  • pkg/auth/jwt_handler.go
  • pkg/auth/jwt_handler_test.go
  • pkg/config/server.go
  • pkg/handlers/resource_handler.go
  • plugins/CLAUDE.md
  • plugins/adapterStatus/plugin.go
  • plugins/generic/plugin.go
  • plugins/resources/plugin.go
  • test/factories/clusters.go
  • test/factories/factory.go
  • test/factories/node_pools.go
  • test/helper.go
  • test/integration/resource_helpers.go
🔗 Linked repositories identified

CodeRabbit considers these linked repositories for cross-repo context during reviews:

  • openshift-hyperfleet/architecture (manual)
  • openshift-hyperfleet/hyperfleet-api (manual)
  • openshift-hyperfleet/hyperfleet-sentinel (manual)
  • openshift-hyperfleet/hyperfleet-adapter (manual)
  • openshift-hyperfleet/hyperfleet-broker (manual)
💤 Files with no reviewable changes (5)
  • cmd/hyperfleet-api/main.go
  • plugins/CLAUDE.md
  • plugins/resources/plugin.go
  • plugins/generic/plugin.go
  • plugins/adapterStatus/plugin.go
🚧 Files skipped from review as they are similar to previous changes (26)
  • pkg/handlers/resource_handler.go
  • README.md
  • cmd/hyperfleet-api/container/auth.go
  • cmd/hyperfleet-api/server/server.go
  • cmd/hyperfleet-api/container/services.go
  • test/factories/node_pools.go
  • cmd/hyperfleet-api/server/routes_entities_test.go
  • test/factories/factory.go
  • pkg/config/server.go
  • cmd/hyperfleet-api/container/validation.go
  • cmd/hyperfleet-api/container/daos.go
  • cmd/hyperfleet-api/container/container_test.go
  • AGENTS.md
  • cmd/hyperfleet-api/servecmd/cmd.go
  • cmd/hyperfleet-api/servecmd/api_server.go
  • cmd/hyperfleet-api/server/api_server_test.go
  • test/factories/clusters.go
  • CONTRIBUTING.md
  • test/integration/resource_helpers.go
  • cmd/hyperfleet-api/container/container.go
  • cmd/hyperfleet-api/server/routes_test.go
  • test/helper.go
  • cmd/hyperfleet-api/server/api_server.go
  • cmd/hyperfleet-api/server/routes.go
  • pkg/auth/jwt_handler.go
  • pkg/auth/jwt_handler_test.go

Comment thread CLAUDE.md Outdated
@kuudori
kuudori force-pushed the HYPERFLEET-1370-refactor-typed-container branch from 7a66fdb to 70e7784 Compare July 29, 2026 14:59

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

🤖 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 `@cmd/hyperfleet-api/servecmd/cmd.go`:
- Around line 153-156: Update ctr.JWTHandler to return (*auth.JWTHandler, error)
and propagate auth.NewJWTHandler failures instead of panicking. In the
JWT-enabled startup branch around jwtHandler, handle the returned error through
the command’s structured startup-error path by logging it and exiting before
continuing. Preserve the disabled-auth behavior and existing JWKS initialization
flow.
🪄 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: Central YAML (base), Organization UI (inherited)

Review profile: CHILL

Plan: Enterprise

Run ID: aa5899ec-cba9-444c-a03b-63d684fdda9d

📥 Commits

Reviewing files that changed from the base of the PR and between 6731593 and 70e7784.

📒 Files selected for processing (33)
  • AGENTS.md
  • CLAUDE.md
  • CONTRIBUTING.md
  • README.md
  • cmd/hyperfleet-api/container/auth.go
  • cmd/hyperfleet-api/container/container.go
  • cmd/hyperfleet-api/container/container_test.go
  • cmd/hyperfleet-api/container/daos.go
  • cmd/hyperfleet-api/container/services.go
  • cmd/hyperfleet-api/container/validation.go
  • cmd/hyperfleet-api/main.go
  • cmd/hyperfleet-api/servecmd/api_server.go
  • cmd/hyperfleet-api/servecmd/cmd.go
  • cmd/hyperfleet-api/server/api_server.go
  • cmd/hyperfleet-api/server/api_server_test.go
  • cmd/hyperfleet-api/server/routes.go
  • cmd/hyperfleet-api/server/routes_entities.go
  • cmd/hyperfleet-api/server/routes_entities_test.go
  • cmd/hyperfleet-api/server/routes_test.go
  • cmd/hyperfleet-api/server/server.go
  • pkg/auth/jwt_handler.go
  • pkg/auth/jwt_handler_test.go
  • pkg/config/server.go
  • pkg/handlers/resource_handler.go
  • plugins/CLAUDE.md
  • plugins/adapterStatus/plugin.go
  • plugins/generic/plugin.go
  • plugins/resources/plugin.go
  • test/factories/clusters.go
  • test/factories/factory.go
  • test/factories/node_pools.go
  • test/helper.go
  • test/integration/resource_helpers.go
🔗 Linked repositories identified

CodeRabbit considers these linked repositories for cross-repo context during reviews:

  • openshift-hyperfleet/architecture (manual)
  • openshift-hyperfleet/hyperfleet-api (manual)
  • openshift-hyperfleet/hyperfleet-sentinel (manual)
  • openshift-hyperfleet/hyperfleet-adapter (manual)
  • openshift-hyperfleet/hyperfleet-broker (manual)
💤 Files with no reviewable changes (5)
  • plugins/resources/plugin.go
  • plugins/adapterStatus/plugin.go
  • plugins/generic/plugin.go
  • plugins/CLAUDE.md
  • cmd/hyperfleet-api/main.go
🚧 Files skipped from review as they are similar to previous changes (26)
  • cmd/hyperfleet-api/container/auth.go
  • cmd/hyperfleet-api/servecmd/api_server.go
  • cmd/hyperfleet-api/container/validation.go
  • test/factories/factory.go
  • cmd/hyperfleet-api/server/server.go
  • test/factories/node_pools.go
  • cmd/hyperfleet-api/container/container.go
  • cmd/hyperfleet-api/container/container_test.go
  • cmd/hyperfleet-api/container/services.go
  • cmd/hyperfleet-api/server/api_server_test.go
  • cmd/hyperfleet-api/server/routes_entities_test.go
  • cmd/hyperfleet-api/server/routes_test.go
  • README.md
  • cmd/hyperfleet-api/container/daos.go
  • pkg/config/server.go
  • CONTRIBUTING.md
  • test/integration/resource_helpers.go
  • cmd/hyperfleet-api/server/api_server.go
  • cmd/hyperfleet-api/server/routes.go
  • test/factories/clusters.go
  • pkg/auth/jwt_handler.go
  • cmd/hyperfleet-api/server/routes_entities.go
  • CLAUDE.md
  • AGENTS.md
  • test/helper.go
  • pkg/auth/jwt_handler_test.go

Comment thread cmd/hyperfleet-api/servecmd/cmd.go Outdated

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

Caution

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

⚠️ Outside diff range comments (2)
pkg/handlers/resource_handler.go (1)

112-115: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Replace the stale services.NewListArguments call. pkg/services/types.go only exposes NewListArguments() with no args and one return value, so services.NewListArguments(r.URL.Query()) does not compile. Use parseListParams(r.URL.Query()) from pkg/handlers/list_params.go, or restore the old parser API.

🤖 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 `@pkg/handlers/resource_handler.go` around lines 112 - 115, Update the
list-argument initialization in the handler to use the existing parseListParams
function with r.URL.Query(), preserving its returned error handling; remove the
incompatible services.NewListArguments call.
cmd/hyperfleet-api/server/routes_entities.go (1)

78-94: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use mux.Vars for these route params.

These /resources/{id} and /resources/{id}/statuses routes are mounted on gorilla/mux, so r.PathValue("id") stays empty here. Switch the handlers to mux.Vars(r)["id"] (and parent_id where applicable), or every read/mutate request on these routes will fail.

🤖 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 `@cmd/hyperfleet-api/server/routes_entities.go` around lines 78 - 94, The root
resource handlers must read route parameters through gorilla/mux rather than
net/http Request.PathValue. Update the handlers registered by
registerRootResourceRoutes, including the /resources/{id} and
/resources/{id}/statuses paths, to use mux.Vars(request)["id"] and use
mux.Vars(request)["parent_id"] wherever applicable, preserving the existing read
and mutation behavior.
🤖 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.

Outside diff comments:
In `@cmd/hyperfleet-api/server/routes_entities.go`:
- Around line 78-94: The root resource handlers must read route parameters
through gorilla/mux rather than net/http Request.PathValue. Update the handlers
registered by registerRootResourceRoutes, including the /resources/{id} and
/resources/{id}/statuses paths, to use mux.Vars(request)["id"] and use
mux.Vars(request)["parent_id"] wherever applicable, preserving the existing read
and mutation behavior.

In `@pkg/handlers/resource_handler.go`:
- Around line 112-115: Update the list-argument initialization in the handler to
use the existing parseListParams function with r.URL.Query(), preserving its
returned error handling; remove the incompatible services.NewListArguments call.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Central YAML (base), Organization UI (inherited)

Review profile: CHILL

Plan: Enterprise

Run ID: aa5899ec-cba9-444c-a03b-63d684fdda9d

📥 Commits

Reviewing files that changed from the base of the PR and between 6731593 and 70e7784.

📒 Files selected for processing (33)
  • AGENTS.md
  • CLAUDE.md
  • CONTRIBUTING.md
  • README.md
  • cmd/hyperfleet-api/container/auth.go
  • cmd/hyperfleet-api/container/container.go
  • cmd/hyperfleet-api/container/container_test.go
  • cmd/hyperfleet-api/container/daos.go
  • cmd/hyperfleet-api/container/services.go
  • cmd/hyperfleet-api/container/validation.go
  • cmd/hyperfleet-api/main.go
  • cmd/hyperfleet-api/servecmd/api_server.go
  • cmd/hyperfleet-api/servecmd/cmd.go
  • cmd/hyperfleet-api/server/api_server.go
  • cmd/hyperfleet-api/server/api_server_test.go
  • cmd/hyperfleet-api/server/routes.go
  • cmd/hyperfleet-api/server/routes_entities.go
  • cmd/hyperfleet-api/server/routes_entities_test.go
  • cmd/hyperfleet-api/server/routes_test.go
  • cmd/hyperfleet-api/server/server.go
  • pkg/auth/jwt_handler.go
  • pkg/auth/jwt_handler_test.go
  • pkg/config/server.go
  • pkg/handlers/resource_handler.go
  • plugins/CLAUDE.md
  • plugins/adapterStatus/plugin.go
  • plugins/generic/plugin.go
  • plugins/resources/plugin.go
  • test/factories/clusters.go
  • test/factories/factory.go
  • test/factories/node_pools.go
  • test/helper.go
  • test/integration/resource_helpers.go
🔗 Linked repositories identified

CodeRabbit considers these linked repositories for cross-repo context during reviews:

  • openshift-hyperfleet/architecture (manual)
  • openshift-hyperfleet/hyperfleet-api (manual)
  • openshift-hyperfleet/hyperfleet-sentinel (manual)
  • openshift-hyperfleet/hyperfleet-adapter (manual)
  • openshift-hyperfleet/hyperfleet-broker (manual)
💤 Files with no reviewable changes (5)
  • plugins/CLAUDE.md
  • plugins/generic/plugin.go
  • plugins/resources/plugin.go
  • plugins/adapterStatus/plugin.go
  • cmd/hyperfleet-api/main.go
🚧 Files skipped from review as they are similar to previous changes (24)
  • cmd/hyperfleet-api/container/validation.go
  • cmd/hyperfleet-api/server/routes_entities_test.go
  • cmd/hyperfleet-api/container/auth.go
  • cmd/hyperfleet-api/servecmd/api_server.go
  • cmd/hyperfleet-api/server/server.go
  • cmd/hyperfleet-api/container/container_test.go
  • cmd/hyperfleet-api/container/container.go
  • cmd/hyperfleet-api/container/services.go
  • pkg/config/server.go
  • CONTRIBUTING.md
  • cmd/hyperfleet-api/server/api_server_test.go
  • test/integration/resource_helpers.go
  • test/factories/clusters.go
  • README.md
  • cmd/hyperfleet-api/server/routes.go
  • cmd/hyperfleet-api/server/routes_test.go
  • cmd/hyperfleet-api/container/daos.go
  • pkg/auth/jwt_handler.go
  • cmd/hyperfleet-api/servecmd/cmd.go
  • CLAUDE.md
  • AGENTS.md
  • cmd/hyperfleet-api/server/api_server.go
  • test/helper.go
  • pkg/auth/jwt_handler_test.go

@kuudori
kuudori force-pushed the HYPERFLEET-1370-refactor-typed-container branch 3 times, most recently from f412da4 to 5725fc3 Compare August 3, 2026 19:01
@kuudori
kuudori force-pushed the HYPERFLEET-1370-refactor-typed-container branch from 5725fc3 to 4fd579e Compare August 3, 2026 19:55

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

🧹 Nitpick comments (1)
cmd/hyperfleet-api/server/routes_entities.go (1)

58-63: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the "resources" literal into a shared constant.

"resources" is hardcoded twice: the reserved-plural guard at Line 58 and the root resource prefix at Line 82. If one changes without the other, the guard silently stops protecting the actual root endpoint (CWE-693, protection mechanism failure through inconsistent enforcement).

As per path instructions, **/*.go: "Magic numbers/strings SHOULD be named constants."

♻️ Proposed fix
+const rootResourcePlural = "resources"
+
 func registerPerEntityRoutes(
 	router *Router,
 	resourceService services.ResourceService,
 	adapterStatusService services.AdapterStatusService,
 ) {
 	descriptors := registry.All()
 	sort.Slice(descriptors, func(i, j int) bool {
 		return descriptors[i].Kind < descriptors[j].Kind
 	})

 	for _, descriptor := range descriptors {
-		if descriptor.Plural == "resources" {
+		if descriptor.Plural == rootResourcePlural {
 			panic(fmt.Sprintf(
 				"entity kind %q uses reserved plural %q which would shadow /resources root endpoint",
 				descriptor.Kind, descriptor.Plural,
 			))
 		}
 	rootHandler := handlers.NewRootResourceHandler(resourceService, adapterStatusService, schemaValidator)
-	prefix := "/resources"
+	prefix := "/" + rootResourcePlural

Also applies to: 75-91

🤖 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 `@cmd/hyperfleet-api/server/routes_entities.go` around lines 58 - 63, Introduce
a shared constant for the reserved resource plural/prefix and replace both
hardcoded "resources" usages in the plural guard and root resource route
construction. Update the guard around descriptor.Plural and the route setup
around the root resource prefix to reference the same constant.
🤖 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 `@test/helper.go`:
- Around line 206-207: Update NewHelper and the startup-failure paths around
env.Initialize(), JWK mock startup, JWT setup, validator creation, and
API-server construction so they return errors to the caller or invoke the
idempotent Helper.Teardown cleanup before failing. Remove os.Exit calls after
resources have been initialized, and ensure every early-return path cleans up
all allocated test resources.

---

Nitpick comments:
In `@cmd/hyperfleet-api/server/routes_entities.go`:
- Around line 58-63: Introduce a shared constant for the reserved resource
plural/prefix and replace both hardcoded "resources" usages in the plural guard
and root resource route construction. Update the guard around descriptor.Plural
and the route setup around the root resource prefix to reference the same
constant.
🪄 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: Central YAML (base), Organization UI (inherited)

Review profile: CHILL

Plan: Enterprise

Run ID: 7f70a4e9-e91c-472b-873c-296976b6b35a

📥 Commits

Reviewing files that changed from the base of the PR and between 5725fc3 and 4fd579e.

📒 Files selected for processing (36)
  • AGENTS.md
  • CLAUDE.md
  • CONTRIBUTING.md
  • README.md
  • cmd/hyperfleet-api/container/auth.go
  • cmd/hyperfleet-api/container/container.go
  • cmd/hyperfleet-api/container/container_test.go
  • cmd/hyperfleet-api/container/daos.go
  • cmd/hyperfleet-api/container/services.go
  • cmd/hyperfleet-api/container/validation.go
  • cmd/hyperfleet-api/main.go
  • cmd/hyperfleet-api/servecmd/api_server.go
  • cmd/hyperfleet-api/servecmd/cmd.go
  • cmd/hyperfleet-api/server/api_server.go
  • cmd/hyperfleet-api/server/api_server_test.go
  • cmd/hyperfleet-api/server/compress.go
  • cmd/hyperfleet-api/server/router.go
  • cmd/hyperfleet-api/server/routes.go
  • cmd/hyperfleet-api/server/routes_entities.go
  • cmd/hyperfleet-api/server/routes_entities_test.go
  • cmd/hyperfleet-api/server/routes_test.go
  • cmd/hyperfleet-api/server/server.go
  • pkg/auth/jwt_handler.go
  • pkg/auth/jwt_handler_test.go
  • pkg/config/server.go
  • pkg/handlers/resource_handler.go
  • plugins/CLAUDE.md
  • plugins/adapterStatus/plugin.go
  • plugins/entities/plugin.go
  • plugins/generic/plugin.go
  • plugins/resources/plugin.go
  • test/factories/clusters.go
  • test/factories/factory.go
  • test/factories/node_pools.go
  • test/helper.go
  • test/integration/resource_helpers.go
🔗 Linked repositories identified

CodeRabbit considers these linked repositories for cross-repo context during reviews:

  • openshift-hyperfleet/architecture (manual)
  • openshift-hyperfleet/hyperfleet-api (manual)
  • openshift-hyperfleet/hyperfleet-sentinel (manual)
  • openshift-hyperfleet/hyperfleet-adapter (manual)
  • openshift-hyperfleet/hyperfleet-broker (manual)
💤 Files with no reviewable changes (6)
  • cmd/hyperfleet-api/main.go
  • plugins/resources/plugin.go
  • plugins/entities/plugin.go
  • plugins/CLAUDE.md
  • plugins/generic/plugin.go
  • plugins/adapterStatus/plugin.go
🚧 Files skipped from review as they are similar to previous changes (23)
  • README.md
  • cmd/hyperfleet-api/server/server.go
  • pkg/handlers/resource_handler.go
  • test/factories/node_pools.go
  • cmd/hyperfleet-api/container/auth.go
  • test/integration/resource_helpers.go
  • cmd/hyperfleet-api/container/validation.go
  • test/factories/clusters.go
  • cmd/hyperfleet-api/container/container.go
  • CONTRIBUTING.md
  • cmd/hyperfleet-api/server/compress.go
  • pkg/config/server.go
  • cmd/hyperfleet-api/server/api_server_test.go
  • cmd/hyperfleet-api/container/container_test.go
  • cmd/hyperfleet-api/container/services.go
  • pkg/auth/jwt_handler.go
  • cmd/hyperfleet-api/server/routes_entities_test.go
  • AGENTS.md
  • test/factories/factory.go
  • cmd/hyperfleet-api/container/daos.go
  • cmd/hyperfleet-api/server/api_server.go
  • pkg/auth/jwt_handler_test.go
  • CLAUDE.md

Comment thread test/helper.go
Comment on lines +206 to +207
logger.Error(context.Background(), "JWT enabled but no issuer configs defined")
os.Exit(1)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Clean up test resources before reporting startup failure.

These os.Exit(1) calls run after env.Initialize() and after the JWK mock starts. They bypass Helper.Teardown(). A JWT, validator, or API-server build failure can leave the test container running and block the Prow pod. This is CWE-772.

Return the startup error to NewHelper, or invoke an idempotent cleanup path before failing the test. Do not call os.Exit after test resources exist.

As per path instructions, “MUST clean up on ALL paths including early returns.”

Also applies to: 228-253

🤖 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 `@test/helper.go` around lines 206 - 207, Update NewHelper and the
startup-failure paths around env.Initialize(), JWK mock startup, JWT setup,
validator creation, and API-server construction so they return errors to the
caller or invoke the idempotent Helper.Teardown cleanup before failing. Remove
os.Exit calls after resources have been initialized, and ensure every
early-return path cleans up all allocated test resources.

Source: Path instructions

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