59 lines
1.9 KiB
Go
59 lines
1.9 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"hfb_sys/backend/internal/tenancy"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func TestRequireKnownApplicationHostFailsClosedOnlyInProduction(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
|
|
newEngine := func(appEnv string) *gin.Engine {
|
|
engine := gin.New()
|
|
engine.Use(RequireKnownApplicationHost(appEnv))
|
|
engine.GET("/api/listings", func(c *gin.Context) { c.Status(http.StatusOK) })
|
|
engine.POST("/api/payments/leshua/notify", func(c *gin.Context) { c.Status(http.StatusOK) })
|
|
return engine
|
|
}
|
|
|
|
production := newEngine("production")
|
|
req := httptest.NewRequest(http.MethodGet, "http://unknown.example.com/api/listings", nil)
|
|
req.Host = "unknown.example.com"
|
|
rec := httptest.NewRecorder()
|
|
production.ServeHTTP(rec, req)
|
|
if rec.Code != http.StatusNotFound {
|
|
t.Fatalf("unknown production host status = %d, want 404", rec.Code)
|
|
}
|
|
|
|
req = httptest.NewRequest(http.MethodPost, "http://callback.example.com/api/payments/leshua/notify", nil)
|
|
req.Host = "callback.example.com"
|
|
rec = httptest.NewRecorder()
|
|
production.ServeHTTP(rec, req)
|
|
if rec.Code != http.StatusOK {
|
|
t.Fatalf("payment callback status = %d, want 200", rec.Code)
|
|
}
|
|
|
|
req = httptest.NewRequest(http.MethodGet, "http://unknown.example.com/api/listings", nil)
|
|
req.Host = "unknown.example.com"
|
|
req = req.WithContext(tenancy.WithScope(req.Context(), tenancy.Scope{TenantID: 101}))
|
|
rec = httptest.NewRecorder()
|
|
production.ServeHTTP(rec, req)
|
|
if rec.Code != http.StatusOK {
|
|
t.Fatalf("known tenant status = %d, want 200", rec.Code)
|
|
}
|
|
|
|
development := newEngine("development")
|
|
req = httptest.NewRequest(http.MethodGet, "http://unknown.example.com/api/listings", nil)
|
|
req.Host = "unknown.example.com"
|
|
rec = httptest.NewRecorder()
|
|
development.ServeHTTP(rec, req)
|
|
if rec.Code != http.StatusOK {
|
|
t.Fatalf("development unknown host status = %d, want 200", rec.Code)
|
|
}
|
|
}
|