Repository navigation
refactor(backend): unified Redis sliding-window rate limiter (#1023) - #1024
Conversation
Replace the bespoke per-endpoint webhook rate limiter with a single shared sliding-window primitive, per TARGET_ARCHITECTURE.md §Backend. New services/rate_limiter.py — a Redis sorted-set rolling window (no fixed-window boundary burst), fail-open with a bounded per-worker in-process fallback, cached Redis client (reset-on-error, ACL-aware logging). `enforce(key, limit, window)` raises 429 + Retry-After. Preserves the #644 anti-TOCTOU property: the count is taken after an atomic pipelined add, never via a read-then-write gap. routers/webhooks.py now calls rate_limiter.enforce(); its ~150 lines of bespoke INCR/fixed-window + in-process fallback + cached-client plumbing are deleted. Behavior preserved (10/60s per token, fail-open). Scope (Option A, decided during implementation): the auth login/OTP limiters in routers/auth.py are failure-counters (increment on failure, reset on success) — a different pattern — and are intentionally NOT migrated. A global ASGI middleware with a route->policy table is a tracked follow-up. Documented in architecture.md §"Rate limiting" + on the issue. Tests: tests/unit/test_rate_limiter.py — 9 tests covering the in-process fallback (allow/block/window-rolloff/key-isolation), the Redis ZSET path, the mid-call Redis error, and enforce() 429+Retry-After. The two old webhook-internal unit test files are removed (their logic moved to the primitive; the #644 property is ported); end-to-end webhook rate limiting stays covered by tests/integration/test_webhook_rate_limit.py. Related to #1023 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…#1023) The `rl` fixture registered the standalone-loaded rate_limiter module via a bare `sys.modules[spec.name] = module`, which the sys.modules-pollution lint flags as a new violation over baseline. Request `monkeypatch` in the fixture and use `monkeypatch.setitem`, which auto-restores (deletes) the entry at teardown. No test-behavior change; the 9 rate_limiter unit tests still pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
5421cbd to
38f964d
Compare
|
Resolve by running |
vybe
left a comment
There was a problem hiding this comment.
Validated via /validate-pr. Sliding-window primitive verified: #644 anti-TOCTOU property preserved (count after atomic pipelined add; 40-thread test), cached Redis client closes the per-request-connection DoS-amplifier, fail-open with bounded in-process fallback, enforce() 429+Retry-After, webhook idempotency (Invariant #18) untouched, architecture.md updated. Scope (Option A — webhook only, auth failure-counters left as-is) is correct.
One conscious note accepted: the Redis-OUTAGE in-process fallback changes from 3x to 1x the limit per worker (stricter, net-safer); normal-operation behavior is identical. Approving.
…utes (trinity-enterprise#1322) CP-P3 — the write tools. create_project_task, update_project_task, add_project_task_note, add_project_log_entry, link_to_project, set_project_health, create_project and import_project pick their door from the key's scope on the same allow-list as the read tools (one doorFor): agent keeps today's exact request; user acts as the person on the Workspace route with the same body; a user key naming an agent is refused act_as_not_offered; any other scope is refused key_not_supported in the tool, with no request. import_project takes `agent` for a person's key (the agent whose folder it is) and refuses its absence as agent_required. No write tool listed to a user key can answer it "needs an agent key" any more: the act-as path is gone from them. create_project_task, create_project and import_project no longer point at propose_project_changes, which a person's key cannot call. The #1024 project act-as tests now expect act_as_not_offered. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ity-enterprise#1322) (#4688) * feat(mcp): list project tools to agent and person keys only (trinity-enterprise#1322) CP-P1 — access rules and listing. Two allow-list predicates in access.ts: projectToolAccess (scope agent or user) for the shared project tools, and agentKeyToolAccess (scope agent) for start_project_task and propose_project_changes. Every project tool now carries its own canAccess, so none inherits the operator gate and the system key, ops, connector, delegate and any future scope are shown no project tool. The policy rows say the tools route by the key's scope. tool-visibility.test.ts gains a real-transport census: each project tool is listed to exactly its scopes for seven key scopes, every registered project tool has a row and its own canAccess, a person-rule row maps to [user] exactly, and a hidden tool called by name is "not found" with zero backend requests. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(mcp): a person's user key reads projects on the Workspace routes (trinity-enterprise#1322) CP-P2 — the person-route client and the read tools. A new module, tools/projects_person_client.ts, calls the Workspace project routes with the person's own user key (no act-as header, no turn), mirroring the agent door's read methods by name and shape. The seven read tools (list_projects, get_project, list_project_tasks, get_project_log, list_project_executions, get_steward_digest, read_project_context) pick the door from the key's scope, an allow-list: agent keeps today's exact request and its refusal of another agent's name; user reads as the person; a user key naming an agent is refused act_as_not_offered; any other scope is refused key_not_supported in the tool, with no request. Keyless dev mode keeps today's path. list_projects takes include_archived for a person's key. projects-person-key.test.ts drives the real tools and client with only fetch stubbed: per tool and scope, the request that leaves the server. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(mcp): a person's user key writes to projects on the Workspace routes (trinity-enterprise#1322) CP-P3 — the write tools. create_project_task, update_project_task, add_project_task_note, add_project_log_entry, link_to_project, set_project_health, create_project and import_project pick their door from the key's scope on the same allow-list as the read tools (one doorFor): agent keeps today's exact request; user acts as the person on the Workspace route with the same body; a user key naming an agent is refused act_as_not_offered; any other scope is refused key_not_supported in the tool, with no request. import_project takes `agent` for a person's key (the agent whose folder it is) and refuses its absence as agent_required. No write tool listed to a user key can answer it "needs an agent key" any more: the act-as path is gone from them. create_project_task, create_project and import_project no longer point at propose_project_changes, which a person's key cannot call. The #1024 project act-as tests now expect act_as_not_offered. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(mcp): five person-only project tools for a person's own user key (trinity-enterprise#1322) CP-P4 — the person's acts, per the orchestrator's second rulings: - set_project_lifecycle: start, stop, finish, archive, restore. Each has a person route (finish is PATCH status=done; the others their own POST). A note is logged on start and stop only, and note_recorded says so. - update_project_settings: sends goal (never description); the fields, steward, visibility and mode each go in their own PATCH, and results reports each, so a refused mode never hides that visibility applied. - set_steward_waking: on resumes, off pauses. - manage_project_members: one request per item, in order, URL-encoded on DELETE, a result per item; at most 20, an item both added and removed is refused, and project_not_found stops the batch with the rest not_attempted. - decide_project_runs: no ids lists the waiting runs with their ids; approve and decline pass the backend's per-id results through; an id in both lists is refused. Each is listed to user keys only (humanOnlyToolAccess("person"), PERSON_ONLY policy rows) and refuses any other key inside the tool: an agent key with persons_act naming the path it has (ask_operator, or propose_project_changes for people and steward), every other scope key_not_supported. The listing census covers all 22 project tools, and a user-only project tool must carry the person policy row. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(mcp): project refusals and descriptions read true for the key that reads them (trinity-enterprise#1322) - explain(): only a 403 saying "is not licensed" reads as not licensed; any other plain-string 403 (account_has_no_email, a Workspace permission) is passed through unchanged. A test per source: list_projects, get_project, fail(). - A session with no scope takes the agent path only when the server requires no key; a keyed one is refused key_not_supported. Over the real server, a key row with no scope is listed and routed as a person's key. - read_project_context promises truncated/next_offset to an agent's key only; an offset from a person's key is refused offset_not_offered, with no request. - get_project gives a person's key the steward-proposal pointer on a waiting proposal: proposal.ask_id as item_id to respond_to_operator_queue, decided by the proposing agent's primary contacts. An agent key's page is unchanged. - link_to_project, get_steward_digest and set_project_health reworded to read true for a person and an agent. - Pointer test over the real transport: no project tool description, and no refusal those tools give, names a tool the reading key (user, agent) is not listed. It went red on a first draft that named respond_to_operator_queue in the shared get_project description. Mutation: with the explain() and scope-less fixes reverted, the three pass-through tests and the keyed scope-less test went red. Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(mcp): project tools route by key scope; 190 tools (trinity-enterprise#1322) - docs/memory/architecture/mcp-server.md: the scope allow-list on the project tools (agent / user / refused), the keyless-only scope-less path, listing per scope, the offset and proposal pointers, the explain() rule, and the guards. - docs/user-docs/sharing-and-access/workspace-projects.md: one pointer line (ruling T5) — a person's own key works on the project tools; a Workspace-only account cannot create an MCP key. - docs/user-docs/integrations/mcp-server.md: 190 tools, 185 operator tools, projects.ts 22 — the counts tool-count-docs.test.ts reads from createServer(). Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(mcp): decide_project_runs reports success only when every id was applied (trinity-enterprise#1322) The backend answers runs/approve|decline with HTTP 200 and one {id, outcome} per id; a refused id (run_not_found, already_decided, ...) was returned under success: true. Each id now carries applied + why, success is true only when every id was applied, and approvals stay reported when the decline request after them fails (review C1, I1). The fixture now uses the backend's real shape; the run_not_found test went red on the previous code (success: true). Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(mcp): project tool texts read true for a person's key; widen the visibility pins (trinity-enterprise#1322) - The two agent-only tools answer a user key "this tool is for an agent's own key", naming no path (review I3). - The not-found-by-name loop covers the agent key on the five person tools (I4). - agent_name and list_projects describe both a person's key and an agent's (I5). - get_project's proposal pointer, built from a backend answer, is walked for tools a user key is not listed (I2; red when the pointer names propose_project_changes). Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(mcp): pin that a project tool call's audit row carries the key's scope (trinity-enterprise#1322) Ruling T4: audit.ts::logToolCall writes mcp_scope from the session on every wrapped call; a get_project call with a user key records mcp_scope 'user'. Red with that field dropped. Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(mcp): project person batch tools report per item; audit row carries scope (trinity-enterprise#1322) Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(portal): the Workspace auth door has a person MCP caller, never an agent one The project tools call the Workspace project routes with a person's own user-scoped key, which get_portal_principal resolves to that person; an agent key is still refused there. Reword the portal_auth comment and the router's # mcp: header, which said no MCP tool targets the surface. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(mcp): decide_project_runs claims the approvals applied only when every id was When the approve request succeeded but some ids were refused (e.g. r1 started, r2 already_decided) and the decline request then failed, the error read "The approvals were applied". It now names both counts: "1 of 2 approvals applied; the declines were not (...)". Red first: "a decline failure after a partly applied approve names both counts" failed on the old code (doesNotMatch /^The approvals were applied/). Its mirror (every approval applied, decline fails) pins the true claim. Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(architecture): workspace principal has one MCP caller, on a person's key Replace the stale "no MCP tool targets it" claim: the project tools reach the surface with a person's own user-scoped key; an agent key is refused. Grepped docs/ for the same claim about this surface: no other hit. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Trinity Agent (trinity) <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
Summary
Replace the bespoke per-endpoint webhook rate limiter with a single shared sliding-window primitive, per
TARGET_ARCHITECTURE.md§"Backend → What Changes". One audited implementation, true rolling window (no fixed-window boundary burst where a flood straddling the edge could pass 2× the limit).What changed
services/rate_limiter.py— Redis sorted-set rolling window.check(key, limit, window)/enforce(...)(429 +Retry-After). Fail-open with a bounded per-worker in-process fallback. Cached Redis client (reset-on-error, ACL-aware logging) — same hardened pattern the webhook limiter used. Preserves the fix(security): TOCTOU race in webhook rate limiter — concurrent requests can bypass WEBHOOK_RATE_LIMIT #644 anti-TOCTOU property: count taken after an atomic pipelined add, never a read-then-write gap.routers/webhooks.py— now callsrate_limiter.enforce(f"webhook:{token}", 10, 60); ~150 lines of bespokeINCR/fixed-window + in-process fallback + cached-client plumbing deleted. Behavior preserved (10/60s per token, fail-open).Scope decision (Option A — agreed during implementation)
Reading the code showed the auth login/OTP limiters (
routers/auth.py) are failure-counters (increment on failure, reset on success) — a fundamentally different pattern from a request-rate limiter, so they do not map to a sliding window. This PR therefore migrates only the webhook limiter (the genuine request-rate case) and leaves auth's failure-counters as-is (documented). A global ASGI middleware with a route→policy table is a tracked follow-up. This keeps the change bounded and avoids force-fitting two different patterns under one abstraction. (Issue #1023 AC corrected via comment.)Testing
tests/unit/test_rate_limiter.py— 9 tests: in-process fallback (allow / block-at-limit / window roll-off / key isolation), Redis ZSET path (allow→block, Retry-After), the fix(security): TOCTOU race in webhook rate limiter — concurrent requests can bypass WEBHOOK_RATE_LIMIT #644 concurrency property (40 threads → exactlylimitallowed), fail-open on mid-call Redis error,enforce()429 +Retry-After. All green.test_webhook_rate_limit_inprocess.py,test_webhook_rate_limit_toctou.py) are removed — their logic moved into the primitive and the fix(security): TOCTOU race in webhook rate limiter — concurrent requests can bypass WEBHOOK_RATE_LIMIT #644 property is ported to the primitive's tests.tests/integration/test_webhook_rate_limit.py(real Redis).tests/unit/run: 1786 passed (5 unrelatedtest_git_pull_branchgit-e2e failures are pre-existing/local-env).Docs
architecture.md— new §"Rate limiting" (the shared primitive, the auth-is-separate rationale, the global-middleware follow-up) + webhook endpoint row updated.Related to #1023
🤖 Generated with Claude Code