Files
gochat/backend/internal/middleware/account_scope_test.go
T
Rogeeandrogee cf263d10b4 HH-437: harden production auth and tenant authorization (#84)
* HH-437 harden auth and account authorization

* HH-437 reject revoked platform access

---------

Co-authored-by: Rogee <rogee@ipao.vip>
2026-08-21 19:13:10 +08:00

228 lines
6.8 KiB
Go

package middleware
import (
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/gochat/gochat/internal/auth"
"github.com/gochat/gochat/internal/config"
"github.com/gochat/gochat/internal/model"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type accountScopeLookup struct{ accountID uint }
func (l accountScopeLookup) GetAccountUserRole(_ uint, accountID uint) (string, uint, error) {
if accountID != l.accountID {
return "", 0, errors.New("membership not found")
}
return "administrator", 0, nil
}
func (accountScopeLookup) GetCustomRolePermissions(uint) (auth.PermissionMatrixMap, error) {
return nil, nil
}
func TestAccountScope_NoUserID(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(AccountScope())
r.GET("/test", func(c *gin.Context) {
c.JSON(200, gin.H{"ok": true})
})
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/test", nil)
r.ServeHTTP(w, req)
assert.Equal(t, 401, w.Code)
}
func TestAccountScope_NoAccountID(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(func(c *gin.Context) { c.Set("user_id", uint(1)); c.Next() })
r.Use(AccountScope())
r.GET("/test", func(c *gin.Context) {
c.JSON(200, gin.H{"ok": true})
})
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/test", nil)
r.ServeHTTP(w, req)
assert.Equal(t, 400, w.Code)
}
func TestAccountScope_FromHeader(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(func(c *gin.Context) { c.Set("user_id", uint(1)); c.Next() })
r.Use(AccountScope())
r.GET("/test", func(c *gin.Context) {
accountID, _ := c.Get("account_id")
c.JSON(200, gin.H{"account_id": accountID})
})
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/test", nil)
req.Header.Set("X-Account-ID", "5")
r.ServeHTTP(w, req)
assert.Equal(t, 200, w.Code)
}
func TestAccountScope_FromContext(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(func(c *gin.Context) { c.Set("user_id", uint(1)); c.Set("account_id", uint(2)); c.Next() })
r.Use(AccountScope())
r.GET("/test", func(c *gin.Context) {
accountID, _ := c.Get("account_id")
c.JSON(200, gin.H{"account_id": accountID})
})
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/test", nil)
r.ServeHTTP(w, req)
assert.Equal(t, 200, w.Code)
}
func TestAccountScope_HeaderOverridesContext(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(func(c *gin.Context) { c.Set("user_id", uint(1)); c.Set("account_id", uint(2)); c.Next() })
r.Use(AccountScope())
r.GET("/test", func(c *gin.Context) {
accountID, _ := c.Get("account_id")
c.JSON(200, gin.H{"account_id": accountID})
})
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/test", nil)
req.Header.Set("X-Account-ID", "10")
r.ServeHTTP(w, req)
assert.Equal(t, 200, w.Code)
}
func TestAccountScope_InvalidHeaderAccountID(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(func(c *gin.Context) { c.Set("user_id", uint(1)); c.Next() })
r.Use(AccountScope())
r.GET("/test", func(c *gin.Context) {
c.JSON(200, gin.H{"ok": true})
})
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/test", nil)
req.Header.Set("X-Account-ID", "abc")
r.ServeHTTP(w, req)
assert.Equal(t, 400, w.Code)
}
func TestAccountScope_RouteAccountMustMatchContext(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(func(c *gin.Context) { c.Set("user_id", uint(1)); c.Set("account_id", uint(2)); c.Next() })
r.Use(AccountScope())
r.GET("/api/v2/accounts/:account_id/live_reports/conversation_metrics", func(c *gin.Context) {
accountID, _ := c.Get("account_id")
c.JSON(200, gin.H{"account_id": accountID})
})
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v2/accounts/3/live_reports/conversation_metrics", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusForbidden, w.Code)
}
func TestAccountScope_RouteAccountMatchesContext(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(func(c *gin.Context) { c.Set("user_id", uint(1)); c.Set("account_id", uint(2)); c.Next() })
r.Use(AccountScope())
r.GET("/api/v2/accounts/:account_id/live_reports/conversation_metrics", func(c *gin.Context) {
accountID, _ := c.Get("account_id")
c.JSON(200, gin.H{"account_id": accountID})
})
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v2/accounts/2/live_reports/conversation_metrics", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
}
func TestAccountScope_UsesAuthMiddlewareRoleForAdministratorRoute(t *testing.T) {
gin.SetMode(gin.TestMode)
cfg := &config.JWTConfig{
Secret: "account-scope-role-test-secret",
ExpiryHours: 1,
RefreshExpiryHours: 1,
}
jwtService := auth.NewJWTService(cfg)
tokens, err := jwtService.GenerateTokenPair(&model.User{
Base: model.Base{ID: 1},
Provider: "email",
}, 1, "administrator")
require.NoError(t, err)
r := gin.New()
r.Use(AuthMiddlewareWithService(jwtService))
r.Use(AccountScope())
r.POST(
"/api/v1/accounts/:account_id/agents",
RoleCheck("administrator"),
func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"ok": true}) },
)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/v1/accounts/1/agents", nil)
req.Header.Set("access-token", tokens.AccessToken)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code, w.Body.String())
}
func TestAccountScopeWithService_AllowsVerifiedAccountSwitch(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(func(c *gin.Context) {
c.Set("user_id", uint(1))
c.Set("account_id", uint(1))
c.Set("role", "agent")
c.Next()
})
r.Use(AccountScopeWithService(accountScopeLookup{accountID: 2}))
r.GET("/api/v1/accounts/:account_id", RoleCheck("administrator"), func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"account_id": c.GetUint("account_id")})
})
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/accounts/2", nil))
assert.Equal(t, http.StatusOK, w.Code, w.Body.String())
w = httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/accounts/3", nil))
assert.Equal(t, http.StatusForbidden, w.Code, w.Body.String())
}
func TestAccountScopeWithService_AllowsSuperAdminAcrossAccounts(t *testing.T) {
r := gin.New()
r.Use(func(c *gin.Context) {
c.Set("user_id", uint(1))
c.Set("account_id", uint(1))
c.Set("user_type", "super_admin")
c.Next()
})
r.Use(AccountScopeWithService(accountScopeLookup{accountID: 999}))
r.PATCH("/api/v1/accounts/:account_id", SuperAdminOrAdministrator(), func(c *gin.Context) {
c.Status(http.StatusOK)
})
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodPatch, "/api/v1/accounts/2", nil))
assert.Equal(t, http.StatusOK, w.Code, w.Body.String())
}