package tests
import (
"strings"
"testing"
)
// TestSQLInjection 测试 SQL 注入防护
func TestSQLInjection(t *testing.T) {
ensureUsers(t)
// 测试用户名中的 SQL 注入
t.Run("SQL Injection in username", func(t *testing.T) {
resp := doRequest(t, "POST", "/api/auth/register", map[string]string{
"username": "admin' OR '1'='1",
"password": "password123",
"email": "sql@test.com",
}, "")
// 应该正常处理,不应该崩溃或返回异常
if resp.Code == 500 {
t.Errorf("SQL injection caused server error: %s", resp.Body.String())
}
})
// 测试组织代码中的 SQL 注入
t.Run("SQL Injection in org code", func(t *testing.T) {
resp := doRequest(t, "POST", "/api/orgs", map[string]string{
"code": "test' OR '1'='1",
"name": "SQL Test Org",
}, User1Token)
// 应该正常处理或返回业务错误,而不是 SQL 错误
if resp.Code == 500 {
t.Errorf("SQL injection in org code caused server error: %s", resp.Body.String())
}
})
// 测试搜索中的 SQL 注入
t.Run("SQL Injection in search", func(t *testing.T) {
resp := doRequest(t, "GET", "/api/auth/users?keyword=admin' OR '1'='1", nil, AdminToken)
// 应该正常处理
if resp.Code == 500 {
t.Errorf("SQL injection in search caused server error: %s", resp.Body.String())
}
})
}
// TestXSSPrevention 测试 XSS 防护
func TestXSSPrevention(t *testing.T) {
ensureUsers(t)
xssPayload := ""
// 测试昵称中的 XSS
t.Run("XSS in nickname", func(t *testing.T) {
resp := doRequest(t, "PATCH", "/api/auth/me", map[string]string{
"nickname": xssPayload,
}, User1Token)
if resp.Code == 200 {
// 检查返回的数据是否被转义
if strings.Contains(resp.Body.String(), "