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 UI support for server/v2 #23092

Closed
wants to merge 32 commits into from
Closed
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
4ed5650
Create handler.go
crStiv Dec 25, 2024
2ac2555
feat(server): add swagger UI configuration
crStiv Dec 25, 2024
8930230
feat(server): integrate swagger UI setup
crStiv Dec 25, 2024
c812722
Create server.go
crStiv Dec 26, 2024
d0c20bc
Update config.go
crStiv Dec 26, 2024
ac5982a
Update config.go
crStiv Dec 26, 2024
f96dafe
Update handler.go
crStiv Dec 26, 2024
9859c38
Update server.go
crStiv Dec 26, 2024
e96e5bb
return original code
crStiv Dec 26, 2024
e733362
Update handler.go
crStiv Jan 6, 2025
34eab36
Update server.go
crStiv Jan 6, 2025
eec89d7
Update config.go
crStiv Jan 6, 2025
654cc99
Update app.go
crStiv Jan 6, 2025
c9d6544
Create doc.go
crStiv Jan 6, 2025
16556c1
Update commands.go
crStiv Jan 6, 2025
2021911
Update app.go
crStiv Jan 6, 2025
93dc4b6
Update handler.go
crStiv Jan 6, 2025
446c0f8
Update handler.go
crStiv Jan 7, 2025
c038d6c
Update doc.go
crStiv Jan 7, 2025
0938d61
Update config.go
crStiv Jan 7, 2025
2466ab5
Update handler.go
crStiv Jan 7, 2025
8a042b2
Update commands.go
crStiv Jan 7, 2025
8ccb884
Update doc.go
crStiv Jan 7, 2025
9659ba7
Update server.go
crStiv Jan 7, 2025
8f3017c
Merge branch 'main' into feat/add-swagger-ui
crStiv Jan 7, 2025
0fa0b6b
Update server.go
crStiv Jan 8, 2025
35f2fad
Update handler.go
crStiv Jan 8, 2025
44da58f
Update server.go
crStiv Jan 8, 2025
98f2d85
Update server.go
crStiv Jan 11, 2025
a3dbbe8
Merge branch 'main' into feat/add-swagger-ui
crStiv Jan 11, 2025
d88e065
Update server.go
crStiv Jan 19, 2025
54fe590
Update doc.go
crStiv Jan 19, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions server/v2/api/swagger/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package swagger

import (
"fmt"
"net/http"

"cosmossdk.io/core/server"
)

const ServerName = "swagger"

// Config defines the configuration for the Swagger UI server
type Config struct {
Enable bool `toml:"enable" mapstructure:"enable"`
Copy link
Member

Choose a reason for hiding this comment

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

Let's add toml comment annotation

Address string `toml:"address" mapstructure:"address"`
Path string `toml:"path" mapstructure:"path"`
SwaggerUI http.FileSystem `toml:"-" mapstructure:"-"`
}

// DefaultConfig returns the default configuration
func DefaultConfig() *Config {
return &Config{
Enable: true,
Address: "localhost:8080",
Copy link
Member

Choose a reason for hiding this comment

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

Let's use something else than 8080 by default

Path: "/swagger/",
Copy link
Member

Choose a reason for hiding this comment

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

Why do we need a path? I think keeping /swagger by default is great.

}
}

// Validate checks the configuration
func (c Config) Validate() error {
if c.Path == "" {
return fmt.Errorf("swagger path cannot be empty")
}
if c.Enable && c.SwaggerUI == nil {
return fmt.Errorf("swagger UI file system must be provided when enabled")
}
return nil
}

// CfgOption defines a function for configuring the settings
type CfgOption func(*Config)
47 changes: 47 additions & 0 deletions server/v2/api/swagger/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
Package swagger provides Swagger UI support for server/v2.

Example usage:

import (
"cosmossdk.io/client/docs"
"cosmossdk.io/core/server"
"cosmossdk.io/log"
swaggerv2 "cosmossdk.io/server/v2/api/swagger"
)

// Create a logger
logger := log.NewLogger()

// Configure Swagger server
swaggerCfg := server.ConfigMap{
"swagger": map[string]any{
"enable": true,
"address": "localhost:8080",
"path": "/swagger/",
},
}

// Create new Swagger server with the default SDK Swagger UI
swaggerServer, err := swaggerv2.New[YourTxType](
logger.With(log.ModuleKey, "swagger"),
Copy link
Member

Choose a reason for hiding this comment

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

Ditto

swaggerCfg,
swaggerv2.CfgOption(func(cfg *swaggerv2.Config) {
cfg.SwaggerUI = docs.SwaggerUI // Use the default SDK Swagger UI
}),
)
if err != nil {
// Handle error
}

// Add Swagger server to your application
app.AddServer(swaggerServer)

