Files
yhy-mager/backend/internal/httpapi/redis_limiter.go
xiewenjun 54c318c615
Some checks failed
Check / delivery-static (push) Has been cancelled
Check / api (push) Has been cancelled
Check / web (push) Has been cancelled
feat: implement license platform business flows and delivery tooling
Add admin and customer interfaces, orders, signed activation and leases, protected package delivery, keyring verification, migrations, security controls, tests and deployment documentation.

Co-Authored-By: Craft Agent <agents-noreply@craft.do>
2026-10-09 15:33:22 +08:00

85 lines
2.6 KiB
Go

package httpapi
import (
"context"
"fmt"
"net"
"os"
"path/filepath"
"strings"
"time"
"github.com/redis/go-redis/v9"
)
type EntryLimiter interface {
Allow(context.Context, string, int) (bool, error)
}
type RedisLimiter struct {
client *redis.Client
prefix string
}
var entryLimitScript = redis.NewScript(`
local n = redis.call('INCR', KEYS[1])
if n == 1 then redis.call('PEXPIRE', KEYS[1], 60000) end
if n > tonumber(ARGV[1]) then return 0 end
return 1
`)
func NewRedisLimiter(client *redis.Client, prefix string) *RedisLimiter {
return &RedisLimiter{client: client, prefix: prefix}
}
func (l *RedisLimiter) Allow(ctx context.Context, key string, limit int) (bool, error) {
ctx, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
defer cancel()
result, err := entryLimitScript.Run(ctx, l.client, []string{l.prefix + key}, limit).Int()
return result == 1, err
}
// Redis errors never fall back to per-process counters.
func ConfigureEntryLimiter(ops *Operations, getenv func(string) string) (func(), error) {
mode := getenv("ENTRY_LIMIT_MODE")
if mode == "local-dev" {
return func() {}, nil
}
if mode != "" && mode != "redis" {
return nil, fmt.Errorf("invalid entry limit mode")
}
addr := getenv("ENTRY_REDIS_ADDR")
if addr == "" {
return nil, fmt.Errorf("Redis entry limiting required; local-dev must be explicitly opted into")
}
host, _, err := net.SplitHostPort(addr)
if err != nil {
return nil, fmt.Errorf("invalid Redis address")
}
opts := &redis.Options{Addr: addr, Username: getenv("ENTRY_REDIS_USERNAME"), DialTimeout: 500 * time.Millisecond, ReadTimeout: 500 * time.Millisecond, WriteTimeout: 500 * time.Millisecond, MaxRetries: -1, ContextTimeoutEnabled: true}
if path := getenv("ENTRY_REDIS_PASSWORD_FILE"); path != "" {
if !filepath.IsAbs(path) {
return nil, fmt.Errorf("Redis password file must be absolute")
}
bytes, err := os.ReadFile(path)
if err != nil || len(bytes) == 0 || len(bytes) > 4096 {
return nil, fmt.Errorf("invalid Redis password file")
}
opts.Password = strings.TrimSpace(string(bytes))
}
// Current profile permits only numeric loopback/private IP transport. Remote TLS remains a release gate.
ip := net.ParseIP(host)
if ip == nil || (!ip.IsLoopback() && !ip.IsPrivate()) {
return nil, fmt.Errorf("Redis must use a numeric private or loopback IP")
}
client := redis.NewClient(opts)
prefix := getenv("ENTRY_REDIS_NAMESPACE")
if prefix == "" {
prefix = "license-platform:entry:"
}
if len(prefix) > 100 {
client.Close()
return nil, fmt.Errorf("invalid Redis namespace")
}
ops.limiter = NewRedisLimiter(client, prefix)
return func() { client.Close() }, nil
}