Skip to content

fix(channels): rate-limit sign-in code emails on Telegram, WhatsApp and Slack (abilityai/trinity-enterprise#1253) - #4543

Merged
obasilakis merged 4 commits into
devfrom
feature/1253-channel-login-rate-limit
Nov 13, 2026
Merged

obasilakis merged 4 commits into
devfrom
feature/1253-channel-login-rate-limit

Conversation

@obasilakis

@obasilakis obasilakis commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Telegram /login <email>, WhatsApp /login <email> and the Slack require_email step each emailed a sign-in code on every request, with no cap. This PR caps sign-in code requests on every surface that mints one.

Design

  • Three caps over 10 minutes in services/channel_login_limit.py, all counted with the shared rate_limiter:
    • per sender (5): channel_login_sender:{channel}:{sender_id} (Slack {team}:{user});
    • per address (3): one budget shared by Telegram, WhatsApp, Slack, the web login and MCP inline auth;
    • per bot / WhatsApp binding / Slack workspace (20).
  • Shared per-address key. login_code_email:<sha256 of the stripped, lowercased address>. It is built in one function (_address_key), so every surface charges the same key for the same address, and its size is fixed whatever the caller sends.
  • Charged before the membership check. The web login (routers/auth.py) and MCP inline auth (services/mcp_auth_service.py) call address_allowed before their whitelist / known-address check, so the budget counts every address alike and its refusal says nothing about membership. The web reply stays the uniform generic body; the MCP send runs after its 202. The channels run the check before the ent#849 membership branch. The cap never reads email_login_codes.
  • Refund. rate_limiter.refund(key, result) removes the hit an allowed check recorded. Channel caps run sender, then address, then bot; when one refuses, the caps already passed are refunded, so a refused request is charged to none.
  • Input bound. EmailLoginRequest.email is capped at 254 characters; a longer address gets the route's usual 422 before any budget is charged. MCP and the channels already reject over 254.
  • In-process fallback (Redis down) caps each key prefix at 10k keys and evicts the oldest key of that prefix, so a flood of login addresses cannot evict another limiter's bucket (MCP global cap, webhook limits, channel sender/bot caps).
  • Over the limit, channels reply "Too many sign-in code requests. Try again in 10 minutes.", send nothing and log a WARN; Slack keeps the pending row at awaiting_email.

Accepted risks

  • Named-victim lockout: any sender within its own cap can request 3 codes per 10 minutes for one address and keep that address from getting a code on every channel, the web login and MCP.
  • With Redis down the fallback is per worker, so caps multiply by the worker count.
  • Plus-addressing gets around the address cap; sender and bot caps still hold.
  • 4 throwaway accounts can block /login on one bot for 10 minutes.

Changes

  • src/backend/services/channel_login_limit.py (new): caps, hashed address key, address_allowed, login_code_request_allowed with refund.
  • src/backend/services/rate_limiter.py: RateLimitResult.member, refund(), per-prefix bounded in-process fallback.
  • src/backend/routers/auth.py: web login charges the shared address budget before the whitelist check.
  • src/backend/services/mcp_auth_service.py: MCP inline auth charges it before the known-address check.
  • src/backend/db_models.py: EmailLoginRequest.email max length 254.
  • src/backend/adapters/{telegram,whatsapp,slack}_adapter.py: call login_code_request_allowed before minting a code.
  • Tests: tests/unit/test_ent1253_channel_login_rate_limit.py (new), tests/unit/test_848_mcp_inline_auth.py, tests/unit/conftest.py (clears limiter buckets per test), tests/test_whatsapp_integration.py (one sender per /login test).
  • Docs: docs/memory/architecture/security.md (rate limiting), docs/memory/feature-flows/unified-channel-access-control.md.

Test Plan

  • cd tests && python -m pytest unit/test_ent1253_channel_login_rate_limit.py unit/test_848_mcp_inline_auth.py unit/test_186_enumeration_uniformity.py unit/test_ent849_email_code_policy.py unit/test_rate_limiter.py -q -p no:randomly
  • Key size is fixed for a 5 MB input; web, MCP and channels compute one key for " [email protected]", "[email protected] ", "[email protected]".
  • A 256-char email on web raises 422 and charges nothing.
  • Flooding distinct login addresses with Redis down does not evict an unrelated bucket.
  • check + refund through the Redis branch (fakeredis).
  • Refused requests are charged to no cap; web/MCP charge before the membership check.

Fixes abilityai/trinity-enterprise#1253

🤖 Generated with Claude Code

…nd Slack

Telegram `/login <email>`, WhatsApp `/login <email>` and the Slack
require_email email step sent a verification email on every request.
Commands reach handle_command straight from the transports, so the
router's per-sender message limit never saw them.

services/channel_login_limit.py caps code requests over 10 minutes:
5 per sender ({channel}:{sender_id}), 3 per address (shared across
channels) and 20 per Telegram bot / WhatsApp binding / Slack workspace,
counted with rate_limiter.check keyed on the input. Adapters call it
after the email-format check and before the ent#849 membership branch.
Over the limit the bot says so, mints no code and sends no email.

The cap never reads email_login_codes: the web login writes rows only
for whitelisted addresses, so a reply derived from them would reveal
whitelist membership. Logs carry a hash of the sender id (a WhatsApp
sender id is a phone number).

tests/unit/conftest.py empties the limiter's in-process buckets before
each test; several files send /login from the same fake sender.

Fixes Abilityai/trinity-enterprise#1253

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@AndriiPasternak31 AndriiPasternak31 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes: an existing integration test will go red under the new cap, and the per-address budget isn't shared with web/MCP login, which the issue asks for.

1. tests/test_whatsapp_integration.py exceeds the new per-sender cap.
The module sends /login <email> six times from the same _TEST_USER_PHONE on one module-scoped binding (lines 295, 310, 332, 358, 384, 414). The emails differ, but the sender cap is 5 per 10 minutes (channel_login_limit.py, PER_SENDER = 5), so the sixth request (in test_logout_clears_verified_email) is suppressed, and the test then times out waiting for the pending-login key. The bucket lives in Redis, so re-running the module within 10 minutes fails earlier. Each test needs its own from_phone.

2. The address budget isn't shared with web/MCP.
Web and MCP count rows in email_login_codes (auth.py:642, mcp_auth_service.py:127); the channel cap is a separate Redis bucket. Channel codes count against web, but not the other way round: after 3 web codes, the channels can still send 3 more, and Slack codes write no row at all. Not reading web rows (to avoid leaking whether an address is whitelisted) doesn't rule out a shared bucket. Web and MCP could charge the same rate_limiter key before their whitelist check, and since the web reply is uniform that leaks nothing. If the split is intended, please get it agreed on ent#1253 and fix the new test module's docstring, which says "shared with web + MCP login".

3. A request refused by a later cap still uses up the earlier ones.
rate_limiter.check records the hit when it passes, so a request that clears the sender and address caps but is refused by the bot cap has still spent the sender's and the address's budget. The module docstring promises only the other direction. While a bot is flooded (the accepted 4-accounts case), a legitimate user's retries can exhaust their address budget across every bot and Slack for the following 10 minutes. Fix with a reorder or a refund. rate_limiter can't check without counting.

4. A named victim can now be locked out on every channel. Please list this in the accepted risks.
One Telegram account, within its sender cap of 5, can send /login [email protected] 3 times every 10 minutes and keep that address locked out of Slack verification and Telegram/WhatsApp /login on every agent. Any per-address cap allows this. Slack previously had no per-address cap, so this is new there.

Smaller items

  • test_web_code_rows_do_not_change_the_reply only catches an import placed inside the function; a module-level from database import db would slip past patch("database.db").
  • The in-process fallback in rate_limiter never removes keys, and here they are user-supplied (emails, sender ids). That only matters while Redis is down.
  • The "Current consumers" list in docs/memory/architecture/security.md:262 isn't updated.

Looks right: all three channels are covered, the cap runs before the ent#849 branch so members and outsiders get the same reply, emails are normalised, and every Redis command used is allowed by the backend ACL.

obasilakis and others added 2 commits November 13, 2026 17:52
The module sent /login six times from one number, past the per-sender
cap of 5 per 10 minutes, and the cap lives in Redis, so re-runs within
the window failed sooner.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…channels

- Web login and MCP inline auth charge the per-address rate_limiter
  bucket the channels use (login_code_email:<email>), before their
  whitelist / known-address check, so the budget is one budget and its
  refusal reveals no membership.
- A channel request refused by a later cap no longer spends the earlier
  ones: rate_limiter.refund removes the recorded hit.
- The in-process fallback is capped at 10,000 keys; keys here are user input.
- Accepted risk documented: one sender can keep a named address from
  receiving a code on every surface (module docstring, security.md, flow doc).
- Current consumers list in security.md updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@obasilakis

Copy link
Copy Markdown
Contributor Author
  1. WhatsApp integration tests now use a fresh sender number per test (user_phone fixture).
  2. Shared budget per ent#1253 AC Fix: Add missing Docker labels to system agent container #1 ("one budget shared with web and MCP login"): web and MCP charge the same login_code_email:<email> limiter key before their whitelist / known-address check; web reply unchanged. The row counts stay as a second cap that holds when Redis is down.
  3. Added rate_limiter.refund; a request refused by any cap is charged to none. Test: test_bot_cap_refusal_spends_no_sender_or_address_budget.
  4. Named-victim lockout listed as an accepted risk (module docstring, security.md, flow doc, PR body).

Smaller: row-read test patches the shared db object; in-process fallback capped at 10k keys; security.md consumers list updated.

Fixed in 80a7cd7 and 78c64b4.

@AndriiPasternak31 AndriiPasternak31 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-checked 80a7cd746 + 78c64b460. All four points are fixed:

  • Each WhatsApp test gets its own sender.
  • Web and MCP charge the shared key before the whitelist / known-address check. Moving either charge after that check fails tests.
  • The refund works: a request refused by any cap is charged to none.
  • The lockout risk is documented.

The web reply stays uniform with the new charge, and refund only adds ZREM.

Still blocking: an unauthenticated caller can fill Redis memory through the web login. This comes from the new shared key.

  • EmailLoginRequest.email is a plain str with no length limit (db_models.py:768), and nothing in request_email_code checks its length.
  • nginx accepts bodies up to 25 MB (nginx-server.conf:20), and the route has no per-IP limit.
  • address_allowed builds the key straight from the input: login_code_email:{email} (channel_login_limit.py), TTL 601 s. A 5 MB "email" gives a 5 MB key.
  • Repeated 25 MB requests stack up for 10 minutes each. Redis has no maxmemory (docker-compose.yml:552) and also holds the event bus and secrets, so this takes the platform down, not just login.
  • MCP (max_length=254) and the channels (>254 rejected) are already bounded, so the web route is the only open path.
  • Fix: hash the normalised email in the key, or refuse anything over 254 chars before charging.

Smaller:

  • PR body is stale. It still describes the first design: "never reads email_login_codes … count against the web cap", "not charged to the next". It doesn't mention the shared web/MCP charge, refund or the lockout risk, and the Changes list omits auth.py, mcp_auth_service.py and rate_limiter.py. The squash commit will carry that text.
  • In-process fallback while Redis is down. Eviction drops the oldest-created key (rate_limiter.py:157-158), and the anonymous web route can push 10k distinct addresses through in seconds. That wipes every long-lived bucket on that worker: the MCP global cap, webhook limits, the channel sender/bot caps. Bounding the key size (above) helps with memory but not with this.
  • Log line. auth.py:637 logs the anonymous email with %s, so newlines and very long lines get through. %r matches the rest of the PR.
  • Test gap. The autouse fixture forces _get_redis=None, so the Redis branch of refund isn't unit-tested.

…llback

- The per-address limiter key holds a sha256 of the stripped, lowercased
  address, so its size is fixed for any input. Web, MCP and the channels
  build it in one function and share the same key for the same address.
- The web login model caps email at 254 characters; a longer address gets
  the route's usual 422 before any budget is charged.
- The in-process fallback caps each key prefix at 10k keys and evicts the
  oldest key of the same prefix, so a flood of login addresses while Redis
  is down cannot evict another limiter's bucket.
- Log the anonymous address with %r on the web and MCP suppression lines.
- Unit test for check + refund through the Redis branch (fakeredis).

Refs Abilityai/trinity-enterprise#1253

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@obasilakis

Copy link
Copy Markdown
Contributor Author

Fixed in 83cd3efc5:

  1. The address key now stores a sha256 of the normalised address, so its size is fixed and web/MCP/channels share one key. The web model caps email at 254, so a longer one gets a 422 before any charge. Tests cover a 5 MB input, the shared key across surfaces, and the over-254 refusal.
  2. PR body rewritten for the current design: shared key charged before the membership check, refund, hashed key, 254 cap, lockout risk, full Changes list.
  3. The in-process fallback now caps each key prefix separately (10k) and evicts within that prefix, so a login-address flood can't evict MCP, webhook or channel buckets. Test added.
  4. Web and MCP suppression lines log the address with %r; both inputs are capped at 254.
  5. Added a fakeredis test that runs check + refund through the Redis branch.

@AndriiPasternak31 AndriiPasternak31 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving 83cd3efc5. The Redis blocker is fixed: every surface builds the key through _address_key (sha256 of the stripped, lowercased address), and the web model caps the email at 254 characters, so a 5 MB email now gets a 422 before any charge and writes no key. The other claims hold:

  • Normalisation is identical across web, MCP and the channels.
  • Per-prefix fallback caps keep a login-address flood from evicting other buckets.
  • The suppression lines use %r.
  • The fakeredis refund test goes red if the Redis branch is broken.

Two wording nits in the PR body and the module docstring:

  • "Caps sign-in code requests on every surface that mints one": the portal (client_portal/service.py:393), public-link verification (routers/public.py:458) and account bind (users.py:116) mint codes outside the shared budget. The portal has its own 5/300 s cap.
  • "MCP and the channels already reject over 254" (channel_login_limit.py:19): Slack's _extract_email (slack_adapter.py:618-620) has no length cap. With the key hashed this can't reach Redis anymore; the only effect is a very long log line on refusal.

@obasilakis
obasilakis merged commit 4d37690 into dev Nov 13, 2026
26 of 28 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants