Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(server/v2): add swagger server component #23486

Merged
merged 7 commits into from
Jan 24, 2025
Merged

feat(server/v2): add swagger server component #23486

merged 7 commits into from
Jan 24, 2025

Conversation

julienrbrt
Copy link
Member

@julienrbrt julienrbrt commented Jan 23, 2025

Description

Closes: #23020
Replaces #23092


Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • included the correct type prefix in the PR title, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch (see PR Targeting)
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • added a changelog entry to CHANGELOG.md
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

Please see Pull Request Reviewer section in the contributing guide for more information on how to review a pull request.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

Release Notes

  • New Features

    • Added Swagger UI server component for enhanced API documentation
    • Introduced new configuration options for server, telemetry, and store settings
  • Improvements

    • Refined server configuration management
    • Updated logging and error handling in various server components
    • Enhanced flexibility in server initialization and component configuration
  • Technical Updates

    • Restructured server initialization process
    • Updated parameter handling in server functions
    • Added support for more granular server and application configuration

Copy link
Contributor

coderabbitai bot commented Jan 23, 2025

📝 Walkthrough

Walkthrough

This pull request introduces a comprehensive enhancement to the Cosmos SDK's server/v2 component by adding default Swagger support. The changes include creating a new swagger package with configuration and server management capabilities, updating various configuration files, and modifying existing server components to integrate the Swagger UI functionality. The implementation provides a flexible and configurable approach to serving Swagger documentation across the SDK's server infrastructure.

Changes

File Change Summary
client/docs/config.json Updated API entries, removing params service and adding protocolpool service
client/docs/embed.go Added GetSwaggerFS() function for embedded Swagger UI filesystem
client/docs/swagger-ui/index.html Updated document type, meta tags, and added server URL attribute
server/v2/CHANGELOG.md Added entry for new server/v2/api/swagger component
server/v2/api/grpcgateway/handler.go Removed logger parameters from route handling functions
server/v2/api/grpcgateway/server.go Updated mountHTTPRoutes function call
server/v2/api/swagger/* Created new package with configuration, server, and handler implementations
simapp/v2/simdv2/cmd/commands.go Integrated Swagger server into command initialization
tools/confix/data/v2-app.toml Added new configuration parameters for Swagger and other components

Assessment against linked issues

Objective Addressed Explanation
Add Swagger support in server/v2
Provide out-of-the-box Swagger UI

Possibly related PRs

Suggested labels

C:Cosmovisor, backport/v0.52.x

Suggested reviewers

  • kocubinski
  • testinginprod
  • sontrinh16
  • akhilkumarpilli
  • facundomedica
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added C:Confix Issues and PR related to Confix C:server/v2 Issues related to server/v2 C:server/v2 api labels Jan 23, 2025
@github-actions github-actions bot added the C:CLI label Jan 23, 2025
@julienrbrt julienrbrt marked this pull request as ready for review January 23, 2025 22:31
@julienrbrt julienrbrt requested review from a team and JulianToledano as code owners January 23, 2025 22:31

This comment has been minimized.

Copy link
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: 3

🧹 Nitpick comments (4)
server/v2/api/swagger/handler.go (1)

8-10: Consider exporting the SwaggerHandler struct

The handler struct is unexported but needs to be instantiated by the Server. Consider exporting it if it's meant to be used by other packages.

-type swaggerHandler struct {
+type SwaggerHandler struct {
 	swaggerFS fs.FS
}
server/v2/api/swagger/config.go (1)

29-34: Fix incorrect comment for Disable function

The comment mentions GRPC server but this is for the Swagger UI server.

-// Disable the grpc server by default (default enabled).
+// Disable disables the Swagger UI server.
 func Disable() CfgOption {
server/v2/api/swagger/server.go (1)

88-100: Improve error handling and context usage in Start method

The Start method:

  1. Doesn't use the provided context for cancellation
  2. Could improve error wrapping
 func (s *Server[T]) Start(ctx context.Context) error {
 	if !s.config.Enable {
 		s.logger.Info(fmt.Sprintf("%s server is disabled via config", s.Name()))
 		return nil
 	}

+	errCh := make(chan error, 1)
 	s.logger.Info("starting swagger server...", "address", s.config.Address)
-	if err := s.server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
-		return fmt.Errorf("failed to start swagger server: %w", err)
-	}
+	go func() {
+		if err := s.server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
+			errCh <- fmt.Errorf("failed to start swagger server: %w", err)
+		}
+		close(errCh)
+	}()
+
+	select {
+	case err := <-errCh:
+		return err
+	case <-ctx.Done():
+		return s.Stop(ctx)
+	}
client/docs/swagger-ui/index.html (1)

9-10: Consider making the server URL configurable.

The server URL is hardcoded to http://localhost:1317. This might not be suitable for production environments or different deployment scenarios.

Consider making it configurable through environment variables or a configuration file:

-    <rapi-doc spec-url="swagger.yaml" server-url="http://localhost:1317">
+    <rapi-doc spec-url="swagger.yaml" server-url="${API_SERVER_URL:-http://localhost:1317}">
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8493d4f and 7a6b995.

📒 Files selected for processing (13)
  • client/docs/config.json (1 hunks)
  • client/docs/embed.go (1 hunks)
  • client/docs/swagger-ui/index.html (1 hunks)
  • server/v2/CHANGELOG.md (1 hunks)
  • server/v2/api/grpcgateway/handler.go (2 hunks)
  • server/v2/api/grpcgateway/server.go (1 hunks)
  • server/v2/api/swagger/config.go (1 hunks)
  • server/v2/api/swagger/doc.go (1 hunks)
  • server/v2/api/swagger/handler.go (1 hunks)
  • server/v2/api/swagger/server.go (1 hunks)
  • server/v2/api/telemetry/server.go (1 hunks)
  • simapp/v2/simdv2/cmd/commands.go (5 hunks)
  • tools/confix/data/v2-app.toml (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • server/v2/api/swagger/doc.go
🧰 Additional context used
📓 Path-based instructions (9)
server/v2/CHANGELOG.md (1)

Pattern **/*.md: "Assess the documentation for misspellings, grammatical errors, missing documentation and correctness"

