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: Trusted Proxies #624

Merged
merged 3 commits into from
Feb 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 4 additions & 0 deletions config.example.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ server:

responseheaders: # response headers are added to every response (default: none)
# X-Custom-Header: "custom value"
#
trustedproxies: # IPs or IP ranges of trusted proxies. Used to obtain the remote ip via the X-Forwarded-For header. (configure 127.0.0.1 to trust sockets)
# - 127.0.0.1/32
# - ::1

cors: # Sets cors headers only when needed and provides support for multiple allowed origins. Overrides Access-Control-* Headers in response headers.
alloworigins:
Expand Down
2 changes: 2 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ type Configuration struct {
AllowMethods []string
AllowHeaders []string
}

TrustedProxies []string
}
Database struct {
Dialect string `default:"sqlite3"`
Expand Down
11 changes: 11 additions & 0 deletions router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,17 @@
func Create(db *database.GormDatabase, vInfo *model.VersionInfo, conf *config.Configuration) (*gin.Engine, func()) {
g := gin.New()

g.RemoteIPHeaders = []string{"X-Forwarded-For"}
g.SetTrustedProxies(conf.Server.TrustedProxies)
g.ForwardedByClientIP = true

g.Use(func(ctx *gin.Context) {
// Map sockets "@" to 127.0.0.1, because gin-gonic can only trust IPs.
if ctx.Request.RemoteAddr == "@" {
ctx.Request.RemoteAddr = "127.0.0.1:65535"

Check warning on line 37 in router/router.go

View check run for this annotation

Codecov / codecov/patch

router/router.go#L37

Added line #L37 was not covered by tests
}
})

g.Use(gin.LoggerWithFormatter(logFormatter), gin.Recovery(), gerror.Handler(), location.Default())
g.NoRoute(gerror.NotFound())

Expand Down
Loading