mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-10-14 12:02:27 +08:00
The redeem failure counter used INCR followed by Expire(24h) on every attempt, so each failed attempt refreshed the key TTL and the window never actually closed for a user who kept retrying within 24h. - Count attempts in a fixed 10-minute window via a small Lua script (INCR, then PEXPIRE only when the key is created or has no TTL), which is atomic and also repairs keys that lost their TTL. - Move the counter to the redeem:ratelimit:v2: key space so pre-existing 24h counters do not seed the new window. - Rename the service threshold to redeemMaxFailedAttempts (30) to reflect that it bounds attempts per window, not per hour. Public redeem behavior is unchanged apart from the window semantics: the check fails open when the counter read fails, and a failed increment never masks the underlying domain error.
78 lines
1.3 KiB
Go
78 lines
1.3 KiB
Go
//go:build unit
|
|
|
|
package repository
|
|
|
|
import (
|
|
"math"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
func TestRedeemRateLimitKey(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
userID int64
|
|
expected string
|
|
}{
|
|
{
|
|
name: "normal_user_id",
|
|
userID: 123,
|
|
expected: "redeem:ratelimit:v2:123",
|
|
},
|
|
{
|
|
name: "zero_user_id",
|
|
userID: 0,
|
|
expected: "redeem:ratelimit:v2:0",
|
|
},
|
|
{
|
|
name: "negative_user_id",
|
|
userID: -1,
|
|
expected: "redeem:ratelimit:v2:-1",
|
|
},
|
|
{
|
|
name: "max_int64",
|
|
userID: math.MaxInt64,
|
|
expected: "redeem:ratelimit:v2:9223372036854775807",
|
|
},
|
|
}
|
|
|
|
for _, tc := range tests {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
got := redeemRateLimitKey(tc.userID)
|
|
require.Equal(t, tc.expected, got)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestRedeemLockKey(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
code string
|
|
expected string
|
|
}{
|
|
{
|
|
name: "normal_code",
|
|
code: "ABC123",
|
|
expected: "redeem:lock:ABC123",
|
|
},
|
|
{
|
|
name: "empty_code",
|
|
code: "",
|
|
expected: "redeem:lock:",
|
|
},
|
|
{
|
|
name: "code_with_special_chars",
|
|
code: "CODE-2024:test",
|
|
expected: "redeem:lock:CODE-2024:test",
|
|
},
|
|
}
|
|
|
|
for _, tc := range tests {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
got := redeemLockKey(tc.code)
|
|
require.Equal(t, tc.expected, got)
|
|
})
|
|
}
|
|
}
|