client/docs/embed.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/api/grpcgateway/server.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/api/swagger/handler.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/api/swagger/config.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/api/telemetry/server.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/api/swagger/server.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

simapp/v2/simdv2/cmd/commands.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

server/v2/api/grpcgateway/handler.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

🪛 checkov (3.2.334)
client/docs/config.json

[HIGH] 1-180: Ensure that security requirement defined in securityDefinitions - version 2.0 files

(CKV_OPENAPI_6)


[HIGH] 1-180: Ensure that the global security field has rules defined

(CKV_OPENAPI_4)


[HIGH] 1-180: Ensure that securityDefinitions is defined and not empty - version 2.0 files

(CKV_OPENAPI_1)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze
  • GitHub Check: Summary
🔇 Additional comments (14)
server/v2/api/swagger/handler.go (1)

14-15: Review CORS configuration for security

The current CORS configuration is very permissive. Consider:

  1. Restricting allowed origins to specific domains
  2. Limiting allowed methods to only those needed
  3. Adding additional security headers (Content-Security-Policy, X-Frame-Options)
server/v2/api/telemetry/server.go (1)

32-32: LGTM! Parameter reordering improves consistency.

The reordering of parameters to place logger and enableTelemetry before cfg follows a good practice where context-like parameters precede configuration parameters.

server/v2/api/grpcgateway/server.go (1)

79-79: LGTM! Simplified function call by removing redundant logger parameter.

The removal of the logger parameter from mountHTTPRoutes is appropriate as logging is handled at the server level.

simapp/v2/simdv2/cmd/commands.go (3)

128-131: LGTM! Updated telemetry server initialization.

The parameter reordering matches the updated function signature in the telemetry package.


133-136: LGTM! Well-structured swagger server initialization.

The swagger server is properly initialized with appropriate error handling and necessary dependencies (logger, filesystem, and config).


90-90: LGTM! Proper integration of swagger server component.

The swagger server is correctly added to both the CLI skeleton and full app configurations.

Also applies to: 179-179

server/v2/api/grpcgateway/handler.go (2)

Line range hint 49-58: LGTM! Simplified HTTP route mounting.

The removal of the logger parameter streamlines the function while maintaining its core functionality and error handling.


63-63: LGTM! Consistent parameter cleanup.

The removal of the logger parameter from registerMethods aligns with the changes in mountHTTPRoutes.

client/docs/swagger-ui/index.html (1)

4-5: LGTM!

The meta tag update follows HTML5 standards and the UTF-8 comment is helpful for maintainers.

server/v2/CHANGELOG.md (1)

25-26: LGTM!

The changelog entry follows the guidelines and properly references the PR.

client/docs/config.json (2)

171-177: LGTM!

The operation ID renames for the protocolpool service follow the established pattern and maintain consistency with other services.


Line range hint 1-180: Add security definitions to the OpenAPI specification.

