ulflow_phattt2901 9df4673657
Some checks failed
CI Pipeline / Security Scan (push) Failing after 4m42s
CI Pipeline / Lint (push) Failing after 5m1s
CI Pipeline / Test (push) Has been skipped
CI Pipeline / Build (push) Has been skipped
CI Pipeline / Notification (push) Successful in 2s
chore: Update config file
2025-05-25 15:22:23 +07:00

85 lines
2.1 KiB
Go

package middleware_test
import (
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"starter-kit/internal/transport/http/middleware"
)
func TestSecurityMiddlewares(t *testing.T) {
// Tạo router mới
r := gin.New()
// Lấy cấu hình bảo mật mặc định
config := middleware.DefaultSecurityConfig()
// Tùy chỉnh cấu hình nếu cần
config.CORS.AllowedOrigins = []string{"https://example.com"}
config.RateLimit.Rate = 100 // 100 requests per minute
config.Headers.ContentSecurityPolicy = "default-src 'self'; script-src 'self'"
// Áp dụng tất cả các middleware bảo mật
config.Apply(r)
// Thêm một route test
r.GET("/test", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "Hello, World!"})
})
// Tạo một test server
ts := httptest.NewServer(r)
defer ts.Close()
// Test CORS
t.Run("Test CORS", func(t *testing.T) {
resp, err := http.Get(ts.URL + "/test")
assert.NoError(t, err)
defer resp.Body.Close()
// Kiểm tra CORS header
assert.Equal(t, "https://example.com", resp.Header.Get("Access-Control-Allow-Origin"))
})
// Test rate limiting
t.Run("Test Rate Limiting", func(t *testing.T) {
// Gửi nhiều request để kiểm tra rate limiting
for i := 0; i < 110; i++ {
resp, err := http.Get(ts.URL + "/test")
assert.NoError(t, err)
resp.Body.Close()
if i >= 100 {
// Sau 100 request, server sẽ trả về 429
assert.Equal(t, http.StatusTooManyRequests, resp.StatusCode)
}
// Đợi một chút để tránh bị block bởi rate limiting
time.Sleep(10 * time.Millisecond)
}
})
// Test security headers
t.Run("Test Security Headers", func(t *testing.T) {
resp, err := http.Get(ts.URL + "/test")
assert.NoError(t, err)
defer resp.Body.Close()
// Kiểm tra các security headers
headers := []string{
"X-Frame-Options",
"X-Content-Type-Options",
"X-XSS-Protection",
"Content-Security-Policy",
}
for _, h := range headers {
assert.NotEmpty(t, resp.Header.Get(h), "Header %s should not be empty", h)
}
})
}