The server will serve Swagger UI documentation at the configured path (default: /swagger/).
Users can customize the configuration through the following options:
- enable: Enable/disable the Swagger server
- address: The address to listen on (default: localhost:8080)
- path: The path to serve Swagger UI at (default: /swagger/)
- SwaggerUI: The http.FileSystem containing Swagger UI files
*/
package swagger
72 changes: 72 additions & 0 deletions server/v2/api/swagger/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package swagger

import (
"io"
"net/http"
"path/filepath"
"strings"
"time"
)

type swaggerHandler struct {
swaggerFS http.FileSystem
}

func (h *swaggerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Set minimal CORS headers
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET")

if r.Method == http.MethodOptions {
return
}

// Process the path
urlPath := strings.TrimPrefix(r.URL.Path, "/swagger")
if urlPath == "" || urlPath == "/" {
urlPath = "/index.html"
}

// Open the file
file, err := h.swaggerFS.Open(urlPath)
Fixed Show fixed Hide fixed
if err != nil {
http.Error(w, "File not found", http.StatusNotFound)
return
}
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

Add path sanitization to prevent directory traversal.

The current path handling could be vulnerable to directory traversal attacks. Consider using filepath.Clean and additional validation.

 // Process the path
 urlPath := strings.TrimPrefix(r.URL.Path, "/swagger")
+urlPath = filepath.Clean(urlPath)
+if strings.Contains(urlPath, "..") {
+    http.Error(w, "Invalid path", http.StatusBadRequest)
+    return
+}
 if urlPath == "" || urlPath == "/" {
     urlPath = "/index.html"
 }
📝 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
// Process the path
urlPath := strings.TrimPrefix(r.URL.Path, "/swagger")
if urlPath == "" || urlPath == "/" {
urlPath = "/index.html"
}
// Open the file
file, err := h.swaggerFS.Open(urlPath)
if err != nil {
http.Error(w, "File not found", http.StatusNotFound)
return
}
// Process the path
urlPath := strings.TrimPrefix(r.URL.Path, "/swagger")
urlPath = filepath.Clean(urlPath)
if strings.Contains(urlPath, "..") {
http.Error(w, "Invalid path", http.StatusBadRequest)
return
}
if urlPath == "" || urlPath == "/" {
urlPath = "/index.html"
}
// Open the file
file, err := h.swaggerFS.Open(urlPath)
if err != nil {
http.Error(w, "File not found", http.StatusNotFound)
return
}

defer file.Close()

// Set the content-type
ext := filepath.Ext(urlPath)
if ct := getContentType(ext); ct != "" {
w.Header().Set("Content-Type", ct)
}

// Set caching headers
w.Header().Set("Cache-Control", "public, max-age=31536000")
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
Fixed Show fixed Hide fixed

// Serve the file
http.ServeContent(w, r, urlPath, time.Now(), file.(io.ReadSeeker))

Check warning

Code scanning / CodeQL

Calling the system time Warning

Calling the system time may be a possible source of non-determinism
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

Optimize caching implementation and add security headers.

  1. Use a constant time for Last-Modified to ensure deterministic behavior
  2. Add security headers to protect against common web vulnerabilities
 // Set caching headers
 w.Header().Set("Cache-Control", "public, max-age=31536000")
-w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
+// Use a fixed timestamp for deterministic behavior
+w.Header().Set("Last-Modified", "Mon, 01 Jan 2024 00:00:00 GMT")
+
+// Add security headers
+w.Header().Set("X-Content-Type-Options", "nosniff")
+w.Header().Set("X-Frame-Options", "DENY")
+w.Header().Set("Content-Security-Policy", "default-src 'self'")

-http.ServeContent(w, r, urlPath, time.Now(), file.(io.ReadSeeker))
+http.ServeContent(w, r, urlPath, time.Unix(0, 0), file.(io.ReadSeeker))
📝 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
// Set caching headers
w.Header().Set("Cache-Control", "public, max-age=31536000")
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
// Serve the file
http.ServeContent(w, r, urlPath, time.Now(), file.(io.ReadSeeker))
// Set caching headers
w.Header().Set("Cache-Control", "public, max-age=31536000")
// Use a fixed timestamp for deterministic behavior
w.Header().Set("Last-Modified", "Mon, 01 Jan 2024 00:00:00 GMT")
// Add security headers
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("Content-Security-Policy", "default-src 'self'")
// Serve the file
http.ServeContent(w, r, urlPath, time.Unix(0, 0), file.(io.ReadSeeker))

}

