forked from mtusi2026/mtusi2026lab7
feat: secure service connections and login
This commit is contained in:
@@ -0,0 +1,111 @@
|
||||
package loginlimit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/valkey-io/valkey-go"
|
||||
)
|
||||
|
||||
const keyPrefix = "login-rate:{login}:"
|
||||
|
||||
var (
|
||||
ErrInvalidConfig = errors.New("invalid login rate limit configuration")
|
||||
ErrStore = errors.New("login rate limit store unavailable")
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
AccountAttempts int64
|
||||
SourceAttempts int64
|
||||
Window time.Duration
|
||||
}
|
||||
|
||||
type Limiter struct {
|
||||
client valkey.Client
|
||||
script *valkey.Lua
|
||||
config Config
|
||||
}
|
||||
|
||||
func New(rawURL string, config Config, tlsConfiguration ...*tls.Config) (*Limiter, error) {
|
||||
if config.AccountAttempts < 1 || config.SourceAttempts < 1 || config.Window < time.Second {
|
||||
return nil, ErrInvalidConfig
|
||||
}
|
||||
option, err := valkey.ParseURL(rawURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: parse Valkey URL: %w", ErrStore, err)
|
||||
}
|
||||
if len(tlsConfiguration) > 0 && tlsConfiguration[0] != nil {
|
||||
option.TLSConfig = tlsConfiguration[0].Clone()
|
||||
}
|
||||
option.DisableCache = true
|
||||
client, err := valkey.NewClient(option)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: create Valkey client: %w", ErrStore, err)
|
||||
}
|
||||
return &Limiter{client: client, script: valkey.NewLuaScript(limitScript), config: config}, nil
|
||||
}
|
||||
|
||||
func (l *Limiter) Allow(ctx context.Context, username, source string) (bool, time.Duration, error) {
|
||||
result, err := l.script.Exec(ctx, l.client,
|
||||
[]string{key("account", username), key("source", source)},
|
||||
[]string{
|
||||
strconv.FormatInt(l.config.Window.Milliseconds(), 10),
|
||||
strconv.FormatInt(l.config.AccountAttempts, 10),
|
||||
strconv.FormatInt(l.config.SourceAttempts, 10),
|
||||
},
|
||||
).AsIntSlice()
|
||||
if err != nil {
|
||||
return false, 0, fmt.Errorf("%w: account login attempt: %w", ErrStore, err)
|
||||
}
|
||||
if len(result) != 2 {
|
||||
return false, 0, fmt.Errorf("%w: unexpected script result", ErrStore)
|
||||
}
|
||||
return result[0] == 1, time.Duration(result[1]) * time.Millisecond, nil
|
||||
}
|
||||
|
||||
func (l *Limiter) Close() error {
|
||||
l.client.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
func key(scope, value string) string {
|
||||
digest := sha256.Sum256([]byte(value))
|
||||
return keyPrefix + scope + ":" + hex.EncodeToString(digest[:])
|
||||
}
|
||||
|
||||
const limitScript = `
|
||||
local function increment(key, window)
|
||||
local count = redis.call('INCR', key)
|
||||
if count == 1 then
|
||||
redis.call('PEXPIRE', key, window)
|
||||
end
|
||||
local ttl = redis.call('PTTL', key)
|
||||
if ttl < 1 then
|
||||
redis.call('PEXPIRE', key, window)
|
||||
ttl = window
|
||||
end
|
||||
return count, ttl
|
||||
end
|
||||
|
||||
local window = tonumber(ARGV[1])
|
||||
local account_count, account_ttl = increment(KEYS[1], window)
|
||||
local source_count, source_ttl = increment(KEYS[2], window)
|
||||
local retry_after = 0
|
||||
|
||||
if account_count > tonumber(ARGV[2]) then
|
||||
retry_after = account_ttl
|
||||
end
|
||||
if source_count > tonumber(ARGV[3]) and source_ttl > retry_after then
|
||||
retry_after = source_ttl
|
||||
end
|
||||
if retry_after > 0 then
|
||||
return {0, retry_after}
|
||||
end
|
||||
return {1, 0}
|
||||
`
|
||||
Reference in New Issue
Block a user