Skip to content

BillionMail gives you open-source MailServer, NewsLetter, Email Marketing — fully self-hosted, dev-friendly, and free from monthly fees. Join the discord: https://discord.gg/asfXzBUhZr

added validate_code unit test.

Jacka44174c81f29
diff --git a/core/internal/service/rbac/validate_code.go b/core/internal/service/rbac/validate_code.go
index dd2957f0..ee736178 100644
--- a/core/internal/service/rbac/validate_code.go
+++ b/core/internal/service/rbac/validate_code.go
@@ -132,74 +132,91 @@ func (p *CodePool) RefreshPool(force bool) {
ctx := context.Background()
currentSize := len(p.pool)
+ // Always ensure at least one captcha is generated (to solve empty pool issue)
+ neededCodes := p.poolSize - currentSize
+ if neededCodes <= 0 && force {
+ neededCodes = 1 // Generate at least one in force mode
+ }
+
// Refresh pool if forced or pool size is below threshold
- if force || currentSize < p.refreshRate {
- neededCodes := p.poolSize - currentSize
+ if neededCodes > 0 {
g.Log().Debug(ctx, "Refreshing code pool, current size:", currentSize, "needed:", neededCodes)
// Generate new captchas to fill the pool
- for i := 0; i < neededCodes; i++ {
+ successCount := 0
+ maxAttempts := neededCodes * 2 // Maximum attempts to avoid infinite loop
+
+ for i := 0; i < maxAttempts && successCount < neededCodes; i++ {
id, _, answer, err := p.captcha.Generate()
if err != nil {
g.Log().Error(ctx, "Failed to generate captcha:", err)
continue
}
p.pool[id] = answer
+ p.store.Set(id, answer) // Immediately add to storage
+ successCount++
}
- g.Log().Debug(ctx, "Code pool refreshed, new size:", len(p.pool))
+ g.Log().Debug(ctx, "Code pool refreshed, new size:", len(p.pool), "added:", successCount)
}
}
// GetCode Get a captcha from the pool
func (p *CodePool) GetCode() (id string, b64s string, err error) {
- p.mutex.Lock()
+ maxRetries := 3
+ for retry := 0; retry < maxRetries; retry++ {
+ // If pool is empty, try refresh first, then generate directly (to avoid failure)
+ if retry > 0 || len(p.pool) == 0 {
+ // Generate a new captcha directly (not relying on pool)
+ id, b64s, _, err = p.captcha.Generate()
+ if err == nil {
+ return id, b64s, nil
+ }
+ g.Log().Error(context.Background(), "Failed to generate captcha directly:", err)
+ time.Sleep(100 * time.Millisecond) // Short delay before retry
+ continue
+ }
- // If pool is empty, try to refresh
- if len(p.pool) == 0 {
- p.mutex.Unlock()
- p.RefreshPool(true)
p.mutex.Lock()
+ poolSize := len(p.pool)
- // If still empty, return error
- if len(p.pool) == 0 {
+ if poolSize == 0 {
p.mutex.Unlock()
- return "", "", errors.New("captcha pool is empty")
+ continue // Proceed to next iteration, try direct generation
}
- }
- // Take a captcha from the pool
- for id, answer := range p.pool {
- delete(p.pool, id)
- p.mutex.Unlock()
+ // Get a captcha from the pool
+ for captchaID, answer := range p.pool {
+ delete(p.pool, id) // Remove from pool
+ p.mutex.Unlock()
- // Get the captcha image data
- item := p.store.Get(id, false)
- if item == "" {
- // If not found in storage, regenerate the captcha
- p.store.Set(id, answer)
- }
+ // Regenerate image data
+ itemC, drawErr := p.captcha.Driver.DrawCaptcha(answer)
+ if drawErr != nil {
+ g.Log().Error(context.Background(), "Failed to draw captcha:", drawErr)
+ break // Break loop and proceed to next retry
+ }
- // Regenerate image data
- itemC, err := p.captcha.Driver.DrawCaptcha(answer)
+ b64s = itemC.EncodeB64string()
- if err != nil {
- g.Log().Error(context.Background(), "Failed to draw captcha:", err)
- return "", "", err
- }
-
- b64s = itemC.EncodeB64string()
+ // Asynchronously refresh if pool size is below threshold
+ if poolSize < p.refreshRate {
+ go p.RefreshPool(false)
+ }
- // If pool size is below threshold, asynchronously refresh
- if len(p.pool) < p.refreshRate {
- go p.RefreshPool(false)
+ return captchaID, b64s, nil
}
+ p.mutex.Unlock() // Ensure unlock
+ }
+
+ // Final attempt to generate a captcha directly as fallback
+ id, b64s, _, err = p.captcha.Generate()
+ if err == nil {
return id, b64s, nil
}
- p.mutex.Unlock()
- return "", "", errors.New("unable to get captcha")
+ return "", "", errors.New("unable to get captcha after multiple attempts")
}
// VerifyCode Verify captcha
diff --git a/core/internal/service/rbac/validate_code_test.go b/core/internal/service/rbac/validate_code_test.go
new file mode 100644
index 00000000..5267146d
--- /dev/null
+++ b/core/internal/service/rbac/validate_code_test.go
@@ -0,0 +1,151 @@
+package rbac
+
+import "testing"
+
+func TestGenerateCaptcha(t *testing.T) {
+ // Basic functionality test - only checks return value types and non-emptiness
+ t.Run("Basic functionality check", func(t *testing.T) {
+ gotId, gotB64s, gotAnswer, err := GenerateCaptcha()
+ if err != nil {
+ t.Errorf("GenerateCaptcha() should not return error, but got: %v", err)
+ }
+ if gotId == "" {
+ t.Error("GenerateCaptcha() returned ID should not be empty")
+ }
+ if gotB64s == "" {
+ t.Error("GenerateCaptcha() returned Base64 string should not be empty")
+ }
+ if len(gotAnswer) != 4 {
+ t.Errorf("GenerateCaptcha() returned answer length should be 4, but got: %d", len(gotAnswer))
+ }
+ })
+
+ // Verify if the captcha answer can pass verification
+ t.Run("Captcha verification test", func(t *testing.T) {
+ gotId, _, gotAnswer, err := GenerateCaptcha()
+ if err != nil {
+ t.Errorf("GenerateCaptcha() should not return error, but got: %v", err)
+ return
+ }
+
+ // Verify with correct answer
+ if !VerifyCaptcha(gotId, gotAnswer) {
+ t.Error("VerifyCaptcha() should return true with correct answer")
+ }
+
+ // Verify with wrong answer
+ if VerifyCaptcha(gotId, "wrong answer") {
+ t.Error("VerifyCaptcha() should return false with wrong answer")
+ }
+ })
+
+ // Verify the format of generated captcha
+ t.Run("Captcha format test", func(t *testing.T) {
+ _, _, gotAnswer, err := GenerateCaptcha()
+ if err != nil {
+ t.Errorf("GenerateCaptcha() should not return error, but got: %v", err)
+ return
+ }
+
+ // According to defaultDriver configuration, the answer should only contain characters from "34578abcdefhjkmnprstuvwxy"
+ validChars := "34578abcdefhjkmnprstuvwxy"
+ for _, char := range gotAnswer {
+ found := false
+ for _, validChar := range validChars {
+ if char == validChar {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Errorf("Captcha contains invalid character: %c", char)
+ }
+ }
+ })
+
+ // Test the GetCaptchaAnswer function
+ t.Run("Get answer test", func(t *testing.T) {
+ gotId, _, gotAnswer, err := GenerateCaptcha()
+ if err != nil {
+ t.Errorf("GenerateCaptcha() should not return error, but got: %v", err)
+ return
+ }
+
+ // Get answer via GetCaptchaAnswer
+ retrievedAnswer := GetCaptchaAnswer(gotId)
+ if retrievedAnswer != gotAnswer {
+ t.Errorf("GetCaptchaAnswer() = %v, want %v", retrievedAnswer, gotAnswer)
+ }
+ })
+}
+
+func TestGetCaptcha(t *testing.T) {
+ // Test basic functionality
+ t.Run("Basic functionality", func(t *testing.T) {
+ gotId, gotB64s, err := GetCaptcha()
+ if err != nil {
+ t.Errorf("GetCaptcha() should not return error, but got: %v", err)
+ }
+ if gotId == "" {
+ t.Error("GetCaptcha() returned ID should not be empty")
+ }
+ if gotB64s == "" {
+ t.Error("GetCaptcha() returned Base64 string should not be empty")
+ }
+ })
+
+ // Test handling of empty captcha pool
+ t.Run("Empty pool handling", func(t *testing.T) {
+ // Create a temporary pool for testing
+ originalPool := globalPool
+ defer func() {
+ globalPool = originalPool // Restore original pool after test
+ }()
+
+ // Create an empty pool
+ emptyPool := NewCodePool(0, DefaultExpiration, DefaultRefreshRate)
+ globalPool = emptyPool
+
+ // Force empty the pool
+ emptyPool.mutex.Lock()
+ emptyPool.pool = make(map[string]string, 0)
+ emptyPool.mutex.Unlock()
+
+ // Call GetCaptcha, it should handle empty pool and generate new captcha
+ gotId, gotB64s, err := GetCaptcha()
+ if err != nil {
+ // Even with empty pool, it should auto-refresh and generate captcha
+ t.Errorf("GetCaptcha() should auto-refresh with empty pool, but got error: %v", err)
+ }
+ if gotId == "" || gotB64s == "" {
+ t.Error("After auto-refresh, GetCaptcha() results should not be empty")
+ }
+ })
+
+ // Test verification process
+ t.Run("Verification test", func(t *testing.T) {
+ // Get a captcha
+ gotId, _, err := GetCaptcha()
+ if err != nil {
+ t.Errorf("GetCaptcha() should not return error, but got: %v", err)
+ return
+ }
+
+ // Get correct answer
+ answer := GetCaptchaAnswer(gotId)
+ if answer == "" {
+ t.Error("Failed to get captcha answer")
+ return
+ }
+
+ // Verify with correct answer
+ if !VerifyCaptcha(gotId, answer) {
+ t.Error("Verification failed with correct answer")
+ }
+
+ // Verify with wrong answer
+ if VerifyCaptcha(gotId, "wrong answer") {
+ t.Error("Verification should not succeed with wrong answer")
+ }
+ })
+}