The OpenAPI specification is missing security definitions and requirements. This could expose your API to security risks.

Please add the following sections to ensure proper security:

{
  "swagger": "2.0",
  "info": {
    "title": "Cosmos SDK - gRPC Gateway docs",
    "description": "A REST interface for state queries.",
    "version": "1.0.0"
  },
+ "securityDefinitions": {
+   "ApiKeyAuth": {
+     "type": "apiKey",
+     "in": "header",
+     "name": "X-API-Key"
+   }
+ },
+ "security": [
+   {
+     "ApiKeyAuth": []
+   }
+ ],
  "apis": [
🧰 Tools
🪛 checkov (3.2.334)

[HIGH] 1-180: Ensure that security requirement defined in securityDefinitions - version 2.0 files

(CKV_OPENAPI_6)


[HIGH] 1-180: Ensure that the global security field has rules defined

(CKV_OPENAPI_4)


[HIGH] 1-180: Ensure that securityDefinitions is defined and not empty - version 2.0 files

(CKV_OPENAPI_1)

tools/confix/data/v2-app.toml (2)

2-176: LGTM!

The configuration parameters are well-documented with clear descriptions and sensible default values.


135-141: Review security implications of enabled Swagger UI in production.

While enabling Swagger UI by default is helpful for development, consider the security implications for production deployments.

Consider adding a warning in the configuration comments about production usage:

 [swagger]

-# Enable enables/disables the Swagger UI server
+# Enable enables/disables the Swagger UI server.
+# WARNING: It's recommended to disable this in production environments unless properly secured.
 enable = true

 # Address defines the server address to bind to
 address = 'localhost:8090'
✅ Verification successful

Add security warning for Swagger UI configuration

The suggestion to add a warning comment about production usage is appropriate. While the default localhost binding provides some security, an explicit warning helps developers make informed decisions about production deployments.

  • The current configuration binds to localhost:8090, which already limits access to local connections
  • Adding the warning comment reinforces security consciousness without affecting functionality
  • This follows security best practices of providing clear guidance for production environments
🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Search for similar configuration files and Swagger-related content
echo "=== Searching for similar configuration files ==="
fd -e toml -x cat {}

echo -e "\n=== Searching for Swagger-related documentation ==="
fd -e md -e txt README -x cat {}

echo -e "\n=== Searching for Swagger implementation ==="
rg -i "swagger" --type go -A 5 -B 5

Length of output: 67187

client/docs/embed.go Show resolved Hide resolved
Comment on lines +73 to +85
func (s *Server[T]) Config() any {
if s.config == nil || s.config.Address == "" {
cfg := DefaultConfig()
// overwrite the default config with the provided options
for _, opt := range s.cfgOptions {
opt(cfg)
}

return cfg
}

return s.config
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix potential race condition in Config method

The Config method has a potential race condition when checking and initializing the config. Consider using sync.Once or initializing config in New.

Comment on lines +59 to +62
s.server = &http.Server{
Addr: s.config.Address,
Handler: mux,
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add timeout configurations for HTTP server

The HTTP server should have reasonable timeouts configured to prevent potential DoS attacks.

 s.server = &http.Server{
 	Addr:    s.config.Address,
 	Handler: mux,
+	ReadTimeout:  15 * time.Second,
+	WriteTimeout: 15 * time.Second,
+	IdleTimeout:  60 * time.Second,
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
s.server = &http.Server{
Addr: s.config.Address,
Handler: mux,
}
s.server = &http.Server{
Addr: s.config.Address,
Handler: mux,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}

@julienrbrt julienrbrt added the backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release label Jan 23, 2025
@julienrbrt
Copy link
Member Author

Adding the backport label for the changes in confix and in client.

@julienrbrt julienrbrt added this pull request to the merge queue Jan 24, 2025
Merged via the queue into main with commit 0cc73ba Jan 24, 2025
76 of 77 checks passed
@julienrbrt julienrbrt deleted the julien/swagger branch January 24, 2025 09:33
mergify bot pushed a commit that referenced this pull request Jan 24, 2025
(cherry picked from commit 0cc73ba)

# Conflicts:
#	server/v2/CHANGELOG.md
#	server/v2/api/grpcgateway/handler.go
#	server/v2/api/grpcgateway/server.go
#	server/v2/api/telemetry/server.go
#	simapp/v2/simdv2/cmd/commands.go
julienrbrt added a commit that referenced this pull request Jan 24, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release C:CLI C:Confix Issues and PR related to Confix C:server/v2 api C:server/v2 Issues related to server/v2
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Default Swagger support in server/v2?
4 participants