Skip to content
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
43 changes: 43 additions & 0 deletions apiserver/internal/utils/middleware/middleware.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package middleware

import (
"fmt"
"net/http"
"strconv"
"strings"

"dkhalife.com/tasks/core/config"
"dkhalife.com/tasks/core/internal/services/logging"
Expand Down Expand Up @@ -43,6 +45,47 @@ func RateLimitMiddleware(limiter *limiter.Limiter) gin.HandlerFunc {
}
}

func effectiveScheme(c *gin.Context) string {
if forwarded := c.GetHeader("X-Forwarded-Proto"); forwarded != "" {
scheme := forwarded
if i := strings.IndexByte(scheme, ','); i >= 0 {
scheme = scheme[:i]
}
return strings.ToLower(strings.TrimSpace(scheme))
}

if c.Request.TLS != nil {
return "https"
}

return "http"
}

func SecurityHeaders(cfg *config.Config) gin.HandlerFunc {
hostName := cfg.Server.HostName
port := cfg.Server.Port

return func(c *gin.Context) {
scheme := effectiveScheme(c)
if scheme == "http" {
target := fmt.Sprintf("https://%s", hostName)
if port != 443 {
target = fmt.Sprintf("%s:%d", target, port)
}
target = fmt.Sprintf("%s%s", target, c.Request.URL.RequestURI())
c.Redirect(http.StatusMovedPermanently, target)
c.Abort()
return
}

if scheme == "https" {
c.Header("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload")
}

c.Next()
Comment thread
dkhalife marked this conversation as resolved.
}
}

func RequestLogger() gin.HandlerFunc {
return func(c *gin.Context) {
c.Next()
Expand Down
126 changes: 126 additions & 0 deletions apiserver/internal/utils/middleware/middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package middleware

import (
"context"
"crypto/tls"
"errors"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -91,3 +92,128 @@ func (s *MiddlewareTestSuite) TestRateLimitMiddlewareStoreFailure() {
s.router.ServeHTTP(w, req)
s.Equal(http.StatusInternalServerError, w.Code)
}

func (s *MiddlewareTestSuite) TestSecurityHeadersAddsHSTS() {
cfg := &config.Config{
Server: config.ServerConfig{
HostName: "example.com",
Port: 443,
},
}

s.router.Use(SecurityHeaders(cfg))
s.router.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "OK")
})

w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/", nil)
req.Header.Set("X-Forwarded-Proto", "https")
s.router.ServeHTTP(w, req)
s.Equal(http.StatusOK, w.Code)
s.Equal("max-age=31536000; includeSubDomains; preload", w.Header().Get("Strict-Transport-Security"))
}

func (s *MiddlewareTestSuite) TestSecurityHeadersNoHSTSForPlainHTTP() {
cfg := &config.Config{
Server: config.ServerConfig{
HostName: "example.com",
Port: 443,
},
}

s.router.Use(SecurityHeaders(cfg))
s.router.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "OK")
})

w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/", nil)
s.router.ServeHTTP(w, req)
s.Equal(http.StatusMovedPermanently, w.Code)
s.Empty(w.Header().Get("Strict-Transport-Security"))
}

func (s *MiddlewareTestSuite) TestSecurityHeadersHSTSWithDirectTLS() {
cfg := &config.Config{
Server: config.ServerConfig{
HostName: "example.com",
Port: 443,
},
}

s.router.Use(SecurityHeaders(cfg))
s.router.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "OK")
})

w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/", nil)
req.TLS = &tls.ConnectionState{}
s.router.ServeHTTP(w, req)
s.Equal(http.StatusOK, w.Code)
s.Equal("max-age=31536000; includeSubDomains; preload", w.Header().Get("Strict-Transport-Security"))
}
Comment thread
dkhalife marked this conversation as resolved.

func (s *MiddlewareTestSuite) TestSecurityHeadersRedirectsHTTP() {
cfg := &config.Config{
Server: config.ServerConfig{
HostName: "example.com",
Port: 443,
},
}

s.router.Use(SecurityHeaders(cfg))
s.router.GET("/path", func(c *gin.Context) {
c.String(http.StatusOK, "OK")
})

w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/path?q=1", nil)
req.Header.Set("X-Forwarded-Proto", "http")
s.router.ServeHTTP(w, req)
s.Equal(http.StatusMovedPermanently, w.Code)
s.Equal("https://example.com/path?q=1", w.Header().Get("Location"))
}

func (s *MiddlewareTestSuite) TestSecurityHeadersRedirectsHTTPNonStandardPort() {
cfg := &config.Config{
Server: config.ServerConfig{
HostName: "example.com",
Port: 8443,
},
}

s.router.Use(SecurityHeaders(cfg))
s.router.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "OK")
})

w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/", nil)
req.Header.Set("X-Forwarded-Proto", "http")
s.router.ServeHTTP(w, req)
s.Equal(http.StatusMovedPermanently, w.Code)
s.Equal("https://example.com:8443/", w.Header().Get("Location"))
}

func (s *MiddlewareTestSuite) TestSecurityHeadersNoRedirectForHTTPS() {
cfg := &config.Config{
Server: config.ServerConfig{
HostName: "example.com",
Port: 443,
},
}

s.router.Use(SecurityHeaders(cfg))
s.router.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "OK")
})

w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/", nil)
req.Header.Set("X-Forwarded-Proto", "https")
s.router.ServeHTTP(w, req)
s.Equal(http.StatusOK, w.Code)
s.Equal("max-age=31536000; includeSubDomains; preload", w.Header().Get("Strict-Transport-Security"))
}
1 change: 1 addition & 0 deletions apiserver/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ func newServer(lc fx.Lifecycle, cfg *config.Config, db *gorm.DB, bgScheduler *sc
corsCfg.AddAllowHeaders("Authorization")
r.Use(cors.New(corsCfg))
}
r.Use(utils.SecurityHeaders(cfg))
r.Use(utils.RequestLogger())

lc.Append(fx.Hook{
Expand Down
6 changes: 6 additions & 0 deletions mcpserver/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,12 @@

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
app.UseHsts();
app.UseHttpsRedirection();
}

app.UseAuthentication();
app.UseAuthorization();
app.MapMcp().RequireAuthorization();
Expand Down
Loading