Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6247: rate limit workspace invitations (#7030)

Multica Eve0a1357498aa9
diff --git a/.env.example b/.env.example
index 5eb030d34b..efa93ad3ca 100644
--- a/.env.example
+++ b/.env.example
@@ -312,7 +312,7 @@ CORS_ALLOWED_ORIGINS=
# Per-IP fixed-window rate limiter on the public auth endpoints
# (/auth/send-code, /auth/verify-code, /auth/google). Backed by Redis.
# When REDIS_URL is unset the limiter is a no-op (fail-open) and the
-# backend logs "rate limiting disabled: REDIS_URL not configured" at
+# backend logs "auth rate limiting disabled: REDIS_URL not configured" at
# startup. The same REDIS_URL is reused by the realtime fan-out hub,
# the PAT cache, and the daemon-token cache.
# REDIS_URL=redis://localhost:6379/0
@@ -325,6 +325,14 @@ CORS_ALLOWED_ORIGINS=
# and 20 for verify-code.
# RATE_LIMIT_AUTH=5
# RATE_LIMIT_AUTH_VERIFY=20
+# Sliding-window budgets for workspace invitation creation. The actor gate is
+# per inviter, the workspace gate is shared by all admins in a workspace, and
+# the recipient gate is shared across workspaces using a SHA-256 email digest.
+# Without Redis these gates use process-local memory; with Redis their budgets
+# are shared across replicas. Set an individual value to 0 to disable that gate.
+# RATE_LIMIT_INVITATION_ACTOR_10M=10
+# RATE_LIMIT_INVITATION_WORKSPACE_24H=50
+# RATE_LIMIT_INVITATION_RECIPIENT_24H=6
# Comma-separated CIDRs whose X-Forwarded-For the auth limiter is
# allowed to trust. Empty (default) = never trust XFF, only RemoteAddr.
# REQUIRED behind a reverse proxy — otherwise every real user shares
diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdx
index b76acb9c89..6533f2cf3d 100644
--- a/apps/docs/content/docs/environment-variables.ja.mdx
+++ b/apps/docs/content/docs/environment-variables.ja.mdx
@@ -142,16 +142,19 @@ allowlist の正確な判定順序は[ログインとサインアップ](/auth-s
| 変数 | デフォルト | 説明 |
|---|---|---|
-| `REDIS_URL` | 空 | 認証レート制限、リアルタイムイベント、token cache に使用。未設定の場合、リアルタイムイベントはプロセス内メモリにフォールバックし、認証レート制限は無効になります |
+| `REDIS_URL` | 空 | 共有レート制限、リアルタイムイベント、token cache に使用。未設定の場合、リアルタイムイベントと招待制限はプロセス内メモリにフォールバックし、認証レート制限は無効になります |
| `REDIS_DISABLE_CLIENT_NAME` | `false` | マネージド Redis が `CLIENT SETNAME` を禁止している場合に `true` を設定 |
| `RATE_LIMIT_AUTH` | `5` | 認証コード送信または Google ログイン開始の、IP あたり毎分の回数 |
| `RATE_LIMIT_AUTH_VERIFY` | `20` | 認証コード検証の、IP あたり毎分の回数 |
+| `RATE_LIMIT_INVITATION_ACTOR_10M` | `10` | 招待者ごとの 10 分間スライディングウィンドウ内のワークスペース招待数。`0` でこの制限を無効化 |
+| `RATE_LIMIT_INVITATION_WORKSPACE_24H` | `50` | ワークスペース内の全管理者による 24 時間スライディングウィンドウ内の招待総数。`0` でこの制限を無効化 |
+| `RATE_LIMIT_INVITATION_RECIPIENT_24H` | `6` | 正規化された同一受信メールアドレスがワークスペースをまたいで 24 時間スライディングウィンドウ内に受け取れる招待数。`0` でこの制限を無効化 |
| `RATE_LIMIT_TRUSTED_PROXIES` | 空 | `X-Forwarded-For` の提供を許可するプロキシ CIDR。カンマ区切り |
| `MULTICA_TRUSTED_PROXIES` | 空 | オートパイロット webhook とリアルタイム接続が使う信頼済みプロキシ CIDR |
リバースプロキシ配下のデプロイでは、実際のプロキシのネットワーク範囲を設定してください。すべての送信元を無条件に信頼してはいけません。クライアントが転送元 IP を偽装できてしまいます。
-上記の `RATE_LIMIT_*` は `REDIS_URL` を設定した場合にのみ有効です。未設定の場合、起動ログに rate limiting disabled と表示されます。Redis が一時的に利用できないときは、レート制限はリクエストを通す側に倒れ、通常のログインを妨げません。
+認証レート制限には `REDIS_URL` が必要です。未設定の場合、起動ログに認証レート制限が無効であることが表示されます。招待制限は Redis なしでもプロセス内メモリで動作し、Redis を設定すると複数レプリカで割り当てを共有します。設定済みの Redis が一時的に利用できない場合、認証レート制限はフェイルオープンしますが、招待作成は保護なしでメールを送らず、再試行可能な `503` を返します。
## 外部連携
diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdx
index b96e59685c..437a881e63 100644
--- a/apps/docs/content/docs/environment-variables.ko.mdx
+++ b/apps/docs/content/docs/environment-variables.ko.mdx
@@ -142,16 +142,19 @@ allowlist의 정확한 판단 순서는 [로그인과 가입](/auth-setup#가입
| 변수 | 기본값 | 설명 |
|---|---|---|
-| `REDIS_URL` | 비어 있음 | 인증 rate limit, 실시간 이벤트, token cache에 사용. 설정하지 않으면 실시간 이벤트는 프로세스 메모리로 fallback하고 인증 rate limit은 비활성화 |
+| `REDIS_URL` | 비어 있음 | 공유 rate limit, 실시간 이벤트, token cache에 사용. 설정하지 않으면 실시간 이벤트와 초대 제한은 프로세스 메모리로 fallback하고 인증 rate limit은 비활성화 |
| `REDIS_DISABLE_CLIENT_NAME` | `false` | 관리형 Redis가 `CLIENT SETNAME`을 금지하면 `true`로 설정 |
| `RATE_LIMIT_AUTH` | `5` | IP당 1분에 인증 코드 전송 또는 Google 로그인 시작 허용 횟수 |
| `RATE_LIMIT_AUTH_VERIFY` | `20` | IP당 1분에 인증 코드 검증 허용 횟수 |
+| `RATE_LIMIT_INVITATION_ACTOR_10M` | `10` | 초대자별 10분 슬라이딩 윈도 내 워크스페이스 초대 생성 횟수. `0`이면 이 제한을 비활성화 |
+| `RATE_LIMIT_INVITATION_WORKSPACE_24H` | `50` | 워크스페이스의 모든 관리자가 24시간 슬라이딩 윈도 내 생성할 수 있는 총 초대 수. `0`이면 이 제한을 비활성화 |
+| `RATE_LIMIT_INVITATION_RECIPIENT_24H` | `6` | 정규화된 동일 수신 이메일이 워크스페이스 전체에서 24시간 슬라이딩 윈도 내 받을 수 있는 초대 수. `0`이면 이 제한을 비활성화 |
| `RATE_LIMIT_TRUSTED_PROXIES` | 비어 있음 | `X-Forwarded-For`를 제공하도록 허용할 proxy CIDR, 쉼표로 구분 |
| `MULTICA_TRUSTED_PROXIES` | 비어 있음 | 자동화 webhook과 실시간 연결에서 사용할 신뢰 proxy CIDR |
reverse proxy 뒤에 배포한다면 실제 proxy 네트워크를 입력해야 합니다. 모든 출처를 그대로 신뢰하지 마세요. 클라이언트가 전달 IP를 위조할 수 있습니다.
-위 `RATE_LIMIT_*` 변수는 `REDIS_URL`을 설정한 경우에만 작동합니다. 설정하지 않으면 시작 로그에 rate limiting disabled가 표시됩니다. Redis를 일시적으로 사용할 수 없을 때는 rate limit이 요청을 허용하는 쪽으로 동작해 정상 로그인을 차단하지 않습니다.
+인증 rate limit에는 `REDIS_URL`이 필요하며, 설정하지 않으면 시작 로그에 인증 rate limit이 비활성화되었다고 표시됩니다. 초대 제한은 Redis 없이도 프로세스 메모리에서 동작하고, Redis를 설정하면 여러 replica가 할당량을 공유합니다. 설정된 Redis를 일시적으로 사용할 수 없으면 인증 rate limit은 fail-open하지만, 초대 생성은 보호 없이 이메일을 보내지 않고 재시도 가능한 `503`을 반환합니다.
## 외부 연동
diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdx
index 33bb23da58..636d418348 100644
--- a/apps/docs/content/docs/environment-variables.mdx
+++ b/apps/docs/content/docs/environment-variables.mdx
@@ -142,16 +142,19 @@ Use `ATTACHMENT_DOWNLOAD_MODE=proxy` when the endpoint — an internal MinIO, fo
| Variable | Default | Description |
|---|---|---|
-| `REDIS_URL` | empty | Used for auth rate limiting, realtime events, and the token cache; when unset, realtime events fall back to in-process memory and auth rate limiting is off |
+| `REDIS_URL` | empty | Used for shared rate limiting, realtime events, and the token cache; when unset, realtime events and invitation limits fall back to in-process memory, while auth rate limiting is off |
| `REDIS_DISABLE_CLIENT_NAME` | `false` | Set `true` when a managed Redis blocks `CLIENT SETNAME` |
| `RATE_LIMIT_AUTH` | `5` | Per-IP requests per minute to send a verification code or start Google sign-in |
| `RATE_LIMIT_AUTH_VERIFY` | `20` | Per-IP code verifications per minute |
+| `RATE_LIMIT_INVITATION_ACTOR_10M` | `10` | Workspace invitations each inviter may create per 10-minute sliding window; `0` disables this gate |
+| `RATE_LIMIT_INVITATION_WORKSPACE_24H` | `50` | Workspace invitations all admins may create per workspace per 24-hour sliding window; `0` disables this gate |
+| `RATE_LIMIT_INVITATION_RECIPIENT_24H` | `6` | Invitations one normalized recipient email may receive across workspaces per 24-hour sliding window; `0` disables this gate |
| `RATE_LIMIT_TRUSTED_PROXIES` | empty | Comma-separated proxy CIDRs allowed to provide `X-Forwarded-For` |
| `MULTICA_TRUSTED_PROXIES` | empty | Trusted proxy CIDRs for automation webhooks and realtime connections |
Deployments behind a reverse proxy must list their real proxy ranges. Do not blanket-trust all sources, or clients can forge forwarded IPs.
-The `RATE_LIMIT_*` variables above only take effect once `REDIS_URL` is set; without it, the startup log notes that rate limiting is disabled. If Redis becomes temporarily unavailable, the limiter fails open and does not block normal sign-ins.
+The auth rate limits require `REDIS_URL`; without it, the startup log notes that auth rate limiting is disabled. Invitation limits still run in process-local memory without Redis and become shared across replicas when Redis is configured. If configured Redis becomes temporarily unavailable, auth rate limiting fails open, while invitation creation returns a retryable `503` instead of sending email without protection.
## External integrations
diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdx
index 311c1e9e9a..128bf5d1fe 100644
--- a/apps/docs/content/docs/environment-variables.zh.mdx
+++ b/apps/docs/content/docs/environment-variables.zh.mdx
@@ -142,16 +142,19 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
| 变量 | 默认值 | 说明 |
|---|---|---|
-| `REDIS_URL` | 空 | 用于认证限流、实时事件和 token cache;未设置时实时事件回退到进程内存,认证限流不生效 |
+| `REDIS_URL` | 空 | 用于共享限流、实时事件和 token cache;未设置时实时事件和邀请限流回退到进程内存,认证限流不生效 |
| `REDIS_DISABLE_CLIENT_NAME` | `false` | 托管 Redis 禁止 `CLIENT SETNAME` 时设为 `true` |
| `RATE_LIMIT_AUTH` | `5` | 单 IP 每分钟发送验证码或发起 Google 登录的次数 |
| `RATE_LIMIT_AUTH_VERIFY` | `20` | 单 IP 每分钟验证验证码的次数 |
+| `RATE_LIMIT_INVITATION_ACTOR_10M` | `10` | 每位邀请人在 10 分钟滑动窗口内可创建的工作区邀请数;设为 `0` 可关闭此项限流 |
+| `RATE_LIMIT_INVITATION_WORKSPACE_24H` | `50` | 同一工作区内所有管理员在 24 小时滑动窗口内可创建的邀请总数;设为 `0` 可关闭此项限流 |
+| `RATE_LIMIT_INVITATION_RECIPIENT_24H` | `6` | 同一规范化收件邮箱跨工作区在 24 小时滑动窗口内可收到的邀请数;设为 `0` 可关闭此项限流 |
| `RATE_LIMIT_TRUSTED_PROXIES` | 空 | 允许提供 `X-Forwarded-For` 的代理 CIDR,逗号分隔 |
| `MULTICA_TRUSTED_PROXIES` | 空 | 自动化 webhook 与实时连接使用的可信代理 CIDR |
反向代理后的部署需要填写真实代理网段。不要直接信任所有来源,否则客户端可以伪造转发 IP。
-上面的 `RATE_LIMIT_*` 只有在设置了 `REDIS_URL` 后才生效;未设置时启动日志会提示 rate limiting disabled。Redis 临时不可用时限流选择放行请求,不会阻断正常登录。
+认证限流需要配置 `REDIS_URL`;未配置时,启动日志会提示认证限流已关闭。邀请限流在没有 Redis 时仍使用进程内存,配置 Redis 后则在多个副本间共享额度。如果已配置的 Redis 临时不可用,认证限流仍选择放行,而邀请创建会返回可重试的 `503`,不会在失去防护时发送邮件。
## 外部集成
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index a229d2add6..6483771dfb 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -98,6 +98,19 @@ func envPositiveInt(name string, def int) int {
return v
}
+func envNonNegativeInt(name string, def int) int {
+ raw := os.Getenv(name)
+ if raw == "" {
+ return def
+ }
+ v, err := strconv.Atoi(raw)
+ if err != nil || v < 0 {
+ slog.Warn("invalid env var, using default", "name", name, "value", raw, "default", def, "error", err)
+ return def
+ }
+ return v
+}
+
func envPositiveInt64(name string, def int64) int64 {
raw := os.Getenv(name)
if raw == "" {
diff --git a/server/cmd/server/main_test.go b/server/cmd/server/main_test.go
index 540b549f1f..9d5908d740 100644
--- a/server/cmd/server/main_test.go
+++ b/server/cmd/server/main_test.go
@@ -331,6 +331,35 @@ func TestEnvNonNegativeDuration(t *testing.T) {
}
}
+func TestEnvNonNegativeInt(t *testing.T) {
+ tests := []struct {
+ name string
+ value string
+ def int
+ want int
+ }{
+ {name: "unset returns default", def: 10, want: 10},
+ {name: "zero disables gate", value: "0", def: 10, want: 0},
+ {name: "positive override", value: "25", def: 10, want: 25},
+ {name: "invalid returns default", value: "many", def: 10, want: 10},
+ {name: "negative returns default", value: "-1", def: 10, want: 10},
+ }
+
+ for i, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ key := "TEST_NON_NEGATIVE_INT_" + strconv.Itoa(i)
+ if tt.name == "unset returns default" {
+ os.Unsetenv(key)
+ } else {
+ t.Setenv(key, tt.value)
+ }
+ if got := envNonNegativeInt(key, tt.def); got != tt.want {
+ t.Fatalf("envNonNegativeInt(%q, %d) = %d, want %d", key, tt.def, got, tt.want)
+ }
+ })
+ }
+}
+
func TestHoldBeforeShutdown(t *testing.T) {
const hold = 10 * time.Millisecond
started := time.Now()
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 329fc31959..339f3d2572 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -237,6 +237,11 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
ServerVersion: normalizeServerVersion(version),
}
h := handler.New(queries, pool, hub, bus, emailSvc, store, cfSigner, analyticsClient, signupConfig, daemonHub)
+ invitationRateLimits := handler.DefaultInvitationRateLimits()
+ invitationRateLimits.Actor.Limit = envNonNegativeInt("RATE_LIMIT_INVITATION_ACTOR_10M", invitationRateLimits.Actor.Limit)
+ invitationRateLimits.Workspace.Limit = envNonNegativeInt("RATE_LIMIT_INVITATION_WORKSPACE_24H", invitationRateLimits.Workspace.Limit)
+ invitationRateLimits.Recipient.Limit = envNonNegativeInt("RATE_LIMIT_INVITATION_RECIPIENT_24H", invitationRateLimits.Recipient.Limit)
+ h.InvitationRateLimiters = handler.NewMemoryInvitationRateLimiters(invitationRateLimits)
h.Metrics = opts.BusinessMetrics
h.FeatureFlags = opts.FeatureFlags
h.TaskService.FeatureFlags = opts.FeatureFlags
@@ -272,6 +277,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
h.WebhookRateLimiter = handler.NewRedisWebhookRateLimiter(rdb, handler.DefaultWebhookRateLimit())
h.WebhookIPRateLimiter = handler.NewRedisWebhookIPRateLimiter(rdb, handler.DefaultWebhookIPRateLimit())
h.WebhookAbsoluteIPRateLimiter = handler.NewRedisWebhookAbsoluteIPRateLimiter(rdb, handler.DefaultWebhookAbsoluteIPRateLimit())
+ h.InvitationRateLimiters = handler.NewRedisInvitationRateLimiters(rdb, invitationRateLimits)
}
// Channel engine (MUL-3620): the platform-agnostic inbound runtime.
@@ -1021,7 +1027,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// Auth (public) — per-IP rate limiting.
if rdb == nil {
- slog.Warn("rate limiting disabled: REDIS_URL not configured")
+ slog.Warn("auth rate limiting disabled: REDIS_URL not configured")
}
trustedProxies := middleware.ParseTrustedProxies(os.Getenv("RATE_LIMIT_TRUSTED_PROXIES"))
authRL := middleware.RateLimit(rdb, envPositiveInt("RATE_LIMIT_AUTH", 5), time.Minute, trustedProxies)
diff --git a/server/internal/handler/autopilot_webhook.go b/server/internal/handler/autopilot_webhook.go
index 2426984a9d..ae87ac6aef 100644
--- a/server/internal/handler/autopilot_webhook.go
+++ b/server/internal/handler/autopilot_webhook.go
@@ -357,7 +357,7 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
writeWebhookRateLimit(w, r, h.WebhookAbsoluteIPRateLimiter, ip, "absolute_ip", h.Metrics)
return
}
- if ip != "" && h.WebhookIPRateLimiter != nil && !webhookLimiterCheck(r.Context(), h.WebhookIPRateLimiter, ip) {
+ if ip != "" && h.WebhookIPRateLimiter != nil && !slidingWindowLimiterCheck(r.Context(), h.WebhookIPRateLimiter, ip) {
writeWebhookRateLimit(w, r, h.WebhookIPRateLimiter, ip, "bad_credential_ip", h.Metrics)
return
}
@@ -914,7 +914,7 @@ func (h *Handler) deliveryProvider(ctx context.Context, id pgtype.UUID) string {
func writeWebhookRateLimit(w http.ResponseWriter, r *http.Request, limiter WebhookRateLimiter, key, gate string, metrics *obsmetrics.BusinessMetrics) {
retryAfter := time.Second
if limiter != nil {
- if retry := webhookLimiterRetryAfter(r.Context(), limiter, key); retry > 0 {
+ if retry := slidingWindowLimiterRetryAfter(r.Context(), limiter, key); retry > 0 {
retryAfter = retry
}
}
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 2059379c97..7523db16d8 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -198,6 +198,7 @@ type Handler struct {
WebhookRateLimiter WebhookRateLimiter
WebhookIPRateLimiter WebhookRateLimiter
WebhookAbsoluteIPRateLimiter WebhookRateLimiter
+ InvitationRateLimiters InvitationRateLimiters
WebhookDeliveryWorker *WebhookDeliveryWorker
CloudRuntime cloudRuntimeProxy
// Lark integration. All three are nil when the Lark master key
@@ -403,6 +404,7 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *event
WebhookRateLimiter: NewMemoryWebhookRateLimiter(DefaultWebhookRateLimit()),
WebhookIPRateLimiter: NewMemoryWebhookIPRateLimiter(DefaultWebhookIPRateLimit()),
WebhookAbsoluteIPRateLimiter: NewMemoryWebhookAbsoluteIPRateLimiter(DefaultWebhookAbsoluteIPRateLimit()),
+ InvitationRateLimiters: NewMemoryInvitationRateLimiters(DefaultInvitationRateLimits()),
CloudRuntime: cloudruntime.NewClient(cloudruntime.Config{
BaseURL: cfg.CloudRuntimeFleetURL,
Timeout: cfg.CloudRuntimeFleetTimeout,
diff --git a/server/internal/handler/handler_test.go b/server/internal/handler/handler_test.go
index bf4d68f5f4..b7d37c88f3 100644
--- a/server/internal/handler/handler_test.go
+++ b/server/internal/handler/handler_test.go
@@ -69,6 +69,11 @@ func TestMain(m *testing.M) {
testHandler.WebhookRateLimiter = NewMemoryWebhookRateLimiter(WebhookRateLimit{Limit: 1_000_000, Window: time.Minute})
testHandler.WebhookIPRateLimiter = NewMemoryWebhookIPRateLimiter(WebhookRateLimit{Limit: 1_000_000, Window: time.Minute})
testHandler.WebhookAbsoluteIPRateLimiter = NewMemoryWebhookAbsoluteIPRateLimiter(WebhookRateLimit{Limit: 1_000_000, Window: time.Minute})
+ testHandler.InvitationRateLimiters = NewMemoryInvitationRateLimiters(InvitationRateLimits{
+ Actor: SlidingWindowRateLimit{Limit: 1_000_000, Window: time.Minute},
+ Workspace: SlidingWindowRateLimit{Limit: 1_000_000, Window: time.Minute},
+ Recipient: SlidingWindowRateLimit{Limit: 1_000_000, Window: time.Minute},
+ })
testPool = pool
testUserID, testWorkspaceID, err = setupHandlerTestFixture(ctx, pool)
diff --git a/server/internal/handler/invitation.go b/server/internal/handler/invitation.go
index abe7832167..db9c1d32a2 100644
--- a/server/internal/handler/invitation.go
+++ b/server/internal/handler/invitation.go
@@ -118,6 +118,18 @@ func (h *Handler) CreateInvitation(w http.ResponseWriter, r *http.Request) {
return
}
+ // Consume every applicable budget only after validation and idempotency
+ // checks, but before the invitation row or email side effect is created.
+ if !h.admitInvitation(
+ w,
+ r,
+ uuidToString(requester.UserID),
+ uuidToString(requester.WorkspaceID),
+ email,
+ ) {
+ return
+ }
+
// Resolve invitee_user_id if the user already exists.
var inviteeUserID pgtype.UUID
if existingUser.ID.Valid {
diff --git a/server/internal/handler/invitation_rate_limiter.go b/server/internal/handler/invitation_rate_limiter.go
new file mode 100644
index 0000000000..bfaddaa083
--- /dev/null
+++ b/server/internal/handler/invitation_rate_limiter.go
@@ -0,0 +1,158 @@
+package handler
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "log/slog"
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/logger"
+ "github.com/redis/go-redis/v9"
+)
+
+const (
+ invitationActorLimiterKeyPrefix = "mul:invitation:actor:"
+ invitationWorkspaceLimiterKeyPrefix = "mul:invitation:workspace:"
+ invitationRecipientLimiterKeyPrefix = "mul:invitation:recipient:"
+)
+
+// InvitationRateLimits configures the independent invitation admission gates.
+type InvitationRateLimits struct {
+ Actor SlidingWindowRateLimit
+ Workspace SlidingWindowRateLimit
+ Recipient SlidingWindowRateLimit
+}
+
+// DefaultInvitationRateLimits returns conservative email-abuse budgets.
+func DefaultInvitationRateLimits() InvitationRateLimits {
+ return InvitationRateLimits{
+ Actor: SlidingWindowRateLimit{Limit: 10, Window: 10 * time.Minute},
+ Workspace: SlidingWindowRateLimit{Limit: 50, Window: 24 * time.Hour},
+ Recipient: SlidingWindowRateLimit{Limit: 6, Window: 24 * time.Hour},
+ }
+}
+
+// InvitationRateLimiters holds the independently keyed gate implementations.
+type InvitationRateLimiters struct {
+ Actor SlidingWindowRateLimiter
+ Workspace SlidingWindowRateLimiter
+ Recipient SlidingWindowRateLimiter
+}
+
+// NewMemoryInvitationRateLimiters builds single-process gates for local and
+// Redis-less deployments.
+func NewMemoryInvitationRateLimiters(limits InvitationRateLimits) InvitationRateLimiters {
+ return InvitationRateLimiters{
+ Actor: newMemorySlidingWindowRateLimiter(limits.Actor),
+ Workspace: newMemorySlidingWindowRateLimiter(limits.Workspace),
+ Recipient: newMemorySlidingWindowRateLimiter(limits.Recipient),
+ }
+}
+
+// NewRedisInvitationRateLimiters builds replica-shared gates with isolated key
+// namespaces for each dimension.
+func NewRedisInvitationRateLimiters(rdb *redis.Client, limits InvitationRateLimits) InvitationRateLimiters {
+ return InvitationRateLimiters{
+ Actor: newRedisSlidingWindowRateLimiter(rdb, limits.Actor, invitationActorLimiterKeyPrefix),
+ Workspace: newRedisSlidingWindowRateLimiter(rdb, limits.Workspace, invitationWorkspaceLimiterKeyPrefix),
+ Recipient: newRedisSlidingWindowRateLimiter(rdb, limits.Recipient, invitationRecipientLimiterKeyPrefix),
+ }
+}
+
+type invitationRateLimitGate struct {
+ name string
+ key string
+ limiter SlidingWindowRateLimiter
+}
+
+func invitationRecipientKey(email string) string {
+ normalized := strings.ToLower(strings.TrimSpace(email))
+ digest := sha256.Sum256([]byte(normalized))
+ return hex.EncodeToString(digest[:])
+}
+
+func (h *Handler) admitInvitation(w http.ResponseWriter, r *http.Request, actorID, workspaceID, email string) bool {
+ gates := []invitationRateLimitGate{
+ {name: "actor", key: actorID, limiter: h.InvitationRateLimiters.Actor},
+ {name: "workspace", key: workspaceID, limiter: h.InvitationRateLimiters.Workspace},
+ {name: "recipient", key: invitationRecipientKey(email), limiter: h.InvitationRateLimiters.Recipient},
+ }
+
+ var checkErr error
+ var checkErrorGates []string
+ var deniedGates []invitationRateLimitGate
+ var retryAfter time.Duration
+ for _, gate := range gates {
+ allowed, err := slidingWindowLimiterCheckWithError(r.Context(), gate.limiter, gate.key)
+ if err != nil {
+ if checkErr == nil {
+ checkErr = err
+ }
+ checkErrorGates = append(checkErrorGates, gate.name)
+ continue
+ }
+ if allowed {
+ continue
+ }
+
+ deniedGates = append(deniedGates, gate)
+ if retry := slidingWindowLimiterRetryAfter(r.Context(), gate.limiter, gate.key); retry > retryAfter {
+ retryAfter = retry
+ }
+ }
+
+ if checkErr != nil {
+ slog.Error("invitation rate limiter unavailable", append(logger.RequestAttrs(r), "gates", strings.Join(checkErrorGates, ","), "error", checkErr)...)
+ writeInvitationLimiterUnavailable(w)
+ return false
+ }
+ if len(deniedGates) > 0 {
+ for _, gate := range deniedGates {
+ h.Metrics.RecordEmailRateLimited("workspace_invitation", gate.name)
+ }
+ writeInvitationRateLimited(w, retryAfter)
+ return false
+ }
+
+ for _, gate := range gates {
+ allowed, err := slidingWindowLimiterAllow(r.Context(), gate.limiter, gate.key)
+ if err != nil {
+ // All gates passed the non-consuming checks, so this failure began in
+ // the narrow Check-to-Allow window. Admit this in-flight request rather
+ // than return an error after an earlier gate may have consumed. A
+ // sustained backend failure is caught by Phase 1 on later requests.
+ slog.Warn("invitation rate limiter consume failed after successful checks; allowing bounded overshoot", append(logger.RequestAttrs(r), "gate", gate.name, "error", err)...)
+ continue
+ }
+ if !allowed {
+ // Another replica filled this gate between Check and Allow. Continue
+ // instead of rejecting after earlier gates may already have consumed;
+ // this permits only a bounded overshoot of a safety budget.
+ continue
+ }
+ }
+ return true
+}
+
+func writeInvitationLimiterUnavailable(w http.ResponseWriter) {
+ w.Header().Set("Cache-Control", "no-store")
+ w.Header().Set("Retry-After", "5")
+ writeErrorCode(w, http.StatusServiceUnavailable, "invitation_rate_limiter_unavailable", "invitation service temporarily unavailable")
+}
+
+func writeInvitationRateLimited(w http.ResponseWriter, retryAfter time.Duration) {
+ retryAfterSeconds := int64((retryAfter + time.Second - 1) / time.Second)
+ if retryAfterSeconds < 1 {
+ retryAfterSeconds = 1
+ }
+ w.Header().Set("Cache-Control", "no-store")
+ w.Header().Set("Retry-After", strconv.FormatInt(retryAfterSeconds, 10))
+ writeJSON(w, http.StatusTooManyRequests, map[string]any{
+ "error": "too many invitation requests",
+ "code": "invitation_rate_limited",
+ "retry_after_seconds": retryAfterSeconds,
+ })
+}
diff --git a/server/internal/handler/invitation_test.go b/server/internal/handler/invitation_test.go
index efcb33429e..ee2e4a1153 100644
--- a/server/internal/handler/invitation_test.go
+++ b/server/internal/handler/invitation_test.go
@@ -1,15 +1,78 @@
package handler
import (
+ "bytes"
"context"
"encoding/json"
+ "errors"
+ "fmt"
"net/http"
"net/http/httptest"
+ "strings"
"testing"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
+ "github.com/multica-ai/multica/server/internal/middleware"
)
const invitationTestEmail = "[email protected]"
+func TestDefaultInvitationRateLimits(t *testing.T) {
+ limits := DefaultInvitationRateLimits()
+ want := SlidingWindowRateLimit{Limit: 6, Window: 24 * time.Hour}
+ if limits.Recipient != want {
+ t.Fatalf("recipient limit = %+v, want %+v", limits.Recipient, want)
+ }
+}
+
+type stubInvitationRateLimiter struct {
+ allowed bool
+ allowResult *bool
+ err error
+ allowErr error
+ retryAfter time.Duration
+ checkKeys []string
+ allowKeys []string
+}
+
+func (l *stubInvitationRateLimiter) Allow(ctx context.Context, key string) bool {
+ allowed, _ := l.AllowWithError(ctx, key)
+ return allowed
+}
+
+func (l *stubInvitationRateLimiter) AllowWithError(_ context.Context, key string) (bool, error) {
+ l.allowKeys = append(l.allowKeys, key)
+ if l.allowResult != nil {
+ return *l.allowResult, l.allowErr
+ }
+ return l.allowed, l.allowErr
+}
+
+func (l *stubInvitationRateLimiter) Check(ctx context.Context, key string) bool {
+ allowed, _ := l.CheckWithError(ctx, key)
+ return allowed
+}
+
+func (l *stubInvitationRateLimiter) CheckWithError(_ context.Context, key string) (bool, error) {
+ l.checkKeys = append(l.checkKeys, key)
+ return l.allowed, l.err
+}
+
+func (l *stubInvitationRateLimiter) RetryAfter(_ context.Context, _ string) time.Duration {
+ return l.retryAfter
+}
+
+func useInvitationRateLimiters(t *testing.T, limiters InvitationRateLimiters) {
+ t.Helper()
+ previous := testHandler.InvitationRateLimiters
+ testHandler.InvitationRateLimiters = limiters
+ t.Cleanup(func() {
+ testHandler.InvitationRateLimiters = previous
+ })
+}
+
func clearInvitationsForTestWorkspace(t *testing.T) {
t.Helper()
ctx := context.Background()
@@ -30,6 +93,10 @@ func clearInvitationsForTestWorkspace(t *testing.T) {
// Sanity check: a fresh, live pending invitation must block re-invitation.
func TestCreateInvitation_BlocksWhilePending(t *testing.T) {
clearInvitationsForTestWorkspace(t)
+ actor := &stubInvitationRateLimiter{allowed: true}
+ workspace := &stubInvitationRateLimiter{allowed: true}
+ recipient := &stubInvitationRateLimiter{allowed: true}
+ useInvitationRateLimiters(t, InvitationRateLimiters{Actor: actor, Workspace: workspace, Recipient: recipient})
req := newRequest("POST", "/api/workspaces/"+testWorkspaceID+"/members", CreateMemberRequest{
Email: invitationTestEmail,
@@ -52,6 +119,14 @@ func TestCreateInvitation_BlocksWhilePending(t *testing.T) {
if w2.Code != http.StatusConflict {
t.Fatalf("second invite: expected 409 while still pending, got %d: %s", w2.Code, w2.Body.String())
}
+ for name, calls := range map[string]int{
+ "actor checks": len(actor.checkKeys), "workspace checks": len(workspace.checkKeys), "recipient checks": len(recipient.checkKeys),
+ "actor allows": len(actor.allowKeys), "workspace allows": len(workspace.allowKeys), "recipient allows": len(recipient.allowKeys),
+ } {
+ if calls != 1 {
+ t.Errorf("%s limiter calls = %d, want 1; a pending retry must not consume budget", name, calls)
+ }
+ }
}
// Regression for issue #2055: an expired pending invitation must NOT block a
@@ -112,3 +187,290 @@ func TestCreateInvitation_AllowsAfterExpiry(t *testing.T) {
t.Fatalf("expected exactly 1 pending invitation after re-invite, got %d", pendingCount)
}
}
+
+func TestCreateInvitation_RateLimitChecksEveryGateBeforeWrite(t *testing.T) {
+ clearInvitationsForTestWorkspace(t)
+ actor := &stubInvitationRateLimiter{allowed: false, retryAfter: 10 * time.Minute}
+ workspace := &stubInvitationRateLimiter{allowed: true}
+ recipient := &stubInvitationRateLimiter{allowed: false, retryAfter: 24 * time.Hour}
+ useInvitationRateLimiters(t, InvitationRateLimiters{Actor: actor, Workspace: workspace, Recipient: recipient})
+
+ const rawEmail = " [email protected] "
+ req := newRequest(http.MethodPost, "/api/workspaces/"+testWorkspaceID+"/members", CreateMemberRequest{
+ Email: rawEmail,
+ Role: "member",
+ })
+ req = withURLParam(req, "id", testWorkspaceID)
+ rec := httptest.NewRecorder()
+ testHandler.CreateInvitation(rec, req)
+
+ if rec.Code != http.StatusTooManyRequests {
+ t.Fatalf("status = %d, want 429: %s", rec.Code, rec.Body.String())
+ }
+ if got := rec.Header().Get("Retry-After"); got != "86400" {
+ t.Errorf("Retry-After = %q, want 86400", got)
+ }
+ if got := rec.Header().Get("Cache-Control"); got != "no-store" {
+ t.Errorf("Cache-Control = %q, want no-store", got)
+ }
+ var body struct {
+ Error string `json:"error"`
+ Code string `json:"code"`
+ RetryAfterSeconds int64 `json:"retry_after_seconds"`
+ }
+ if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if body.Error != "too many invitation requests" || body.Code != "invitation_rate_limited" || body.RetryAfterSeconds != 86400 {
+ t.Errorf("unexpected body: %+v", body)
+ }
+ if strings.Contains(rec.Body.String(), "actor") || strings.Contains(rec.Body.String(), "workspace") || strings.Contains(rec.Body.String(), "recipient") {
+ t.Errorf("response leaked the limiting gate: %s", rec.Body.String())
+ }
+
+ normalizedEmail := strings.ToLower(strings.TrimSpace(rawEmail))
+ checks := []struct {
+ name string
+ got []string
+ want string
+ }{
+ {name: "actor", got: actor.checkKeys, want: testUserID},
+ {name: "workspace", got: workspace.checkKeys, want: testWorkspaceID},
+ {name: "recipient", got: recipient.checkKeys, want: invitationRecipientKey(normalizedEmail)},
+ }
+ for _, check := range checks {
+ if len(check.got) != 1 || check.got[0] != check.want {
+ t.Errorf("%s limiter keys = %v, want [%s]", check.name, check.got, check.want)
+ }
+ }
+ if len(recipient.checkKeys) == 1 && (recipient.checkKeys[0] == normalizedEmail || strings.Contains(recipient.checkKeys[0], "@")) {
+ t.Errorf("recipient limiter key contains the email instead of a digest: %q", recipient.checkKeys[0])
+ }
+ for name, calls := range map[string]int{
+ "actor": len(actor.allowKeys), "workspace": len(workspace.allowKeys), "recipient": len(recipient.allowKeys),
+ } {
+ if calls != 0 {
+ t.Errorf("%s limiter consumed %d times, want 0 after a rejected check", name, calls)
+ }
+ }
+
+ var pendingCount int
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT COUNT(*) FROM workspace_invitation
+ WHERE workspace_id = $1 AND invitee_email = $2 AND status = 'pending'
+ `, parseUUID(testWorkspaceID), normalizedEmail).Scan(&pendingCount); err != nil {
+ t.Fatalf("count pending invitations: %v", err)
+ }
+ if pendingCount != 0 {
+ t.Fatalf("pending invitation count = %d, want 0 after rate limit rejection", pendingCount)
+ }
+}
+
+func TestCreateInvitation_RateLimiterFailureReturnsServiceUnavailable(t *testing.T) {
+ clearInvitationsForTestWorkspace(t)
+ actor := &stubInvitationRateLimiter{allowed: false, retryAfter: 10 * time.Minute}
+ workspace := &stubInvitationRateLimiter{allowed: true, err: errors.New("redis unavailable")}
+ recipient := &stubInvitationRateLimiter{allowed: true}
+ useInvitationRateLimiters(t, InvitationRateLimiters{Actor: actor, Workspace: workspace, Recipient: recipient})
+ previousMetrics := testHandler.Metrics
+ testHandler.Metrics = obsmetrics.NewBusinessMetrics()
+ t.Cleanup(func() {
+ testHandler.Metrics = previousMetrics
+ })
+
+ req := newRequest(http.MethodPost, "/api/workspaces/"+testWorkspaceID+"/members", CreateMemberRequest{
+ Email: "[email protected]",
+ Role: "member",
+ })
+ req = withURLParam(req, "id", testWorkspaceID)
+ rec := httptest.NewRecorder()
+ testHandler.CreateInvitation(rec, req)
+
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Fatalf("status = %d, want 503: %s", rec.Code, rec.Body.String())
+ }
+ if rec.Header().Get("Retry-After") != "5" || rec.Header().Get("Cache-Control") != "no-store" {
+ t.Errorf("unexpected retry/cache headers: %v", rec.Header())
+ }
+ var body map[string]string
+ if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if body["code"] != "invitation_rate_limiter_unavailable" {
+ t.Errorf("code = %q, want invitation_rate_limiter_unavailable", body["code"])
+ }
+ metricFamily := obsmetrics.GatherForTest(t, testHandler.Metrics)["multica_email_rate_limited_total"]
+ for _, metric := range metricFamily.GetMetric() {
+ if metric.GetCounter().GetValue() != 0 {
+ t.Errorf("rate-limit metric = %v, want 0 when the final response is 503", metric.GetCounter().GetValue())
+ }
+ }
+ for name, calls := range map[string]int{
+ "actor checks": len(actor.checkKeys), "workspace checks": len(workspace.checkKeys), "recipient checks": len(recipient.checkKeys),
+ } {
+ if calls != 1 {
+ t.Errorf("%s = %d, want 1 even when another gate errors", name, calls)
+ }
+ }
+ for name, calls := range map[string]int{
+ "actor": len(actor.allowKeys), "workspace": len(workspace.allowKeys), "recipient": len(recipient.allowKeys),
+ } {
+ if calls != 0 {
+ t.Errorf("%s limiter consumed %d times, want 0 after a backend error", name, calls)
+ }
+ }
+ var pendingCount int
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT COUNT(*) FROM workspace_invitation
+ WHERE workspace_id = $1 AND invitee_email = '[email protected]' AND status = 'pending'
+ `, parseUUID(testWorkspaceID)).Scan(&pendingCount); err != nil {
+ t.Fatalf("count pending invitations: %v", err)
+ }
+ if pendingCount != 0 {
+ t.Fatalf("pending invitation count = %d, want 0 after limiter backend failure", pendingCount)
+ }
+}
+
+func TestAdmitInvitation_RejectedActorDoesNotConsumeWorkspaceBudget(t *testing.T) {
+ limits := InvitationRateLimits{
+ Actor: SlidingWindowRateLimit{Limit: 1, Window: time.Hour},
+ Workspace: SlidingWindowRateLimit{Limit: 2, Window: time.Hour},
+ Recipient: SlidingWindowRateLimit{Limit: 10, Window: time.Hour},
+ }
+ h := *testHandler
+ h.InvitationRateLimiters = NewMemoryInvitationRateLimiters(limits)
+
+ admit := func(actorID, email string) bool {
+ req := httptest.NewRequest(http.MethodPost, "/api/workspaces/workspace-a/members", nil)
+ return h.admitInvitation(httptest.NewRecorder(), req, actorID, "workspace-a", email)
+ }
+
+ if !admit("actor-a", "[email protected]") {
+ t.Fatal("first invitation was unexpectedly rejected")
+ }
+ for i := 0; i < 3; i++ {
+ if admit("actor-a", fmt.Sprintf("rejected-%[email protected]", i)) {
+ t.Fatalf("actor-limited invitation %d was unexpectedly admitted", i)
+ }
+ }
+ if !admit("actor-b", "[email protected]") {
+ t.Fatal("actor-limited retries consumed the shared workspace budget")
+ }
+}
+
+func TestAdmitInvitation_RejectedActorDoesNotConsumeRecipientBudget(t *testing.T) {
+ limits := InvitationRateLimits{
+ Actor: SlidingWindowRateLimit{Limit: 1, Window: time.Hour},
+ Workspace: SlidingWindowRateLimit{Limit: 10, Window: time.Hour},
+ Recipient: SlidingWindowRateLimit{Limit: 2, Window: time.Hour},
+ }
+ h := *testHandler
+ h.InvitationRateLimiters = NewMemoryInvitationRateLimiters(limits)
+
+ admit := func(actorID, workspaceID string) bool {
+ req := httptest.NewRequest(http.MethodPost, "/api/workspaces/"+workspaceID+"/members", nil)
+ return h.admitInvitation(httptest.NewRecorder(), req, actorID, workspaceID, "[email protected]")
+ }
+
+ if !admit("actor-a", "workspace-a") {
+ t.Fatal("first invitation was unexpectedly rejected")
+ }
+ if admit("actor-a", "workspace-a") {
+ t.Fatal("actor-limited retry was unexpectedly admitted")
+ }
+ if !admit("actor-b", "workspace-b") {
+ t.Fatal("actor-limited retry consumed the global recipient budget")
+ }
+}
+
+func TestAdmitInvitation_AllowsBoundedOvershootWhenGateFillsAfterCheck(t *testing.T) {
+ allowDenied := false
+ actor := &stubInvitationRateLimiter{allowed: true, allowResult: &allowDenied}
+ workspace := &stubInvitationRateLimiter{allowed: true}
+ recipient := &stubInvitationRateLimiter{allowed: true}
+ h := *testHandler
+ h.InvitationRateLimiters = InvitationRateLimiters{Actor: actor, Workspace: workspace, Recipient: recipient}
+
+ req := httptest.NewRequest(http.MethodPost, "/api/workspaces/workspace-a/members", nil)
+ if !h.admitInvitation(httptest.NewRecorder(), req, "actor-a", "workspace-a", "[email protected]") {
+ t.Fatal("concurrent fill rejected after a different gate may already have consumed")
+ }
+ for name, calls := range map[string]int{
+ "actor checks": len(actor.checkKeys), "workspace checks": len(workspace.checkKeys), "recipient checks": len(recipient.checkKeys),
+ "actor allows": len(actor.allowKeys), "workspace allows": len(workspace.allowKeys), "recipient allows": len(recipient.allowKeys),
+ } {
+ if calls != 1 {
+ t.Errorf("%s = %d, want 1", name, calls)
+ }
+ }
+}
+
+func TestAdmitInvitation_AllowsBoundedOvershootWhenBackendFailsAfterChecks(t *testing.T) {
+ actor := &stubInvitationRateLimiter{allowed: true}
+ workspace := &stubInvitationRateLimiter{allowed: true, allowErr: errors.New("redis unavailable")}
+ recipient := &stubInvitationRateLimiter{allowed: true}
+ h := *testHandler
+ h.InvitationRateLimiters = InvitationRateLimiters{Actor: actor, Workspace: workspace, Recipient: recipient}
+
+ req := httptest.NewRequest(http.MethodPost, "/api/workspaces/workspace-a/members", nil)
+ rec := httptest.NewRecorder()
+ if !h.admitInvitation(rec, req, "actor-a", "workspace-a", "[email protected]") {
+ t.Fatalf("backend failed after successful checks: request was rejected with %d: %s", rec.Code, rec.Body.String())
+ }
+ if rec.Body.Len() != 0 || rec.Header().Get("Retry-After") != "" {
+ t.Fatalf("backend failure after checks wrote an error response: headers=%v body=%s", rec.Header(), rec.Body.String())
+ }
+ for name, calls := range map[string]int{
+ "actor checks": len(actor.checkKeys), "workspace checks": len(workspace.checkKeys), "recipient checks": len(recipient.checkKeys),
+ "actor allows": len(actor.allowKeys), "workspace allows": len(workspace.allowKeys), "recipient allows": len(recipient.allowKeys),
+ } {
+ if calls != 1 {
+ t.Errorf("%s = %d, want 1", name, calls)
+ }
+ }
+}
+
+func TestCreateInvitation_RouteRequiresAdminRole(t *testing.T) {
+ clearInvitationsForTestWorkspace(t)
+ ctx := context.Background()
+ const memberEmail = "[email protected]"
+ _, _ = testPool.Exec(ctx, `DELETE FROM "user" WHERE email = $1`, memberEmail)
+ var memberUserID string
+ if err := testPool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ('Invitation Route Member', $1) RETURNING id`, memberEmail).Scan(&memberUserID); err != nil {
+ t.Fatalf("create member user: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')`, testWorkspaceID, memberUserID); err != nil {
+ t.Fatalf("create member: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM member WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, memberUserID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, memberUserID)
+ })
+
+ router := chi.NewRouter()
+ router.Route("/api/workspaces/{id}", func(r chi.Router) {
+ r.Group(func(r chi.Router) {
+ r.Use(middleware.RequireWorkspaceRoleFromURL(testHandler.Queries, "id", "owner", "admin"))
+ r.Post("/members", testHandler.CreateInvitation)
+ })
+ })
+
+ call := func(userID, inviteeEmail string) *httptest.ResponseRecorder {
+ var body bytes.Buffer
+ if err := json.NewEncoder(&body).Encode(CreateMemberRequest{Email: inviteeEmail, Role: "member"}); err != nil {
+ t.Fatal(err)
+ }
+ req := httptest.NewRequest(http.MethodPost, "/api/workspaces/"+testWorkspaceID+"/members", &body)
+ req.Header.Set("X-User-ID", userID)
+ rec := httptest.NewRecorder()
+ router.ServeHTTP(rec, req)
+ return rec
+ }
+
+ if rec := call(memberUserID, "[email protected]"); rec.Code != http.StatusForbidden {
+ t.Errorf("member status = %d, want 403: %s", rec.Code, rec.Body.String())
+ }
+ if rec := call(testUserID, fmt.Sprintf("invitation-route-owner-%[email protected]", testWorkspaceID)); rec.Code != http.StatusCreated {
+ t.Errorf("owner status = %d, want 201: %s", rec.Code, rec.Body.String())
+ }
+}
diff --git a/server/internal/handler/webhook_delivery_worker.go b/server/internal/handler/webhook_delivery_worker.go
index f859846336..b131434943 100644
--- a/server/internal/handler/webhook_delivery_worker.go
+++ b/server/internal/handler/webhook_delivery_worker.go
@@ -122,7 +122,7 @@ func (w *WebhookDeliveryWorker) ProcessNext(ctx context.Context) (bool, error) {
key := uuidToString(delivery.TriggerID)
if !w.h.WebhookRateLimiter.Allow(ctx, key) {
w.h.Metrics.RecordWebhookRateLimited("worker_trigger")
- retryAfter := webhookLimiterRetryAfter(ctx, w.h.WebhookRateLimiter, key)
+ retryAfter := slidingWindowLimiterRetryAfter(ctx, w.h.WebhookRateLimiter, key)
if retryAfter <= 0 {
retryAfter = time.Second
}
diff --git a/server/internal/handler/webhook_rate_limiter.go b/server/internal/handler/webhook_rate_limiter.go
index 94e4f65593..2d0de3ddc0 100644
--- a/server/internal/handler/webhook_rate_limiter.go
+++ b/server/internal/handler/webhook_rate_limiter.go
@@ -9,17 +9,22 @@ import (
"github.com/redis/go-redis/v9"
)
-// WebhookRateLimit is a coarse per-token sliding-window limiter.
+// SlidingWindowRateLimit configures a per-key sliding-window limiter.
+type SlidingWindowRateLimit struct {
+ Limit int // maximum requests per window; zero disables the gate
+ Window time.Duration // sliding window length
+}
+
+// WebhookRateLimit keeps the webhook-facing API stable while the underlying
+// sliding-window implementation is shared with other admission gates.
+type WebhookRateLimit = SlidingWindowRateLimit
+
+// DefaultWebhookRateLimit is a coarse per-token sliding-window limiter.
//
// Defaults: 60 requests per 60s (1 RPS sustained, with bursts up to 60). The
// goal is "stop a misconfigured or malicious sender from hammering us
// indefinitely" — not "shape traffic to a precise budget" — so the
// implementation aims for cheap and good-enough rather than exact.
-type WebhookRateLimit struct {
- Limit int // maximum requests per window
- Window time.Duration // sliding window length
-}
-
func DefaultWebhookRateLimit() WebhookRateLimit {
return WebhookRateLimit{Limit: 60, Window: time.Minute}
}
@@ -41,38 +46,76 @@ func DefaultWebhookAbsoluteIPRateLimit() WebhookRateLimit {
return WebhookRateLimit{Limit: 600, Window: time.Minute}
}
-// WebhookRateLimiter is the contract implemented by both the in-memory and
-// Redis-backed limiters.
+// SlidingWindowRateLimiter is the contract implemented by both the in-memory
+// and Redis-backed limiters.
//
-// Check is non-consuming and is used to reject an IP that has already built
-// up bad-credential debt. Allow consumes one unit. RetryAfter returns a safe
-// client retry interval after either gate rejects.
-type WebhookRateLimiter interface {
+// Implementations may expose non-consuming checks and retry hints through the
+// optional interfaces below. Allow consumes one unit.
+type SlidingWindowRateLimiter interface {
Allow(ctx context.Context, key string) bool
- // Implementations may also satisfy webhookRateLimiterInspector. Keeping
+ // Implementations may also satisfy slidingWindowRateLimiterInspector. Keeping
// the base contract at Allow preserves compatibility with billing and
// tests that inject simple one-method safety gates.
}
-type webhookRateLimiterInspector interface {
+// WebhookRateLimiter keeps the webhook-facing contract stable.
+type WebhookRateLimiter = SlidingWindowRateLimiter
+
+type slidingWindowRateLimiterWithError interface {
+ AllowWithError(ctx context.Context, key string) (bool, error)
+}
+
+type slidingWindowRateLimiterInspector interface {
Check(ctx context.Context, key string) bool
RetryAfter(ctx context.Context, key string) time.Duration
}
-func webhookLimiterCheck(ctx context.Context, limiter WebhookRateLimiter, key string) bool {
- if inspector, ok := limiter.(webhookRateLimiterInspector); ok {
- return inspector.Check(ctx, key)
+type slidingWindowRateLimiterCheckWithError interface {
+ CheckWithError(ctx context.Context, key string) (bool, error)
+}
+
+// slidingWindowLimiterCheck keeps webhook ingress fail-open when an optional
+// backend-backed check is unavailable.
+func slidingWindowLimiterCheck(ctx context.Context, limiter SlidingWindowRateLimiter, key string) bool {
+ allowed, err := slidingWindowLimiterCheckWithError(ctx, limiter, key)
+ return err != nil || allowed
+}
+
+// slidingWindowLimiterCheckWithError exposes check failures to callers, such
+// as invitation admission, that must fail closed without consuming a budget.
+func slidingWindowLimiterCheckWithError(ctx context.Context, limiter SlidingWindowRateLimiter, key string) (bool, error) {
+ if limiter == nil {
+ return true, nil
}
- return true
+ if withError, ok := limiter.(slidingWindowRateLimiterCheckWithError); ok {
+ return withError.CheckWithError(ctx, key)
+ }
+ if inspector, ok := limiter.(slidingWindowRateLimiterInspector); ok {
+ return inspector.Check(ctx, key), nil
+ }
+ return true, nil
}
-func webhookLimiterRetryAfter(ctx context.Context, limiter WebhookRateLimiter, key string) time.Duration {
- if inspector, ok := limiter.(webhookRateLimiterInspector); ok {
+func slidingWindowLimiterRetryAfter(ctx context.Context, limiter SlidingWindowRateLimiter, key string) time.Duration {
+ if inspector, ok := limiter.(slidingWindowRateLimiterInspector); ok {
return inspector.RetryAfter(ctx, key)
}
return time.Minute
}
+// slidingWindowLimiterAllow exposes backend errors to callers that cannot
+// safely fail open. The legacy Allow method intentionally keeps webhook
+// ingress fail-open on Redis errors.
+func slidingWindowLimiterAllow(ctx context.Context, limiter SlidingWindowRateLimiter, key string) (bool, error) {
+ if limiter == nil {
+ return true, nil
+ }
+ if withError, ok := limiter.(slidingWindowRateLimiterWithError); ok {
+ return withError.AllowWithError(ctx, key)
+ }
+ return limiter.Allow(ctx, key), nil
+}
+
// ── In-memory implementation ────────────────────────────────────────────────
// memoryWebhookRateLimiter keeps per-key timestamps in a slice and prunes them
@@ -80,21 +123,36 @@ func webhookLimiterRetryAfter(ctx context.Context, limiter WebhookRateLimiter, k
// deployments should use the Redis-backed implementation so rate budgets are
// shared across pods.
type memoryWebhookRateLimiter struct {
- cfg WebhookRateLimit
- mu sync.Mutex
- hit map[string][]time.Time
+ cfg SlidingWindowRateLimit
+ mu sync.Mutex
+ hit map[string][]time.Time
+ lastSweep time.Time
}
-func NewMemoryWebhookRateLimiter(cfg WebhookRateLimit) WebhookRateLimiter {
+func newMemorySlidingWindowRateLimiter(cfg SlidingWindowRateLimit) SlidingWindowRateLimiter {
return &memoryWebhookRateLimiter{cfg: cfg, hit: make(map[string][]time.Time)}
}
-func (l *memoryWebhookRateLimiter) Allow(_ context.Context, key string) bool {
- return l.evaluate(key, true)
+func NewMemoryWebhookRateLimiter(cfg WebhookRateLimit) WebhookRateLimiter {
+ return newMemorySlidingWindowRateLimiter(cfg)
+}
+
+func (l *memoryWebhookRateLimiter) Allow(ctx context.Context, key string) bool {
+ allowed, _ := l.AllowWithError(ctx, key)
+ return allowed
+}
+
+func (l *memoryWebhookRateLimiter) AllowWithError(_ context.Context, key string) (bool, error) {
+ return l.evaluate(key, true), nil
+}
+
+func (l *memoryWebhookRateLimiter) Check(ctx context.Context, key string) bool {
+ allowed, _ := l.CheckWithError(ctx, key)
+ return allowed
}
-func (l *memoryWebhookRateLimiter) Check(_ context.Context, key string) bool {
- return l.evaluate(key, false)
+func (l *memoryWebhookRateLimiter) CheckWithError(_ context.Context, key string) (bool, error) {
+ return l.evaluate(key, false), nil
}
func (l *memoryWebhookRateLimiter) evaluate(key string, consume bool) bool {
@@ -106,6 +164,7 @@ func (l *memoryWebhookRateLimiter) evaluate(key string, consume bool) bool {
l.mu.Lock()
defer l.mu.Unlock()
+ l.sweepExpired(now, cutoff)
hits := l.hit[key]
// Trim entries that fell out of the window.
@@ -126,6 +185,22 @@ func (l *memoryWebhookRateLimiter) evaluate(key string, consume bool) bool {
return true
}
+func (l *memoryWebhookRateLimiter) sweepExpired(now, cutoff time.Time) {
+ sweepInterval := l.cfg.Window
+ if sweepInterval <= 0 || sweepInterval > time.Minute {
+ sweepInterval = time.Minute
+ }
+ if !l.lastSweep.IsZero() && now.Sub(l.lastSweep) < sweepInterval {
+ return
+ }
+ for key, hits := range l.hit {
+ if len(hits) == 0 || !hits[len(hits)-1].After(cutoff) {
+ delete(l.hit, key)
+ }
+ }
+ l.lastSweep = now
+}
+
func (l *memoryWebhookRateLimiter) RetryAfter(_ context.Context, key string) time.Duration {
if l.cfg.Limit <= 0 {
return 0
@@ -211,23 +286,27 @@ var webhookLimiterCheckScript = redis.NewScript(webhookLimiterCheckSrc)
func webhookLimiterAllowSource() string { return webhookLimiterAllowSrc }
type redisWebhookRateLimiter struct {
- cfg WebhookRateLimit
+ cfg SlidingWindowRateLimit
rdb *redis.Client
keyPrefix string
}
+func newRedisSlidingWindowRateLimiter(rdb *redis.Client, cfg SlidingWindowRateLimit, keyPrefix string) SlidingWindowRateLimiter {
+ return &redisWebhookRateLimiter{cfg: cfg, rdb: rdb, keyPrefix: keyPrefix}
+}
+
func NewRedisWebhookRateLimiter(rdb *redis.Client, cfg WebhookRateLimit) WebhookRateLimiter {
- return &redisWebhookRateLimiter{cfg: cfg, rdb: rdb, keyPrefix: webhookLimiterKeyPrefix}
+ return newRedisSlidingWindowRateLimiter(rdb, cfg, webhookLimiterKeyPrefix)
}
// NewRedisWebhookIPRateLimiter is the per-IP variant: same sliding-window
// Lua script, different key namespace so the two budgets don't interfere.
func NewRedisWebhookIPRateLimiter(rdb *redis.Client, cfg WebhookRateLimit) WebhookRateLimiter {
- return &redisWebhookRateLimiter{cfg: cfg, rdb: rdb, keyPrefix: webhookIPLimiterKeyPrefix}
+ return newRedisSlidingWindowRateLimiter(rdb, cfg, webhookIPLimiterKeyPrefix)
}
func NewRedisWebhookAbsoluteIPRateLimiter(rdb *redis.Client, cfg WebhookRateLimit) WebhookRateLimiter {
- return &redisWebhookRateLimiter{cfg: cfg, rdb: rdb, keyPrefix: webhookAbsoluteIPLimiterKeyPrefix}
+ return newRedisSlidingWindowRateLimiter(rdb, cfg, webhookAbsoluteIPLimiterKeyPrefix)
}
// NewMemoryWebhookIPRateLimiter is the in-memory per-IP variant used when no
@@ -242,11 +321,22 @@ func NewMemoryWebhookAbsoluteIPRateLimiter(cfg WebhookRateLimit) WebhookRateLimi
}
func (l *redisWebhookRateLimiter) Allow(ctx context.Context, key string) bool {
- if l.cfg.Limit <= 0 || l.rdb == nil {
+ allowed, err := l.AllowWithError(ctx, key)
+ if err != nil {
+ // Webhook ingress keeps its historical fail-open behavior because this
+ // limiter is a safety net, not a correctness requirement.
return true
}
- now := time.Now().UnixNano()
- cutoff := time.Now().Add(-l.cfg.Window).UnixNano()
+ return allowed
+}
+
+func (l *redisWebhookRateLimiter) AllowWithError(ctx context.Context, key string) (bool, error) {
+ if l.cfg.Limit <= 0 || l.rdb == nil {
+ return true, nil
+ }
+ nowTime := time.Now()
+ now := nowTime.UnixNano()
+ cutoff := nowTime.Add(-l.cfg.Window).UnixNano()
ttlSeconds := int64(l.cfg.Window/time.Second) * 2
if ttlSeconds < 1 {
ttlSeconds = 1
@@ -266,18 +356,23 @@ func (l *redisWebhookRateLimiter) Allow(ctx context.Context, key string) bool {
now, cutoff, l.cfg.Limit, ttlSeconds, member,
).Int()
if err != nil {
- // Fail open on Redis errors — webhook ingress should keep working
- // when the cache hiccups, since the rate limit is a safety net,
- // not a correctness requirement.
- return true
+ return false, err
}
- return res == 1
+ return res == 1, nil
}
func (l *redisWebhookRateLimiter) Check(ctx context.Context, key string) bool {
- if l.cfg.Limit <= 0 || l.rdb == nil {
+ allowed, err := l.CheckWithError(ctx, key)
+ if err != nil {
return true
}
+ return allowed
+}
+
+func (l *redisWebhookRateLimiter) CheckWithError(ctx context.Context, key string) (bool, error) {
+ if l.cfg.Limit <= 0 || l.rdb == nil {
+ return true, nil
+ }
cutoff := time.Now().Add(-l.cfg.Window).UnixNano()
prefix := l.keyPrefix
if prefix == "" {
@@ -290,9 +385,9 @@ func (l *redisWebhookRateLimiter) Check(ctx context.Context, key string) bool {
cutoff, l.cfg.Limit,
).Int()
if err != nil {
- return true
+ return false, err
}
- return res == 1
+ return res == 1, nil
}
func (l *redisWebhookRateLimiter) RetryAfter(_ context.Context, _ string) time.Duration {
diff --git a/server/internal/handler/webhook_rate_limiter_test.go b/server/internal/handler/webhook_rate_limiter_test.go
index df43497e0d..ebaa0e3686 100644
--- a/server/internal/handler/webhook_rate_limiter_test.go
+++ b/server/internal/handler/webhook_rate_limiter_test.go
@@ -50,6 +50,31 @@ func TestMemoryWebhookRateLimiter_WindowExpiry(t *testing.T) {
}
}
+func TestMemorySlidingWindowRateLimiter_PrunesExpiredKeys(t *testing.T) {
+ limiter := NewMemoryWebhookRateLimiter(WebhookRateLimit{Limit: 1, Window: 10 * time.Millisecond})
+ memoryLimiter, ok := limiter.(*memoryWebhookRateLimiter)
+ if !ok {
+ t.Fatalf("limiter type = %T, want *memoryWebhookRateLimiter", limiter)
+ }
+ ctx := context.Background()
+ if !limiter.Allow(ctx, "expired") {
+ t.Fatal("first key should be allowed")
+ }
+ time.Sleep(20 * time.Millisecond)
+ if !limiter.Allow(ctx, "current") {
+ t.Fatal("current key should be allowed")
+ }
+
+ memoryLimiter.mu.Lock()
+ defer memoryLimiter.mu.Unlock()
+ if _, ok := memoryLimiter.hit["expired"]; ok {
+ t.Fatal("expired key was not removed by the opportunistic sweep")
+ }
+ if _, ok := memoryLimiter.hit["current"]; !ok {
+ t.Fatal("current key was removed by the opportunistic sweep")
+ }
+}
+
func TestMemoryWebhookRateLimiter_ZeroLimitDisabled(t *testing.T) {
l := NewMemoryWebhookRateLimiter(WebhookRateLimit{Limit: 0, Window: time.Minute})
ctx := context.Background()
@@ -63,16 +88,16 @@ func TestMemoryWebhookRateLimiter_ZeroLimitDisabled(t *testing.T) {
func TestMemoryWebhookRateLimiter_CheckDoesNotConsumeBudget(t *testing.T) {
l := NewMemoryWebhookRateLimiter(WebhookRateLimit{Limit: 1, Window: time.Minute})
ctx := context.Background()
- if !webhookLimiterCheck(ctx, l, "shared-ip") || !webhookLimiterCheck(ctx, l, "shared-ip") {
+ if !slidingWindowLimiterCheck(ctx, l, "shared-ip") || !slidingWindowLimiterCheck(ctx, l, "shared-ip") {
t.Fatal("non-consuming checks should remain allowed before bad debt is charged")
}
if !l.Allow(ctx, "shared-ip") {
t.Fatal("check unexpectedly consumed the only budget slot")
}
- if webhookLimiterCheck(ctx, l, "shared-ip") {
+ if slidingWindowLimiterCheck(ctx, l, "shared-ip") {
t.Fatal("check should reject after bad debt reaches the limit")
}
- if retry := webhookLimiterRetryAfter(ctx, l, "shared-ip"); retry <= 0 || retry > time.Minute {
+ if retry := slidingWindowLimiterRetryAfter(ctx, l, "shared-ip"); retry <= 0 || retry > time.Minute {
t.Fatalf("unexpected retry interval: %v", retry)
}
}
@@ -151,3 +176,54 @@ func TestRedisWebhookIPRateLimiter_HasSeparateBudgetFromTokenLimiter(t *testing.
t.Fatal("IP limiter third request should be rejected")
}
}
+
+func TestRedisSlidingWindowRateLimiter_SeparatesInvitationNamespaces(t *testing.T) {
+ rdb := newRedisTestClient(t)
+ limits := InvitationRateLimits{
+ Actor: SlidingWindowRateLimit{Limit: 1, Window: time.Minute},
+ Workspace: SlidingWindowRateLimit{Limit: 1, Window: time.Minute},
+ Recipient: SlidingWindowRateLimit{Limit: 1, Window: time.Minute},
+ }
+ limiters := NewRedisInvitationRateLimiters(rdb, limits)
+ ctx := context.Background()
+
+ if !limiters.Actor.Allow(ctx, "same-key") || limiters.Actor.Allow(ctx, "same-key") {
+ t.Fatal("actor limiter did not enforce its independent one-request budget")
+ }
+ if !limiters.Workspace.Allow(ctx, "same-key") {
+ t.Fatal("workspace limiter shared the actor Redis namespace")
+ }
+ if !limiters.Recipient.Allow(ctx, "same-key") {
+ t.Fatal("recipient limiter shared another invitation Redis namespace")
+ }
+}
+
+func TestRedisSlidingWindowRateLimiter_PreservesWebhookFailOpenAndExposesErrors(t *testing.T) {
+ rdb := newRedisTestClient(t)
+ limiter := NewRedisWebhookRateLimiter(rdb, WebhookRateLimit{Limit: 1, Window: time.Minute})
+ if err := rdb.Close(); err != nil {
+ t.Fatalf("close Redis client: %v", err)
+ }
+
+ ctx := context.Background()
+ if !limiter.Allow(ctx, "webhook") {
+ t.Fatal("legacy webhook Allow must fail open when Redis is unavailable")
+ }
+ if !slidingWindowLimiterCheck(ctx, limiter, "webhook") {
+ t.Fatal("legacy webhook check must fail open when Redis is unavailable")
+ }
+ allowed, err := slidingWindowLimiterAllow(ctx, limiter, "invitation")
+ if err == nil {
+ t.Fatal("explicit sliding-window admission must expose the Redis error")
+ }
+ if allowed {
+ t.Fatal("explicit sliding-window admission must not report allowed on Redis error")
+ }
+ allowed, err = slidingWindowLimiterCheckWithError(ctx, limiter, "invitation")
+ if err == nil {
+ t.Fatal("explicit sliding-window check must expose the Redis error")
+ }
+ if allowed {
+ t.Fatal("explicit sliding-window check must not report allowed on Redis error")
+ }
+}
diff --git a/server/internal/metrics/business_events.go b/server/internal/metrics/business_events.go
index dca60058a3..d27efb3d37 100644
--- a/server/internal/metrics/business_events.go
+++ b/server/internal/metrics/business_events.go
@@ -56,6 +56,7 @@ type businessEventMetrics struct {
autopilotRunSkipped *prometheus.CounterVec
webhookDelivery *prometheus.CounterVec
webhookRateLimited *prometheus.CounterVec
+ emailRateLimited *prometheus.CounterVec
githubEventReceived *prometheus.CounterVec
githubPRReview *prometheus.CounterVec
githubPRMergeSeconds prometheus.Histogram
@@ -173,6 +174,10 @@ func newBusinessEventMetrics() *businessEventMetrics {
Name: "multica_webhook_rate_limited_total",
Help: "Total webhook admissions or worker dispatches delayed by a bounded safety gate.",
}, metricLabels("multica_webhook_rate_limited_total")),
+ emailRateLimited: prometheus.NewCounterVec(prometheus.CounterOpts{
+ Name: "multica_email_rate_limited_total",
+ Help: "Total email-producing actions rejected by a bounded safety gate.",
+ }, metricLabels("multica_email_rate_limited_total")),
githubEventReceived: prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "multica_github_event_received_total",
Help: "Total GitHub webhook events received by event kind and action.",
@@ -241,6 +246,7 @@ func (e *businessEventMetrics) collectors() []prometheus.Collector {
e.autopilotRunSkipped,
e.webhookDelivery,
e.webhookRateLimited,
+ e.emailRateLimited,
e.githubEventReceived,
e.githubPRReview,
e.githubPRMergeSeconds,
@@ -408,6 +414,16 @@ func (m *BusinessMetrics) RecordWebhookRateLimited(gate string) {
m.events.webhookRateLimited.WithLabelValues(NormalizeWebhookRateLimitGate(gate)).Inc()
}
+func (m *BusinessMetrics) RecordEmailRateLimited(action, gate string) {
+ if m == nil || m.events == nil {
+ return
+ }
+ m.events.emailRateLimited.WithLabelValues(
+ NormalizeEmailRateLimitAction(action),
+ NormalizeEmailRateLimitGate(gate),
+ ).Inc()
+}
+
// RecordGithubEventReceived counts a GitHub webhook event by event kind / action.
func (m *BusinessMetrics) RecordGithubEventReceived(eventKind, action string) {
if m == nil || m.events == nil {
diff --git a/server/internal/metrics/business_test.go b/server/internal/metrics/business_test.go
index a2b6a2f50b..a65b5ac08a 100644
--- a/server/internal/metrics/business_test.go
+++ b/server/internal/metrics/business_test.go
@@ -142,6 +142,7 @@ func TestBusinessMetricsRegistryExposesAllFamilies(t *testing.T) {
m.RecordAutopilotRunSkipped("manual", "throttled")
m.RecordWebhookDelivery("github", "dispatched")
m.RecordWebhookRateLimited("absolute_ip")
+ m.RecordEmailRateLimited("workspace_invitation", "recipient")
m.RecordGithubEventReceived("pull_request", "opened")
m.RecordGithubPRReview("approved")
m.ObserveGithubPRMergeSeconds(120)
diff --git a/server/internal/metrics/labels.go b/server/internal/metrics/labels.go
index 7eda69db2d..caca63badb 100644
--- a/server/internal/metrics/labels.go
+++ b/server/internal/metrics/labels.go
@@ -79,6 +79,7 @@ var businessMetricLabels = map[string][]string{
"multica_autopilot_run_skipped_total": {labelCadence, labelReason},
"multica_webhook_delivery_total": {labelProvider, labelStatus},
"multica_webhook_rate_limited_total": {labelGate},
+ "multica_email_rate_limited_total": {labelAction, labelGate},
"multica_github_event_received_total": {labelEventKind, labelAction},
"multica_github_pr_review_total": {labelResult},
"multica_cloudruntime_request_total": {labelOp, labelStatus},
diff --git a/server/internal/metrics/labels_pr3.go b/server/internal/metrics/labels_pr3.go
index d1c9f783bb..1e0772417e 100644
--- a/server/internal/metrics/labels_pr3.go
+++ b/server/internal/metrics/labels_pr3.go
@@ -127,6 +127,18 @@ var (
"other": "other",
}
+ knownEmailRateLimitActions = map[string]string{
+ "workspace_invitation": "workspace_invitation",
+ "other": "other",
+ }
+
+ knownEmailRateLimitGates = map[string]string{
+ "actor": "actor",
+ "workspace": "workspace",
+ "recipient": "recipient",
+ "other": "other",
+ }
+
knownGithubEventKinds = map[string]string{
"pull_request": "pull_request",
"pull_request_review": "pull_request_review",
@@ -347,6 +359,14 @@ func NormalizeWebhookRateLimitGate(value string) string {
return normalizeFromAllowList(value, knownWebhookRateLimitGates, "other")
}
+func NormalizeEmailRateLimitAction(value string) string {
+ return normalizeFromAllowList(value, knownEmailRateLimitActions, "other")
+}
+
+func NormalizeEmailRateLimitGate(value string) string {
+ return normalizeFromAllowList(value, knownEmailRateLimitGates, "other")
+}
+
func NormalizeGithubEventKind(value string) string {
return normalizeFromAllowList(value, knownGithubEventKinds, "other")
}
diff --git a/server/internal/metrics/labels_pr3_test.go b/server/internal/metrics/labels_pr3_test.go
index f1c066d7c3..ff20c75550 100644
--- a/server/internal/metrics/labels_pr3_test.go
+++ b/server/internal/metrics/labels_pr3_test.go
@@ -37,6 +37,9 @@ func TestNormalizePR3LabelsCollapseUnknownValues(t *testing.T) {
{"webhook_provider_unknown", metrics.NormalizeWebhookProvider, "internal-billing", "other", "other"},
{"webhook_status_unknown", metrics.NormalizeWebhookDeliveryStatus, "exotic", "other", "other"},
{"webhook_gate_unknown", metrics.NormalizeWebhookRateLimitGate, "exotic", "other", "other"},
+ {"email_rate_limit_action_known", metrics.NormalizeEmailRateLimitAction, "workspace_invitation", "workspace_invitation", "other"},
+ {"email_rate_limit_action_unknown", metrics.NormalizeEmailRateLimitAction, "password_reset", "other", "other"},
+ {"email_rate_limit_gate_unknown", metrics.NormalizeEmailRateLimitGate, "email_address", "other", "other"},
{"github_event_unknown", metrics.NormalizeGithubEventKind, "deploy_status", "other", "other"},
{"github_action_empty", metrics.NormalizeGithubAction, "", "none", "none"},
{"github_action_unknown", metrics.NormalizeGithubAction, "rerequested_by_user", "other", "other"},