feat(embed): add backend embed channels with auth and rate limiting (#1657)

Introduce embed_channels storage, publish-token and session-token auth,
origin allowlist enforcement, shared Redis rate limiter, public embed API
routes, webhooks with SSRF validation, and session listing by embed source.
This commit is contained in:
wizardchen
2026-06-12 22:40:18 +08:00
committed by lyingbug
parent a0786b6fe7
commit ed9802ff2b
30 changed files with 4070 additions and 216 deletions
-199
View File
@@ -1,199 +0,0 @@
package im
import (
"context"
"fmt"
"sync"
"time"
"github.com/redis/go-redis/v9"
)
const (
// rateLimitWindow is the sliding window duration for rate limiting.
rateLimitWindow = 60 * time.Second
// rateLimitMaxRequests is the maximum number of requests allowed per window per key.
rateLimitMaxRequests = 10
// rateLimitCleanupInterval is how often stale entries are purged.
rateLimitCleanupInterval = 1 * time.Minute
)
// ──────────────────────────────────────────────────────────────────────────────
// distributedLimiter: Redis ZSET + local fallback
// ──────────────────────────────────────────────────────────────────────────────
// rateLimitScript is an atomic Lua script that implements a sliding-window rate
// limiter on a Redis Sorted Set. It prunes expired entries, checks the count,
// and conditionally adds a new member — all in a single round-trip.
//
// KEYS[1] = the rate-limit key
// ARGV[1] = now (Unix milliseconds)
// ARGV[2] = window size (milliseconds)
// ARGV[3] = max allowed requests
// ARGV[4] = unique member value (e.g. now_ms as string)
//
// Returns 1 if the request is allowed, 0 if rate-limited.
var rateLimitScript = redis.NewScript(`
local key = KEYS[1]
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local maxReq = tonumber(ARGV[3])
local member = ARGV[4]
redis.call('ZREMRANGEBYSCORE', key, 0, now - window)
local count = redis.call('ZCARD', key)
if count < maxReq then
redis.call('ZADD', key, now, member)
redis.call('PEXPIRE', key, window + 1000)
return 1
end
return 0
`)
// distributedLimiter tries Redis first, falls back to a local sliding-window
// limiter when Redis is unavailable (nil client or transient error).
type distributedLimiter struct {
redisClient *redis.Client
local *slidingWindowLimiter
window time.Duration
maxRequests int
instanceID string // used to disambiguate ZSET members across instances
}
func newDistributedLimiter(redisClient *redis.Client, window time.Duration, maxRequests int, instanceID string) *distributedLimiter {
return &distributedLimiter{
redisClient: redisClient,
local: newSlidingWindowLimiter(window, maxRequests),
window: window,
maxRequests: maxRequests,
instanceID: instanceID,
}
}
// Allow returns true if the request for the given key is within the rate limit.
func (d *distributedLimiter) Allow(key string) bool {
if d.redisClient != nil {
allowed, err := d.redisAllow(context.Background(), key)
if err == nil {
return allowed
}
// Redis failed — fall through to local limiter.
}
return d.local.Allow(key)
}
func (d *distributedLimiter) redisAllow(ctx context.Context, key string) (bool, error) {
redisKey := RedisKeyRateLimit + key
nowMs := time.Now().UnixMilli()
windowMs := d.window.Milliseconds()
member := fmt.Sprintf("%s:%d", d.instanceID, nowMs) // instanceID prevents ZSET member collision across instances
result, err := rateLimitScript.Run(ctx, d.redisClient,
[]string{redisKey},
nowMs, windowMs, d.maxRequests, member,
).Int64()
if err != nil {
return false, err
}
return result == 1, nil
}
// cleanupLoop delegates to the local limiter's cleanup for the fallback path.
func (d *distributedLimiter) cleanupLoop(stopCh <-chan struct{}) {
d.local.cleanupLoop(stopCh)
}
// ──────────────────────────────────────────────────────────────────────────────
// slidingWindowLimiter: local in-memory fallback (original implementation)
// ──────────────────────────────────────────────────────────────────────────────
// rateLimitEntry holds the request timestamps for a single key.
type rateLimitEntry struct {
mu sync.Mutex
timestamps []time.Time
deleted bool // marked true when removed from the map by cleanupLoop
}
// slidingWindowLimiter implements per-key sliding window rate limiting.
type slidingWindowLimiter struct {
window time.Duration
maxRequests int
entries sync.Map // key -> *rateLimitEntry
}
func newSlidingWindowLimiter(window time.Duration, maxRequests int) *slidingWindowLimiter {
return &slidingWindowLimiter{
window: window,
maxRequests: maxRequests,
}
}
// Allow checks if the request for the given key is within the rate limit.
// Returns true if allowed, false if rate limited.
func (l *slidingWindowLimiter) Allow(key string) bool {
now := time.Now()
cutoff := now.Add(-l.window)
for {
val, _ := l.entries.LoadOrStore(key, &rateLimitEntry{})
entry := val.(*rateLimitEntry)
entry.mu.Lock()
// If the entry was concurrently deleted by cleanupLoop, retry with a fresh one.
if entry.deleted {
entry.mu.Unlock()
l.entries.Delete(key) // ensure stale entry is gone
continue
}
// Remove expired timestamps
valid := entry.timestamps[:0]
for _, t := range entry.timestamps {
if t.After(cutoff) {
valid = append(valid, t)
}
}
entry.timestamps = valid
if len(entry.timestamps) >= l.maxRequests {
entry.mu.Unlock()
return false
}
entry.timestamps = append(entry.timestamps, now)
entry.mu.Unlock()
return true
}
}
// cleanupLoop periodically removes stale entries from the limiter.
func (l *slidingWindowLimiter) cleanupLoop(stopCh <-chan struct{}) {
ticker := time.NewTicker(rateLimitCleanupInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
cutoff := time.Now().Add(-l.window)
l.entries.Range(func(key, val interface{}) bool {
entry := val.(*rateLimitEntry)
entry.mu.Lock()
allExpired := true
for _, t := range entry.timestamps {
if t.After(cutoff) {
allExpired = false
break
}
}
if allExpired {
entry.deleted = true
l.entries.Delete(key)
}
entry.mu.Unlock()
return true
})
case <-stopCh:
return
}
}
}
+12 -6
View File
@@ -20,6 +20,7 @@ import (
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/ratelimit"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
@@ -305,6 +306,9 @@ const (
RedisKeyQueueUser = "im:queue:user:" // + userKey — global per-user queue counter
RedisKeyRateLimit = "im:ratelimit:" // + key — sliding-window rate limiting
RedisKeyGlobalGate = "im:global:active" // global concurrent worker counter
defaultRateLimitWindow = 60 * time.Second
defaultRateLimitMaxRequests = 10
)
// channelState holds runtime state for a running IM channel.
@@ -372,7 +376,8 @@ type Service struct {
// rateLimiter enforces per-user sliding window rate limiting.
// Uses Redis ZSET when available, falls back to local sliding window.
rateLimiter *distributedLimiter
rateLimiter *ratelimit.Limiter
rateLimitMax int
// inflight tracks in-progress QA requests, keyed by userKey
// ("channelID:userID:chatID"). Allows /stop to abort a running request
@@ -493,8 +498,8 @@ func resolveIMConfig(appCfg *config.Config) (workers, maxQueue, maxPerUser, glob
workers = defaultWorkers
maxQueue = defaultMaxQueueSize
maxPerUser = defaultMaxPerUser
rlWindow = rateLimitWindow
rlMax = rateLimitMaxRequests
rlWindow = defaultRateLimitWindow
rlMax = defaultRateLimitMaxRequests
if appCfg == nil || appCfg.IM == nil {
return
@@ -565,7 +570,8 @@ func NewService(
cmdRegistry: registry,
channels: make(map[string]*channelState),
adapterFactories: make(map[string]AdapterFactory),
rateLimiter: newDistributedLimiter(redisClient, rlWindow, rlMax, instanceID),
rateLimiter: ratelimit.New(redisClient, RedisKeyRateLimit, rlWindow, instanceID),
rateLimitMax: rlMax,
redis: redisClient,
instanceID: instanceID,
stopCh: make(chan struct{}),
@@ -581,7 +587,7 @@ func NewService(
if redisClient == nil {
go s.dedupCleanupLoop()
}
go s.rateLimiter.cleanupLoop(s.stopCh)
go s.rateLimiter.StartCleanup(s.stopCh)
if redisClient != nil {
globalInfo := "unlimited"
@@ -1070,7 +1076,7 @@ func (s *Service) HandleMessage(ctx context.Context, msg *IncomingMessage, chann
isCommand := s.cmdRegistry.IsRegistered(msg.Content)
if !isCommand {
rateLimitKey := makeUserKey(channelID, msg.UserID, msg.ChatID, threadID)
if !s.rateLimiter.Allow(rateLimitKey) {
if !s.rateLimiter.Allow(ctx, rateLimitKey, s.rateLimitMax) {
logger.Warnf(ctx, "[IM] Rate limited: channel=%s user=%s chat=%s", channelID, msg.UserID, msg.ChatID)
_ = adapter.SendReply(ctx, msg, &ReplyMessage{
Content: "您的消息发送过于频繁,请稍后再试。",