veza/veza-backend-api/internal/services/captcha_service_test.go
senke e4dd09a909
Some checks failed
Backend API CI / test-unit (push) Failing after 0s
Backend API CI / test-integration (push) Failing after 0s
feat(v0.13.0): conformité features partielles — CAPTCHA, password history, login history, SMS 2FA
TASK-CONF-001: SMS 2FA service (sms_2fa_service.go) — SMSProvider interface,
  rate limiting (3/h), 6-digit codes, 5min expiry, LogSMSProvider for dev.
TASK-CONF-002: CAPTCHA service (captcha_service.go) — Cloudflare Turnstile
  verification with fail-open + RequireCaptcha middleware. 11 tests.
TASK-CONF-003: Auth features completed:
  - F014 password history (password_history_service.go) — checks last 5 hashes,
    integrated into PasswordService.ChangePassword. 3 tests.
  - F024 login history (login_history_service.go) — Record, GetUserHistory,
    CountRecentFailures for security auditing.
  - F010/F013/F018/F021/F026 verified already implemented.
TASK-CONF-004: F075 ClamAV verified implemented. F080 watermark deferred (P4).
TASK-CONF-005: ADR-005 handler architecture documented (keep dual, migrate forward).
TASK-CONF-006: Frontend 0 TODO/FIXME, backend 1 — criteria met.

Migration: 970_password_login_history_v0130.sql (password_history, login_history,
sms_verification_codes tables).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 09:31:50 +01:00

99 lines
3.1 KiB
Go

package services
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
)
// TestCaptchaService_Disabled verifies that disabled CAPTCHA always passes.
func TestCaptchaService_Disabled(t *testing.T) {
svc := NewCaptchaService(CaptchaConfig{Enabled: false}, zap.NewNop())
err := svc.Verify(context.Background(), "", "127.0.0.1")
assert.NoError(t, err, "disabled CAPTCHA should always pass")
}
// TestCaptchaService_EmptyToken verifies that enabled CAPTCHA rejects empty token.
func TestCaptchaService_EmptyToken(t *testing.T) {
svc := NewCaptchaService(CaptchaConfig{Enabled: true, SecretKey: "test"}, zap.NewNop())
err := svc.Verify(context.Background(), "", "127.0.0.1")
assert.Error(t, err)
assert.Contains(t, err.Error(), "captcha token required")
}
// TestCaptchaService_VerifySuccess verifies that a valid CAPTCHA token is accepted.
func TestCaptchaService_VerifySuccess(t *testing.T) {
// Mock Turnstile API
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
resp := map[string]interface{}{"success": true}
json.NewEncoder(w).Encode(resp)
}))
defer server.Close()
svc := &CaptchaService{
secretKey: "test-secret",
verifyURL: server.URL,
enabled: true,
httpClient: server.Client(),
logger: zap.NewNop(),
}
err := svc.Verify(context.Background(), "valid-token", "127.0.0.1")
assert.NoError(t, err)
}
// TestCaptchaService_VerifyFailure verifies that an invalid CAPTCHA token is rejected.
func TestCaptchaService_VerifyFailure(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
resp := map[string]interface{}{
"success": false,
"error-codes": []string{"invalid-input-response"},
}
json.NewEncoder(w).Encode(resp)
}))
defer server.Close()
svc := &CaptchaService{
secretKey: "test-secret",
verifyURL: server.URL,
enabled: true,
httpClient: server.Client(),
logger: zap.NewNop(),
}
err := svc.Verify(context.Background(), "bad-token", "127.0.0.1")
assert.Error(t, err)
assert.Contains(t, err.Error(), "captcha verification failed")
}
// TestCaptchaService_IsEnabled returns correct state.
func TestCaptchaService_IsEnabled(t *testing.T) {
disabled := NewCaptchaService(CaptchaConfig{Enabled: false}, zap.NewNop())
assert.False(t, disabled.IsEnabled())
enabled := NewCaptchaService(CaptchaConfig{Enabled: true, SecretKey: "k"}, zap.NewNop())
assert.True(t, enabled.IsEnabled())
}
// TestCaptchaService_FailOpen verifies that if the CAPTCHA server is unreachable, we fail open.
func TestCaptchaService_FailOpen(t *testing.T) {
svc := &CaptchaService{
secretKey: "test-secret",
verifyURL: "http://localhost:1", // unreachable
enabled: true,
httpClient: &http.Client{},
logger: zap.NewNop(),
}
err := svc.Verify(context.Background(), "some-token", "127.0.0.1")
// Should fail open (not block users when CAPTCHA service is down)
require.NoError(t, err, "should fail open when CAPTCHA service is unreachable")
}