// getContentType returns the content-type for a file extension
func getContentType(ext string) string {
switch strings.ToLower(ext) {
case ".html":
return "text/html"
case ".css":
return "text/css"
case ".js":
return "application/javascript"
case ".json":
return "application/json"
case ".png":
return "image/png"
case ".jpg", ".jpeg":
return "image/jpeg"
case ".svg":
return "image/svg+xml"
default:
return ""
}
}
110 changes: 110 additions & 0 deletions server/v2/api/swagger/server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package swagger

import (
"context"
"fmt"
"net/http"

"cosmossdk.io/core/server"
"cosmossdk.io/core/transaction"
"cosmossdk.io/log"
serverv2 "cosmossdk.io/server/v2"
)

var (
_ serverv2.ServerComponent[transaction.Tx] = (*Server[transaction.Tx])(nil)
_ serverv2.HasConfig = (*Server[transaction.Tx])(nil)
)

// Server represents a Swagger UI server
type Server[T transaction.Tx] struct {
logger log.Logger
config *Config
cfgOptions []CfgOption
server *http.Server
}

// New creates a new Swagger UI server
func New[T transaction.Tx](
logger log.Logger,
cfg server.ConfigMap,
cfgOptions ...CfgOption,
) (*Server[T], error) {
srv := &Server[T]{
logger: logger.With(log.ModuleKey, ServerName),
cfgOptions: cfgOptions,
}

serverCfg := srv.Config().(*Config)
julienrbrt marked this conversation as resolved.
Show resolved Hide resolved
if len(cfg) > 0 {
if err := serverv2.UnmarshalSubConfig(cfg, srv.Name(), &serverCfg); err != nil {
return nil, fmt.Errorf("failed to unmarshal config: %w", err)
}
}
srv.config = serverCfg

if err := srv.config.Validate(); err != nil {
return nil, err
}

mux := http.NewServeMux()
mux.Handle(srv.config.Path, &swaggerHandler{
swaggerFS: srv.config.SwaggerUI,
})

srv.server = &http.Server{
Addr: srv.config.Address,
Handler: mux,
}

return srv, nil
}

// NewWithConfigOptions creates a new server with configuration options
func NewWithConfigOptions[T transaction.Tx](opts ...CfgOption) *Server[T] {
return &Server[T]{
cfgOptions: opts,
}
}

// Name returns the server's name
func (s *Server[T]) Name() string {
return ServerName
}

// Config returns the server configuration
func (s *Server[T]) Config() any {
if s.config == nil || s.config.Address == "" {
cfg := DefaultConfig()
for _, opt := range s.cfgOptions {
opt(cfg)
}
return cfg
}
return s.config
}

// Start starts the server
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
}

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)
}

return nil
}

// Stop stops the server
func (s *Server[T]) Stop(ctx context.Context) error {
if !s.config.Enable {
return nil
}

s.logger.Info("stopping swagger server...", "address", s.config.Address)
return s.server.Shutdown(ctx)
}
1 change: 1 addition & 0 deletions simapp/v2/app.go
julienrbrt marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ func NewSimApp[T transaction.Tx](
if err = app.LoadLatest(); err != nil {
return nil, err
}

return app, nil
}

Expand Down
16 changes: 16 additions & 0 deletions simapp/v2/simdv2/cmd/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ import (
genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
v2 "github.com/cosmos/cosmos-sdk/x/genutil/v2/cli"
"cosmossdk.io/client/docs"
Copy link
Member

Choose a reason for hiding this comment

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

This import doesn't exist and the ordering is wrong (Make lint-fix should have fixed that.)

swaggerv2 "cosmossdk.io/server/v2/api/swagger"
)

// CommandDependencies is a struct that contains all the dependencies needed to initialize the root command.
Expand Down Expand Up @@ -92,6 +94,7 @@ func InitRootCmd[T transaction.Tx](
&telemetry.Server[T]{},
&rest.Server[T]{},
&grpcgateway.Server[T]{},
&swaggerv2.Server[T]{},
)
}

Expand Down Expand Up @@ -163,6 +166,18 @@ func InitRootCmd[T transaction.Tx](
}
registerGRPCGatewayRoutes[T](deps, grpcgatewayServer)

// Create Swagger server
swaggerServer, err := swaggerv2.New[T](
logger.With(log.ModuleKey, "swagger"),
Copy link
Member

Choose a reason for hiding this comment

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

We can just pass the litter here, the key is added in the constrictor

deps.GlobalConfig,
swaggerv2.CfgOption(func(cfg *swaggerv2.Config) {
cfg.SwaggerUI = docs.SwaggerUI
}),
)
if err != nil {
return nil, err
}

// wire server commands
return serverv2.AddCommands[T](
rootCmd,
Expand All @@ -176,6 +191,7 @@ func InitRootCmd[T transaction.Tx](
telemetryServer,
restServer,
grpcgatewayServer,
swaggerServer,
)
}

Expand Down
Loading