fix: correct WriteHeader ordering in debug endpoints and remove dead DumpCerts#1611
fix: correct WriteHeader ordering in debug endpoints and remove dead DumpCerts#1611imshubham22apr-gif wants to merge 4 commits intokmesh-net:mainfrom
Conversation
Signed-off-by: Yash Israni <118755067+yashisrani@users.noreply.github.com>
Signed-off-by: Yash Israni <118755067+yashisrani@users.noreply.github.com>
- Move w.WriteHeader(http.StatusOK) after json.MarshalIndent in configDumpServices and configDumpPolicies so that a marshal failure correctly returns 500 instead of a silent 200 with an empty body - Remove SecretManager.DumpCerts() which was added solely for the /debug/config_dump/security endpoint; that endpoint was removed because it leaked TLS private keys, leaving DumpCerts unreachable and dropping code coverage - Add unit tests for both handlers covering the mode-guard (400) and happy-path (200 + valid JSON body) cases
|
[APPROVALNOTIFIER] This PR is NOT APPROVED This pull-request has been approved by: The full list of commands accepted by this bot can be found here. DetailsNeeds approval from an approver in each of these files:Approvers can indicate their approval by writing |
|
Welcome @imshubham22apr-gif! It looks like this is your first PR to kmesh-net/kmesh 🎉 |
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request refines the debug endpoint functionality by addressing critical feedback related to HTTP response handling, ensuring that status codes are only written after successful data processing. It also streamlines the codebase by removing obsolete security-related logic and introduces new debug endpoints for services and policies, backed by robust unit tests to enhance overall reliability and maintainability. Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. A bug once lurked, a header's plight, Now JSON marshals, all is right. Dead code removed, tests now gleam, A cleaner path, a coding dream. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request effectively addresses the feedback from a previous code review. The ordering of WriteHeader in the new debug endpoints is now correct, preventing potential race conditions. The removal of the unused DumpCerts method is a good cleanup. The addition of unit tests for the new service and policy dump endpoints is also a great improvement for ensuring stability. My main feedback is on the implementation of the new handlers, where there is an opportunity to reduce code duplication.
| // configDumpServices dumps all K8s services known to Kmesh | ||
| func (s *Server) configDumpServices(w http.ResponseWriter, r *http.Request) { | ||
| if !s.checkWorkloadMode(w) { | ||
| return | ||
| } | ||
|
|
||
| client := s.xdsClient | ||
| services := client.WorkloadController.Processor.ServiceCache.List() | ||
|
|
||
| serviceDump := make([]*Service, 0, len(services)) | ||
| for _, svc := range services { | ||
| serviceDump = append(serviceDump, ConvertService(svc)) | ||
| } | ||
|
|
||
| data, err := json.MarshalIndent(serviceDump, "", " ") | ||
| if err != nil { | ||
| log.Errorf("Failed to marshal services: %v", err) | ||
| w.WriteHeader(http.StatusInternalServerError) | ||
| return | ||
| } | ||
| w.WriteHeader(http.StatusOK) | ||
| _, _ = w.Write(data) | ||
| } | ||
|
|
||
| // configDumpPolicies dumps all security (RBAC) policies | ||
| func (s *Server) configDumpPolicies(w http.ResponseWriter, r *http.Request) { | ||
| if !s.checkWorkloadMode(w) { | ||
| return | ||
| } | ||
|
|
||
| client := s.xdsClient | ||
| policies := client.WorkloadController.Rbac.PoliciesList() | ||
|
|
||
| policyDump := make([]*AuthorizationPolicy, 0, len(policies)) | ||
| for _, policy := range policies { | ||
| policyDump = append(policyDump, ConvertAuthorizationPolicy(policy)) | ||
| } | ||
|
|
||
| data, err := json.MarshalIndent(policyDump, "", " ") | ||
| if err != nil { | ||
| log.Errorf("Failed to marshal policies: %v", err) | ||
| w.WriteHeader(http.StatusInternalServerError) | ||
| return | ||
| } | ||
| w.WriteHeader(http.StatusOK) | ||
| _, _ = w.Write(data) | ||
| } |
There was a problem hiding this comment.
The new handlers, configDumpServices and configDumpPolicies, contain very similar logic for fetching, converting, and marshalling data to JSON. To improve maintainability and reduce code duplication, you can extract this common logic into a single generic helper function. This will make the code cleaner and easier to manage in the future.
// configDumpServices dumps all K8s services known to Kmesh
func (s *Server) configDumpServices(w http.ResponseWriter, r *http.Request) {
if !s.checkWorkloadMode(w) {
return
}
services := s.xdsClient.WorkloadController.Processor.ServiceCache.List()
dumpJSON(w, services, ConvertService, "services")
}
// configDumpPolicies dumps all security (RBAC) policies
func (s *Server) configDumpPolicies(w http.ResponseWriter, r *http.Request) {
if !s.checkWorkloadMode(w) {
return
}
policies := s.xdsClient.WorkloadController.Rbac.PoliciesList()
dumpJSON(w, policies, ConvertAuthorizationPolicy, "policies")
}
// dumpJSON is a generic helper to marshal and write a slice of items as JSON.
func dumpJSON[T any, U any](w http.ResponseWriter, items []T, converter func(T) U, subject string) {
dump := make([]U, 0, len(items))
for _, item := range items {
dump = append(dump, converter(item))
}
data, err := json.MarshalIndent(dump, "", " ")
if err != nil {
log.Errorf("Failed to marshal %s: %v", subject, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write(data)
}There was a problem hiding this comment.
Pull request overview
This PR implements debug endpoints for dumping Kubernetes services and security (RBAC) policies known to Kmesh, addressing the TODO comment that was previously in the code. The changes add two new HTTP handlers that expose services and authorization policies configuration through the admin debug server.
Changes:
- Added two new debug endpoints (
/debug/config_dump/servicesand/debug/config_dump/policies) - Implemented
configDumpServiceshandler to dump all cached K8s services as JSON - Implemented
configDumpPolicieshandler to dump all cached security policies as JSON - Added comprehensive test coverage for both new handlers
- Removed the TODO comment about implementing these features
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
| pkg/status/status_server.go | Added pattern constants, registered handlers in NewServer, and implemented the two handler methods |
| pkg/status/status_server_test.go | Added comprehensive test cases for both new handlers |
| pkg/controller/security/manager.go | Minor formatting: added trailing newline |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
You can also share your feedback on Copilot code review. Take the survey.
23b4cd1 to
b1d07ff
Compare
- Extract common logic for fetching, converting, and marshalling items into a generic dumpJSON helper - Update configDumpServices and configDumpPolicies to use the new helper - Addressed code review feedback from Gemini Code Assist bot
There was a problem hiding this comment.
Pull request overview
This PR implements two new debug endpoints for the Kmesh status server to dump K8s services and security (RBAC) policies, resolving a TODO comment that was previously in the codebase.
Changes:
- Added two new HTTP debug endpoints
/debug/config_dump/servicesand/debug/config_dump/policiesto expose K8s services and authorization policies respectively - Implemented corresponding handler functions
configDumpServices()andconfigDumpPolicies()that follow existing patterns and use a new generic helper functiondumpJSON() - Removed the TODO comment that mentioned these missing features
- Added comprehensive test coverage for both new endpoints
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
| pkg/status/status_server.go | Added two new route patterns, handlers, and a generic JSON helper function to dump services and policies |
| pkg/status/status_server_test.go | Added test cases for both new endpoints covering error cases and successful responses |
| pkg/controller/security/manager.go | Trivial whitespace change (added blank line at end of file) |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
You can also share your feedback on Copilot code review. Take the survey.
What type of PR is this?
/kind bug
What this PR does / why we need it:
This PR addresses the technical feedback provided during the recent code review of the debug endpoints. The following improvements have been implemented:
Corrected HTTP Response Header Lifecycle
In the previous implementation, the 200 OK status was being dispatched before the JSON marshalling process. This created a race condition where a marshalling failure would still return a success code to the client. I have refactored the handlers to ensure that json.MarshalIndent is completed successfully before any status headers are written. In the event of a failure, the server now correctly returns a 500 Internal Server Error.
Clean-up of Unused Security Logic
Following the removal of the security debug endpoint (due to TLS key exposure risks), the DumpCerts() method in the security manager became unreachable. I have removed this dead code to maintain a clean codebase and resolve the drop in project code coverage.
Enhancement of Test Coverage
To ensure long-term stability and satisfy coverage requirements, I have added comprehensive unit tests for the services and policies debug handlers. These tests validate both the successful data retrieval path and the appropriate error handling when the controller is in an invalid mode.
Which issue(s) this PR fixes:
Fixes code review comments on PR 1604
Does this PR introduce a user-facing change?:
NONE