Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

feat(agents,web): WS-D1 hardening — rate limit, real tests, drawer vitest

Beenu Arora03934c31779d
diff --git a/apps/web/src/components/alerts/ExplainDrawer.test.tsx b/apps/web/src/components/alerts/ExplainDrawer.test.tsx
new file mode 100644
index 000000000..357178113
--- /dev/null
+++ b/apps/web/src/components/alerts/ExplainDrawer.test.tsx
@@ -0,0 +1,574 @@
+// WS-D1 — pin the ExplainDrawer streaming contract.
+//
+// The drawer is a thin renderer over the `agentsApi.explainStream` NDJSON
+// pipe, but it owns three things that the rest of the app depends on and
+// that have already broken once before: (1) the abort lifecycle so a closed
+// drawer doesn't keep an LLM call alive, (2) per-frame routing so a re-emitted
+// MITRE card doesn't double-render, and (3) graceful fallback when the
+// backend trips a rate limit or runs into a transport error.
+//
+// We test against a controllable `ReadableStream`: each test gets an
+// `enqueue(frame)` helper and chooses exactly when to close the body. That
+// keeps timing assertions deterministic without faking timers, which is the
+// only way React state batches behave consistently in jsdom.
+
+import { describe, expect, it, vi, beforeEach } from 'vitest';
+import { act, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+// ─── Mocks ───────────────────────────────────────────────────────────────────
+
+const explainStreamMock = vi.hoisted(() => vi.fn());
+vi.mock('@/lib/api', () => ({
+ __esModule: true,
+ agentsApi: {
+ explainStream: explainStreamMock,
+ },
+}));
+
+// Import AFTER the mock so the component picks up our stub.
+import { ExplainDrawer } from './ExplainDrawer';
+import type { Alert, ExplainStreamFrame } from '@/lib/api';
+
+// ─── Helpers ─────────────────────────────────────────────────────────────────
+
+interface MockStreamHandle {
+ /** Push one NDJSON frame onto the wire. Newline is appended for you. */
+ enqueue: (frame: ExplainStreamFrame) => Promise<void>;
+ /** Push a raw string (used when we want a malformed line, etc.). */
+ enqueueRaw: (text: string) => Promise<void>;
+ /** Close the body cleanly (stream "done" from the server's POV). */
+ close: () => Promise<void>;
+ /** Capture the AbortSignal the drawer passed to `explainStream`. */
+ signal: () => AbortSignal | undefined;
+}
+
+/**
+ * Build a controllable Response whose body is a ReadableStream we can push
+ * to from the test. The drawer's `getReader().read()` loop will surface
+ * each chunk to `applyFrame` exactly as the real backend would.
+ */
+function buildMockStream(opts: {
+ status?: number;
+ signalCapture: { current: AbortSignal | undefined };
+}): { response: Response; handle: MockStreamHandle } {
+ const encoder = new TextEncoder();
+ let controller: ReadableStreamDefaultController<Uint8Array>;
+ const body = new ReadableStream<Uint8Array>({
+ start(c) {
+ controller = c;
+ },
+ });
+
+ const response = new Response(body, {
+ status: opts.status ?? 200,
+ headers: { 'Content-Type': 'application/x-ndjson' },
+ });
+
+ const handle: MockStreamHandle = {
+ async enqueue(frame) {
+ // Wrap in act() so the React state updates inside the drawer's
+ // streaming reader are flushed before the test moves on. Without
+ // this we get noisy "not wrapped in act(...)" warnings even though
+ // the assertions resolve correctly via waitFor().
+ await act(async () => {
+ controller.enqueue(encoder.encode(JSON.stringify(frame) + '\n'));
+ await Promise.resolve();
+ });
+ },
+ async enqueueRaw(text) {
+ await act(async () => {
+ controller.enqueue(encoder.encode(text));
+ await Promise.resolve();
+ });
+ },
+ async close() {
+ await act(async () => {
+ controller.close();
+ await Promise.resolve();
+ });
+ },
+ signal: () => opts.signalCapture.current,
+ };
+
+ return { response, handle };
+}
+
+const ALERT: Alert = {
+ id: 'ALERT-WS-D1-0001',
+ title: 'Impossible travel — login from Frankfurt then Tokyo',
+ severity: 'high',
+ source: 'okta',
+ status: 'new',
+ description: 'Account takeover suspected.',
+ tags: ['account-takeover'],
+ // The component strips `rawEvent`, so we include it to confirm.
+ rawEvent: { 'do-not': 'send' },
+ receivedAt: '2026-05-09T18:00:00Z',
+ mitreAttack: [{ techniqueId: 'T1078' }],
+ iocs: [{ type: 'ip', value: '203.0.113.42' }],
+ // The remaining fields don't matter for rendering but the type wants them.
+} as unknown as Alert;
+
+// ─── Tests ───────────────────────────────────────────────────────────────────
+
+describe('ExplainDrawer', () => {
+ beforeEach(() => {
+ explainStreamMock.mockReset();
+ });
+
+ it('returns null when closed', () => {
+ const { container } = render(
+ <ExplainDrawer open={false} onClose={vi.fn()} alert={ALERT} />,
+ );
+ // When closed the component renders nothing — no overlay, no aside.
+ expect(container.firstChild).toBeNull();
+ expect(explainStreamMock).not.toHaveBeenCalled();
+ });
+
+ it('renders header + sections as frames arrive and closes on done', async () => {
+ const signalRef: { current: AbortSignal | undefined } = { current: undefined };
+ const { response, handle } = buildMockStream({ signalCapture: signalRef });
+ explainStreamMock.mockImplementation(
+ async (_payload: unknown, signal?: AbortSignal) => {
+ signalRef.current = signal;
+ return response;
+ },
+ );
+
+ render(<ExplainDrawer open={true} onClose={vi.fn()} alert={ALERT} />);
+
+ // The drawer starts streaming immediately on open.
+ await waitFor(() => {
+ expect(explainStreamMock).toHaveBeenCalledTimes(1);
+ });
+
+ // Header surfaces alert metadata regardless of status.
+ expect(
+ screen.getByText(/Impossible travel/),
+ ).toBeInTheDocument();
+ expect(screen.getByText(/okta · high · ALERT-WS-D1-0001/)).toBeInTheDocument();
+
+ // The drawer trims `rawEvent` from the payload it sends to the backend.
+ const callArgs = explainStreamMock.mock.calls[0][0] as {
+ alert: Record<string, unknown>;
+ alertId: string;
+ };
+ expect(callArgs.alertId).toBe('ALERT-WS-D1-0001');
+ expect(callArgs.alert).toMatchObject({ id: 'ALERT-WS-D1-0001', source: 'okta' });
+ expect(callArgs.alert).not.toHaveProperty('rawEvent');
+
+ // Push a section header + summary deltas. The summary should render
+ // tokens as they arrive (this is the streaming UX).
+ await handle.enqueue({ kind: 'section', id: 'summary', title: 'What happened' });
+ await handle.enqueue({ kind: 'delta', section: 'summary', text: 'Two logins ' });
+ await handle.enqueue({ kind: 'delta', section: 'summary', text: 'from impossible distance.' });
+
+ await waitFor(() => {
+ expect(
+ screen.getByText('Two logins from impossible distance.'),
+ ).toBeInTheDocument();
+ });
+
+ // OCSF section.
+ await handle.enqueue({
+ kind: 'ocsf',
+ category: 'Identity & Access Management',
+ category_uid: 3,
+ class: 'Authentication',
+ class_uid: 3002,
+ activity: 'Logon',
+ fields: { 'actor.user.name': 'alice' },
+ });
+ await waitFor(() => {
+ expect(screen.getByText(/OCSF mapping/i)).toBeInTheDocument();
+ expect(screen.getByText(/Authentication \(3002\)/)).toBeInTheDocument();
+ // Field key + value should both render in the dl.
+ expect(screen.getByText('actor.user.name')).toBeInTheDocument();
+ expect(screen.getByText('alice')).toBeInTheDocument();
+ });
+
+ // MITRE — first card renders, then a duplicate ID is ignored.
+ await handle.enqueue({
+ kind: 'mitre',
+ id: 'T1078',
+ name: 'Valid Accounts',
+ tactic_names: ['Defense Evasion', 'Initial Access'],
+ description: 'Adversaries may obtain credentials.',
+ url: 'https://attack.mitre.org/techniques/T1078/',
+ found: true,
+ });
+ await handle.enqueue({
+ kind: 'mitre',
+ id: 'T1078',
+ name: 'Valid Accounts (DUP)',
+ tactic_names: [],
+ description: 'should not appear',
+ url: 'https://attack.mitre.org/techniques/T1078/',
+ found: true,
+ });
+ await waitFor(() => {
+ expect(screen.getAllByText('T1078')).toHaveLength(1);
+ expect(screen.getByText('Valid Accounts')).toBeInTheDocument();
+ });
+ expect(screen.queryByText('Valid Accounts (DUP)')).not.toBeInTheDocument();
+ expect(screen.queryByText('should not appear')).not.toBeInTheDocument();
+
+ // Evidence + next-step.
+ await handle.enqueue({
+ kind: 'evidence',
+ label: 'src_ip',
+ value: '203.0.113.42',
+ annotation: 'Frankfurt',
+ });
+ await handle.enqueue({
+ kind: 'next_step',
+ title: 'Force re-authentication',
+ rationale: 'Invalidate active sessions for this user.',
+ playbook_id: 'identity-compromise-v1',
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText('203.0.113.42')).toBeInTheDocument();
+ expect(screen.getByText('Force re-authentication')).toBeInTheDocument();
+ expect(screen.getByText('identity-compromise-v1')).toBeInTheDocument();
+ });
+
+ // Done frame flips status to "done" and surfaces the disclaimer.
+ await handle.enqueue({ kind: 'done', alert_id: 'ALERT-WS-D1-0001' });
+ await handle.close();
+
+ await waitFor(() => {
+ expect(screen.getByText('Done')).toBeInTheDocument();
+ expect(
+ screen.getByText(/Always verify before taking action/i),
+ ).toBeInTheDocument();
+ });
+ });
+
+ it('aborts the in-flight stream when the drawer closes', async () => {
+ const signalRef: { current: AbortSignal | undefined } = { current: undefined };
+ const { response, handle } = buildMockStream({ signalCapture: signalRef });
+ explainStreamMock.mockImplementation(
+ async (_payload: unknown, signal?: AbortSignal) => {
+ signalRef.current = signal;
+ return response;
+ },
+ );
+
+ const { rerender } = render(
+ <ExplainDrawer open={true} onClose={vi.fn()} alert={ALERT} />,
+ );
+
+ await waitFor(() => {
+ expect(explainStreamMock).toHaveBeenCalled();
+ expect(signalRef.current).toBeDefined();
+ });
+ expect(signalRef.current?.aborted).toBe(false);
+
+ // Close the drawer — the `useEffect` cleanup should hit `abortRef.abort()`.
+ rerender(<ExplainDrawer open={false} onClose={vi.fn()} alert={ALERT} />);
+
+ await waitFor(() => {
+ expect(signalRef.current?.aborted).toBe(true);
+ });
+
+ // Back-pressure check: the stream is still readable from our side, but
+ // the drawer no longer reads from it (drawer is unmounted-ish in the
+ // visual sense). Nothing else should crash if we close after.
+ await handle.close();
+ });
+
+ it('aborts the in-flight stream on unmount', async () => {
+ const signalRef: { current: AbortSignal | undefined } = { current: undefined };
+ const { response } = buildMockStream({ signalCapture: signalRef });
+ explainStreamMock.mockImplementation(
+ async (_payload: unknown, signal?: AbortSignal) => {
+ signalRef.current = signal;
+ return response;
+ },
+ );
+
+ const { unmount } = render(
+ <ExplainDrawer open={true} onClose={vi.fn()} alert={ALERT} />,
+ );
+
+ await waitFor(() => {
+ expect(signalRef.current).toBeDefined();
+ });
+
+ unmount();
+
+ await waitFor(() => {
+ expect(signalRef.current?.aborted).toBe(true);
+ });
+ });
+
+ it('shows an error banner + Retry button on HTTP non-2xx', async () => {
+ // Simulate the rate-limit response — body present, but status 429.
+ const signalRef: { current: AbortSignal | undefined } = { current: undefined };
+ const encoder = new TextEncoder();
+ const body = new ReadableStream<Uint8Array>({
+ start(c) {
+ c.enqueue(
+ encoder.encode(
+ JSON.stringify({
+ kind: 'error',
+ error: 'rate limit exceeded; retry in 30s',
+ }) + '\n',
+ ),
+ );
+ c.close();
+ },
+ });
+ const response = new Response(body, {
+ status: 429,
+ headers: {
+ 'Content-Type': 'application/x-ndjson',
+ 'Retry-After': '30',
+ },
+ });
+ explainStreamMock.mockImplementation(
+ async (_payload: unknown, signal?: AbortSignal) => {
+ signalRef.current = signal;
+ return response;
+ },
+ );
+
+ render(<ExplainDrawer open={true} onClose={vi.fn()} alert={ALERT} />);
+
+ await waitFor(() => {
+ expect(screen.getByText(/Explain endpoint returned HTTP 429/)).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument();
+ });
+
+ // Status badge should reflect the failure too.
+ expect(screen.getByText('Error')).toBeInTheDocument();
+ });
+
+ it('surfaces a backend NDJSON error frame on a 200 stream', async () => {
+ const signalRef: { current: AbortSignal | undefined } = { current: undefined };
+ const { response, handle } = buildMockStream({ signalCapture: signalRef });
+ explainStreamMock.mockImplementation(
+ async (_payload: unknown, signal?: AbortSignal) => {
+ signalRef.current = signal;
+ return response;
+ },
+ );
+
+ render(<ExplainDrawer open={true} onClose={vi.fn()} alert={ALERT} />);
+
+ await waitFor(() => {
+ expect(explainStreamMock).toHaveBeenCalled();
+ });
+
+ // Stream a partial summary, then an inline error — the drawer should
+ // halt and show the error rather than waiting for more frames.
+ await handle.enqueue({
+ kind: 'delta',
+ section: 'summary',
+ text: 'Investigating...',
+ });
+ await handle.enqueue({
+ kind: 'error',
+ error: 'OCSF mapper unavailable; partial result returned',
+ });
+ await handle.close();
+
+ await waitFor(() => {
+ expect(
+ screen.getByText('OCSF mapper unavailable; partial result returned'),
+ ).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument();
+ });
+ });
+
+ it('survives malformed NDJSON lines without breaking the stream', async () => {
+ const signalRef: { current: AbortSignal | undefined } = { current: undefined };
+ const { response, handle } = buildMockStream({ signalCapture: signalRef });
+ explainStreamMock.mockImplementation(
+ async (_payload: unknown, signal?: AbortSignal) => {
+ signalRef.current = signal;
+ return response;
+ },
+ );
+
+ render(<ExplainDrawer open={true} onClose={vi.fn()} alert={ALERT} />);
+ await waitFor(() => expect(explainStreamMock).toHaveBeenCalled());
+
+ // Push a junk line first, then valid content. The good frames must
+ // still render — silent drop on parse failure is the documented behavior.
+ await handle.enqueueRaw('this is not json\n');
+ await handle.enqueue({
+ kind: 'delta',
+ section: 'summary',
+ text: 'Recovered.',
+ });
+ await handle.enqueue({ kind: 'done', alert_id: 'ALERT-WS-D1-0001' });
+ await handle.close();
+
+ await waitFor(() => {
+ expect(screen.getByText('Recovered.')).toBeInTheDocument();
+ expect(screen.getByText('Done')).toBeInTheDocument();
+ });
+ });
+
+ it('handles NDJSON frames split mid-line across chunks', async () => {
+ const signalRef: { current: AbortSignal | undefined } = { current: undefined };
+ const { response, handle } = buildMockStream({ signalCapture: signalRef });
+ explainStreamMock.mockImplementation(
+ async (_payload: unknown, signal?: AbortSignal) => {
+ signalRef.current = signal;
+ return response;
+ },
+ );
+
+ render(<ExplainDrawer open={true} onClose={vi.fn()} alert={ALERT} />);
+ await waitFor(() => expect(explainStreamMock).toHaveBeenCalled());
+
+ // Classic backpressure split: half a frame, then the rest, then EOL.
+ // The buffer logic in startStream must stitch these together before
+ // JSON.parse, otherwise we'd lose summary text.
+ const fullLine = JSON.stringify({
+ kind: 'delta',
+ section: 'summary',
+ text: 'Hello world.',
+ });
+ const half = fullLine.slice(0, 18);
+ const rest = fullLine.slice(18);
+ await handle.enqueueRaw(half);
+ await handle.enqueueRaw(rest + '\n');
+ await handle.enqueue({ kind: 'done', alert_id: 'ALERT-WS-D1-0001' });
+ await handle.close();
+
+ await waitFor(() => {
+ expect(screen.getByText('Hello world.')).toBeInTheDocument();
+ });
+ });
+
+ it('fires onRunPlaybook with the playbook_id when "Run playbook" is clicked', async () => {
+ const signalRef: { current: AbortSignal | undefined } = { current: undefined };
+ const { response, handle } = buildMockStream({ signalCapture: signalRef });
+ explainStreamMock.mockImplementation(
+ async (_payload: unknown, signal?: AbortSignal) => {
+ signalRef.current = signal;
+ return response;
+ },
+ );
+
+ const onRunPlaybook = vi.fn();
+ const user = userEvent.setup();
+
+ render(
+ <ExplainDrawer
+ open={true}
+ onClose={vi.fn()}
+ alert={ALERT}
+ onRunPlaybook={onRunPlaybook}
+ />,
+ );
+
+ await handle.enqueue({
+ kind: 'next_step',
+ title: 'Force re-authentication',
+ rationale: 'Invalidate sessions.',
+ playbook_id: 'identity-compromise-v1',
+ });
+ await handle.enqueue({ kind: 'done', alert_id: 'ALERT-WS-D1-0001' });
+ await handle.close();
+
+ const runBtn = await screen.findByRole('button', { name: /Run playbook/i });
+ await user.click(runBtn);
+
+ expect(onRunPlaybook).toHaveBeenCalledWith('identity-compromise-v1');
+ });
+
+ it('closes when ESC is pressed', async () => {
+ const signalRef: { current: AbortSignal | undefined } = { current: undefined };
+ const { response } = buildMockStream({ signalCapture: signalRef });
+ explainStreamMock.mockImplementation(async () => response);
+
+ const onClose = vi.fn();
+ render(<ExplainDrawer open={true} onClose={onClose} alert={ALERT} />);
+
+ await waitFor(() => expect(explainStreamMock).toHaveBeenCalled());
+
+ const event = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true });
+ document.dispatchEvent(event);
+
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+
+ it('closes when the overlay is clicked', async () => {
+ const signalRef: { current: AbortSignal | undefined } = { current: undefined };
+ const { response } = buildMockStream({ signalCapture: signalRef });
+ explainStreamMock.mockImplementation(async () => response);
+
+ const onClose = vi.fn();
+ const user = userEvent.setup();
+ render(<ExplainDrawer open={true} onClose={onClose} alert={ALERT} />);
+
+ await waitFor(() => expect(explainStreamMock).toHaveBeenCalled());
+
+ // Both close affordances live behind aria-label="Close" — the overlay
+ // button (full-width) and the X button. We click the overlay one
+ // explicitly via testid-free lookup; clicking either works the same.
+ const closeButtons = screen.getAllByRole('button', { name: 'Close' });
+ expect(closeButtons.length).toBeGreaterThanOrEqual(1);
+ await user.click(closeButtons[0]);
+
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+
+ it('clicking Retry restarts the stream from a fresh idle state', async () => {
+ let attempt = 0;
+ const signalRefs: AbortSignal[] = [];
+
+ explainStreamMock.mockImplementation(async (_payload, signal?: AbortSignal) => {
+ attempt += 1;
+ if (signal) signalRefs.push(signal);
+ if (attempt === 1) {
+ // First attempt: 503.
+ return new Response('boom', { status: 503 });
+ }
+ // Second attempt: a clean stream with one delta then done.
+ const encoder = new TextEncoder();
+ const body = new ReadableStream<Uint8Array>({
+ start(c) {
+ c.enqueue(
+ encoder.encode(
+ JSON.stringify({
+ kind: 'delta',
+ section: 'summary',
+ text: 'Recovered after retry.',
+ }) + '\n',
+ ),
+ );
+ c.enqueue(
+ encoder.encode(
+ JSON.stringify({ kind: 'done', alert_id: ALERT.id }) + '\n',
+ ),
+ );
+ c.close();
+ },
+ });
+ return new Response(body, { status: 200 });
+ });
+
+ const user = userEvent.setup();
+ render(<ExplainDrawer open={true} onClose={vi.fn()} alert={ALERT} />);
+
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument();
+ });
+
+ await user.click(screen.getByRole('button', { name: 'Retry' }));
+
+ await waitFor(() => {
+ expect(screen.getByText('Recovered after retry.')).toBeInTheDocument();
+ expect(screen.getByText('Done')).toBeInTheDocument();
+ });
+ expect(attempt).toBe(2);
+ expect(signalRefs).toHaveLength(2);
+ });
+});
diff --git a/services/agents/app/api/explain.py b/services/agents/app/api/explain.py
index 3243c8271..a8c14abd0 100644
--- a/services/agents/app/api/explain.py
+++ b/services/agents/app/api/explain.py
@@ -32,6 +32,37 @@ When the LLM path is skipped, the deterministic synthesizer fills the
``summary`` section from the alert payload itself, so the demo path
never breaks.
+Rate limiting
+-------------
+
+Every explain request can fan out to one outbound LLM call, so a noisy
+client (or a hostile script hammering Explain across every alert in
+the grid) would burn token budget and stall every other analyst's
+drawer behind queued LLM calls. We use a per-tenant token bucket
+(``services/agents/app/core/rate_limit.py``):
+
+* ``AISOC_EXPLAIN_BURST`` — bucket capacity (default 20)
+* ``AISOC_EXPLAIN_RPM`` — refill, requests per minute (default 60).
+ Set to ``0`` to disable the limiter
+ entirely (used in tests and demos).
+
+When the bucket is empty we return HTTP 429 with ``Retry-After`` and
+the standard ``X-RateLimit-*`` headers, *and* emit a single NDJSON
+``error`` frame so an EventSource-style client that has already
+started reading still gets a structured failure to render.
+
+BYOK / per-tenant LLM overrides
+-------------------------------
+
+Per-tenant API-key overrides (Bring-Your-Own-Key) are explicitly
+deferred to v1.1 — the live snapshot is documented in
+``services/api/app/api/v1/endpoints/llm_status.py``. v1 honours a
+single process-wide configuration (``OPENAI_API_KEY`` /
+``OPENAI_BASE_URL`` / ``AISOC_AIRGAPPED``) so we don't ship a half-
+finished credential model that we'd later need to migrate. Tenant ID
+is still recorded on every request so the v1.1 cutover is purely a
+code change, not a data migration.
+
NDJSON frame shapes
-------------------
@@ -69,15 +100,82 @@ from collections.abc import AsyncIterator
from typing import Any
import structlog
-from fastapi import APIRouter
+from fastapi import APIRouter, Request
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
+from app.core.rate_limit import RateLimitDecision, TokenBucketLimiter
+
logger = structlog.get_logger()
router = APIRouter(prefix="/api/v1", tags=["explain"])
+# ---------------------------------------------------------------------------
+# Rate limiter (per-tenant token bucket)
+# ---------------------------------------------------------------------------
+#
+# Lazy-initialised at first request so the env vars can be patched per-test
+# without paying the cost of touching ``time.monotonic`` at import time.
+# A value of 0 for ``AISOC_EXPLAIN_RPM`` short-circuits the limiter
+# entirely — useful for the deterministic eval harness, where we want to
+# stream the same 200 incidents back-to-back without throttling noise.
+
+_DEFAULT_BURST = 20
+_DEFAULT_RPM = 60
+
+_explain_limiter: TokenBucketLimiter | None = None
+
+
+def _get_explain_limiter() -> TokenBucketLimiter | None:
+ """Return the process-wide explain limiter, or ``None`` if disabled.
+
+ We re-read the env vars only on first construction; subsequent
+ calls return the cached singleton. Tests that need a fresh
+ limiter call :func:`_reset_explain_limiter` first.
+ """
+ global _explain_limiter
+ if _explain_limiter is not None:
+ return _explain_limiter
+ try:
+ rpm = int(os.environ.get("AISOC_EXPLAIN_RPM", _DEFAULT_RPM))
+ burst = int(os.environ.get("AISOC_EXPLAIN_BURST", _DEFAULT_BURST))
+ except ValueError:
+ rpm, burst = _DEFAULT_RPM, _DEFAULT_BURST
+ if rpm <= 0 or burst <= 0:
+ return None
+ _explain_limiter = TokenBucketLimiter(
+ capacity=float(burst),
+ refill_per_second=rpm / 60.0,
+ )
+ return _explain_limiter
+
+
+def _reset_explain_limiter() -> None:
+ """Drop the cached limiter — used by tests to pick up env changes."""
+ global _explain_limiter
+ _explain_limiter = None
+
+
+def _rate_limit_key(req: ExplainRequest, request: Request | None) -> str:
+ """Compose the bucket key for a request.
+
+ Prefer the body-supplied tenant_id (fairness across analysts on
+ the same tenant), fall back to client IP (hygiene against
+ unauthenticated abuse). The agents service runs behind a reverse
+ proxy in production, but ``request.client.host`` is good enough
+ for in-process throttling — proxy spoofing only changes which
+ bucket gets drained, never lets a caller bypass the bucket.
+ """
+ tenant = (req.tenant_id or "").strip()
+ if tenant and tenant != "default":
+ return f"tenant:{tenant}"
+ ip = "unknown"
+ if request is not None and request.client is not None:
+ ip = request.client.host or "unknown"
+ return f"ip:{ip}"
+
+
# ---------------------------------------------------------------------------
# Request shape
# ---------------------------------------------------------------------------
@@ -591,9 +689,48 @@ async def _stream_explanation(req: ExplainRequest) -> AsyncIterator[bytes]:
@router.post("/explain")
-async def explain(req: ExplainRequest) -> StreamingResponse:
- """Stream an OCSF + MITRE-grounded explanation of an alert as NDJSON."""
+async def explain(req: ExplainRequest, request: Request) -> StreamingResponse:
+ """Stream an OCSF + MITRE-grounded explanation of an alert as NDJSON.
+
+ Each request consumes one token from a per-tenant bucket (see the
+ "Rate limiting" section in the module docstring). When the bucket
+ is empty we return HTTP 429 — *not* a 200 with an error frame —
+ so generic HTTP clients and reverse proxies see a real
+ throttle. The body is still NDJSON so an SSE/EventSource client
+ that ignores status codes still gets a structured failure.
+ """
+ limiter = _get_explain_limiter()
+ decision: RateLimitDecision | None = None
+ if limiter is not None:
+ key = _rate_limit_key(req, request)
+ decision = await limiter.acquire(key)
+ if not decision.allowed:
+ logger.info(
+ "explain.rate_limited",
+ key=key,
+ retry_after=decision.retry_after_seconds,
+ remaining=decision.remaining,
+ )
+ headers = decision.to_headers()
+ body = _frame(
+ {
+ "kind": "error",
+ "error": (
+ "rate_limited: too many explain requests for this tenant; "
+ f"retry after ~{int(decision.retry_after_seconds + 0.999)}s"
+ ),
+ }
+ )
+ return StreamingResponse(
+ iter([body]),
+ media_type="application/x-ndjson",
+ status_code=429,
+ headers=headers,
+ )
+
+ response_headers = decision.to_headers() if decision is not None else None
return StreamingResponse(
_stream_explanation(req),
media_type="application/x-ndjson",
+ headers=response_headers,
)
diff --git a/services/agents/app/core/rate_limit.py b/services/agents/app/core/rate_limit.py
new file mode 100644
index 000000000..568ba9608
--- /dev/null
+++ b/services/agents/app/core/rate_limit.py
@@ -0,0 +1,164 @@
+"""Per-key token-bucket rate limiter for the agents service.
+
+This is a stripped-down sibling of ``services/api/app/services/lake_rate_limit.py``.
+We can't share the module across services without inventing a shared
+package, but we keep the algorithm and the public surface deliberately
+identical so a future ``packages/sdk-py`` can consolidate them.
+
+Why a token bucket here
+-----------------------
+
+The ``/api/v1/explain`` endpoint can fan out to an outbound LLM call per
+request. A noisy frontend (or a hostile script) hammering Explain
+against every alert in the grid would burn token budget and stall every
+other analyst's drawer behind the queued LLM calls.
+
+Token buckets give us:
+
+* Fast cold-start behaviour — an analyst opening Explain ten times in
+ ten seconds while triaging is still well under burst capacity.
+* Smooth steady-state pressure — a runaway loop is throttled to the
+ refill rate, not "the next minute window".
+* O(1) per-request cost — no Redis round trip on the hot path.
+
+In-memory, per-process. Acceptable for v1 because we ship a single
+agents pod by default; documented in the PROGRESS log so that the day
+we horizontally scale we either move to Redis or accept the under-
+enforcement-by-N-pods factor.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import time
+from dataclasses import dataclass, field
+
+
+@dataclass
+class _TokenBucket:
+ """One key's bucket. Refills lazily on each acquire."""
+
+ capacity: float
+ refill_per_second: float
+ tokens: float = field(default=0.0)
+ last_refill: float = field(default_factory=time.monotonic)
+ lock: asyncio.Lock = field(default_factory=asyncio.Lock)
+
+ def __post_init__(self) -> None:
+ # Start full so the first request from a key always succeeds —
+ # we throttle sustained load, not cold starts.
+ if self.tokens <= 0.0 or self.tokens > self.capacity:
+ self.tokens = self.capacity
+
+ def _refill(self, now: float) -> None:
+ elapsed = max(0.0, now - self.last_refill)
+ if elapsed > 0.0:
+ self.tokens = min(
+ self.capacity, self.tokens + elapsed * self.refill_per_second
+ )
+ self.last_refill = now
+
+
+@dataclass(frozen=True)
+class RateLimitDecision:
+ """Outcome of an :meth:`TokenBucketLimiter.acquire` attempt."""
+
+ allowed: bool
+ remaining: float
+ capacity: float
+ retry_after_seconds: float
+
+ def to_headers(self) -> dict[str, str]:
+ """Render the de-facto ``X-RateLimit-*`` family.
+
+ Matches the lake limiter so operator dashboards parse one set
+ of headers across services.
+ """
+ headers = {
+ "X-RateLimit-Limit": f"{int(self.capacity)}",
+ "X-RateLimit-Remaining": f"{max(0, int(self.remaining))}",
+ }
+ if not self.allowed:
+ # RFC 7231 §7.1.3 — non-negative integer seconds. Round up
+ # so a client that retries exactly at Retry-After doesn't
+ # bounce off the bucket again.
+ headers["Retry-After"] = (
+ f"{max(1, int(self.retry_after_seconds + 0.999))}"
+ )
+ return headers
+
+
+class TokenBucketLimiter:
+ """Process-wide, key-scoped token-bucket limiter.
+
+ The key is opaque — the explain endpoint uses ``tenant_id`` (or
+ falls back to client IP for unauthenticated traffic). Other callers
+ can use whatever scoping they need.
+ """
+
+ def __init__(self, *, capacity: float, refill_per_second: float) -> None:
+ if capacity <= 0:
+ raise ValueError("capacity must be positive")
+ if refill_per_second <= 0:
+ raise ValueError("refill_per_second must be positive")
+ self._capacity = capacity
+ self._refill_per_second = refill_per_second
+ self._buckets: dict[str, _TokenBucket] = {}
+ self._registry_lock = asyncio.Lock()
+
+ async def acquire(self, key: str, *, cost: float = 1.0) -> RateLimitDecision:
+ """Try to consume ``cost`` tokens for ``key``.
+
+ Never raises on the rate-limited path; the caller decides how
+ to surface the 429 (FastAPI ``HTTPException`` with headers, or
+ a structured NDJSON error frame).
+ """
+ if cost <= 0:
+ raise ValueError("cost must be positive")
+ if cost > self._capacity:
+ raise ValueError(
+ f"cost {cost} exceeds bucket capacity {self._capacity}; "
+ "this would never succeed"
+ )
+
+ bucket = await self._get_bucket(key)
+ async with bucket.lock:
+ now = time.monotonic()
+ bucket._refill(now)
+ if bucket.tokens >= cost:
+ bucket.tokens -= cost
+ return RateLimitDecision(
+ allowed=True,
+ remaining=bucket.tokens,
+ capacity=self._capacity,
+ retry_after_seconds=0.0,
+ )
+ shortfall = cost - bucket.tokens
+ return RateLimitDecision(
+ allowed=False,
+ remaining=bucket.tokens,
+ capacity=self._capacity,
+ retry_after_seconds=shortfall / self._refill_per_second,
+ )
+
+ async def reset(self, key: str | None = None) -> None:
+ """Drop one bucket or the whole registry. Used by tests."""
+ async with self._registry_lock:
+ if key is None:
+ self._buckets.clear()
+ else:
+ self._buckets.pop(key, None)
+
+ async def _get_bucket(self, key: str) -> _TokenBucket:
+ bucket = self._buckets.get(key)
+ if bucket is not None:
+ return bucket
+ async with self._registry_lock:
+ bucket = self._buckets.get(key)
+ if bucket is None:
+ bucket = _TokenBucket(
+ capacity=self._capacity,
+ refill_per_second=self._refill_per_second,
+ )
+ self._buckets[key] = bucket
+ return bucket
diff --git a/services/agents/tests/test_explain_endpoint.py b/services/agents/tests/test_explain_endpoint.py
new file mode 100644
index 000000000..1cb8ca7d8
--- /dev/null
+++ b/services/agents/tests/test_explain_endpoint.py
@@ -0,0 +1,333 @@
+"""Integration tests for ``POST /api/v1/explain`` (WS-D1).
+
+We mount *only* the explain router into a fresh FastAPI app so the test
+suite does not pull in the heavyweight ``services/agents/app/main.py``
+lifespan (LangGraph, model loaders, MITRE corpus prefetch, etc.). The
+LLM is forced off via ``AISOC_AIRGAPPED=true`` and a missing
+``OPENAI_API_KEY`` so every stream is deterministic.
+
+Each test resets the module-level explain-limiter singleton via
+:func:`_reset_explain_limiter` so env-var-driven config changes take
+effect for the next request.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from pathlib import Path
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+# ----- import path setup ---------------------------------------------------
+
+_AGENTS_ROOT = Path(__file__).resolve().parents[1]
+if str(_AGENTS_ROOT) not in sys.path:
+ sys.path.insert(0, str(_AGENTS_ROOT))
+
+# Force the LLM off *before* importing app.api.explain so its module-level
+# default ladder is consistent with what the tests assume.
+os.environ.pop("OPENAI_API_KEY", None)
+os.environ["AISOC_AIRGAPPED"] = "true"
+
+from app.api.explain import ( # noqa: E402
+ _frame,
+ _reset_explain_limiter,
+ router as explain_router,
+)
+
+# ----- shared fixtures ------------------------------------------------------
+
+
+SAMPLE_ALERT: dict[str, Any] = {
+ "id": "ALERT-TEST-0001",
+ "title": "Impossible travel — login from Frankfurt then Tokyo within 8 minutes",
+ "severity": "high",
+ "source": "okta",
+ "description": (
+ "User authenticated successfully from two geographically impossible "
+ "locations within an 8-minute window. Likely account takeover."
+ ),
+ "tags": ["account-takeover", "ato", "identity"],
+ "mitreAttack": [{"techniqueId": "T1078"}],
+ "iocs": [
+ {"type": "ip", "value": "203.0.113.42"},
+ {"type": "ip", "value": "198.51.100.7"},
+ ],
+ "rawEvent": {
+ "user_name": "alice.tan",
+ "src_ip": "203.0.113.42",
+ "hostname": "okta-prod",
+ },
+}
+
+
+def _build_app() -> FastAPI:
+ """Construct a fresh FastAPI app with only the explain router mounted."""
+ _reset_explain_limiter()
+ app = FastAPI()
+ app.include_router(explain_router)
+ return app
+
+
+def _parse_ndjson(body: str) -> list[dict[str, Any]]:
+ out: list[dict[str, Any]] = []
+ for line in body.splitlines():
+ line = line.strip()
+ if not line:
+ continue
+ out.append(json.loads(line))
+ return out
+
+
[email protected](autouse=True)
+def _isolate_limiter_state() -> Any:
+ """Reset the explain limiter singleton before and after every test.
+
+ Env vars are restored automatically by ``monkeypatch``; the singleton
+ is process-wide and outlives the env scope, so we drop it explicitly.
+ """
+ _reset_explain_limiter()
+ yield
+ _reset_explain_limiter()
+
+
+# ---------------------------------------------------------------------------
+# Happy path — full stream contract
+# ---------------------------------------------------------------------------
+
+
+def test_explain_streams_grounded_ndjson(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Verify the full WS-D1 frame contract on a representative ATO alert.
+
+ Asserts:
+ * HTTP 200 + ``application/x-ndjson`` content-type
+ * ``X-RateLimit-*`` headers present and consistent with config
+ * Section ordering: summary → ocsf → mitre → evidence → next
+ * Last frame is ``done`` and echoes the alert id
+ * Okta-sourced alert maps to OCSF Authentication (class_uid=3002)
+ * MITRE T1078 emitted with a valid attack.mitre.org URL
+ * ATO-tagged alert recommends ``ato-impossible-travel-block-v1``
+ * Evidence frame surfaces the user from ``rawEvent``
+ """
+ monkeypatch.setenv("AISOC_EXPLAIN_RPM", "120")
+ monkeypatch.setenv("AISOC_EXPLAIN_BURST", "60")
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+ monkeypatch.setenv("AISOC_AIRGAPPED", "true")
+
+ client = TestClient(_build_app())
+ response = client.post(
+ "/api/v1/explain",
+ json={
+ "alert": SAMPLE_ALERT,
+ "alert_id": SAMPLE_ALERT["id"],
+ "tenant_id": "tenant-a",
+ },
+ )
+
+ assert response.status_code == 200, response.text
+ assert response.headers["content-type"].startswith("application/x-ndjson")
+ assert int(response.headers["X-RateLimit-Limit"]) == 60
+ # First request consumes one token.
+ assert int(response.headers["X-RateLimit-Remaining"]) == 59
+ assert "Retry-After" not in response.headers
+
+ frames = _parse_ndjson(response.text)
+ assert frames, "expected at least one NDJSON frame"
+
+ last = frames[-1]
+ assert last["kind"] == "done", f"expected 'done' last, got {last}"
+ assert last["alert_id"] == "ALERT-TEST-0001"
+
+ # Section ordering — explicit and stable so the frontend can rely on it.
+ section_ids = [f["id"] for f in frames if f["kind"] == "section"]
+ assert section_ids == ["summary", "ocsf", "mitre", "evidence", "next"], (
+ f"unexpected section order: {section_ids}"
+ )
+
+ # OCSF mapping: Okta source → Authentication (class_uid 3002).
+ ocsf = next((f for f in frames if f["kind"] == "ocsf"), None)
+ assert ocsf is not None, "no ocsf frame emitted"
+ assert ocsf["class_uid"] == 3002
+
+ # MITRE: T1078 with valid attack.mitre.org URL.
+ mitre = [f for f in frames if f["kind"] == "mitre"]
+ assert any(m["id"] == "T1078" for m in mitre), (
+ f"expected T1078, got {[m['id'] for m in mitre]}"
+ )
+ for m in mitre:
+ assert m["url"].startswith("https://attack.mitre.org/techniques/")
+
+ # ATO tag pulls in the impossible-travel-block playbook.
+ next_steps = [f for f in frames if f["kind"] == "next_step"]
+ assert any(s["playbook_id"] == "ato-impossible-travel-block-v1" for s in next_steps)
+
+ # Evidence surfaces the offending user from rawEvent.
+ evidence = [f for f in frames if f["kind"] == "evidence"]
+ assert any("alice.tan" in e["value"] for e in evidence), (
+ f"evidence missing user from rawEvent: "
+ f"{[(e['label'], e['value']) for e in evidence]}"
+ )
+
+
+def test_explain_uses_default_tenant_when_omitted(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Omitting ``tenant_id`` must still produce a valid stream.
+
+ The body model defaults ``tenant_id`` to ``"default"`` which the
+ rate-limit-key resolver explicitly treats as "no tenant — fall back
+ to client IP", so the call must not 500 on a missing field.
+ """
+ monkeypatch.setenv("AISOC_EXPLAIN_RPM", "120")
+ monkeypatch.setenv("AISOC_EXPLAIN_BURST", "60")
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+ monkeypatch.setenv("AISOC_AIRGAPPED", "true")
+
+ client = TestClient(_build_app())
+ response = client.post(
+ "/api/v1/explain",
+ json={"alert": SAMPLE_ALERT, "alert_id": SAMPLE_ALERT["id"]},
+ )
+ assert response.status_code == 200, response.text
+ frames = _parse_ndjson(response.text)
+ assert frames[-1]["kind"] == "done"
+
+
+# ---------------------------------------------------------------------------
+# Rate limiting
+# ---------------------------------------------------------------------------
+
+
+def test_explain_throttles_with_429_and_ndjson_error_frame(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Tenant exceeds bucket → second call returns 429 + structured error.
+
+ Capacity=1 with a tiny refill rate guarantees the second call within
+ the same test is denied. The 429 body must be a single NDJSON
+ ``error`` frame so SSE/EventSource clients that ignore HTTP status
+ still see a structured failure.
+ """
+ monkeypatch.setenv("AISOC_EXPLAIN_RPM", "1")
+ monkeypatch.setenv("AISOC_EXPLAIN_BURST", "1")
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+ monkeypatch.setenv("AISOC_AIRGAPPED", "true")
+
+ client = TestClient(_build_app())
+ body = {
+ "alert": SAMPLE_ALERT,
+ "alert_id": SAMPLE_ALERT["id"],
+ "tenant_id": "tenant-a",
+ }
+
+ first = client.post("/api/v1/explain", json=body)
+ assert first.status_code == 200, first.text
+
+ second = client.post("/api/v1/explain", json=body)
+ assert second.status_code == 429, second.text
+ assert second.headers["content-type"].startswith("application/x-ndjson")
+ assert int(second.headers["X-RateLimit-Limit"]) == 1
+ assert int(second.headers["X-RateLimit-Remaining"]) == 0
+ # Retry-After must be a non-negative integer ≥ 1 (rounded up).
+ retry = int(second.headers["Retry-After"])
+ assert retry >= 1
+
+ frames = _parse_ndjson(second.text)
+ assert len(frames) == 1, (
+ f"429 body must be a single NDJSON error frame, got {len(frames)}"
+ )
+ assert frames[0]["kind"] == "error"
+ assert "rate_limited" in frames[0]["error"]
+
+
+def test_explain_buckets_are_per_tenant(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Draining tenant-a's bucket must not throttle tenant-b."""
+ monkeypatch.setenv("AISOC_EXPLAIN_RPM", "1")
+ monkeypatch.setenv("AISOC_EXPLAIN_BURST", "1")
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+ monkeypatch.setenv("AISOC_AIRGAPPED", "true")
+
+ client = TestClient(_build_app())
+
+ drain = client.post(
+ "/api/v1/explain",
+ json={"alert": SAMPLE_ALERT, "tenant_id": "tenant-a"},
+ )
+ assert drain.status_code == 200
+ deny = client.post(
+ "/api/v1/explain",
+ json={"alert": SAMPLE_ALERT, "tenant_id": "tenant-a"},
+ )
+ assert deny.status_code == 429
+
+ # tenant-b is fresh — its bucket has not been touched.
+ fresh = client.post(
+ "/api/v1/explain",
+ json={"alert": SAMPLE_ALERT, "tenant_id": "tenant-b"},
+ )
+ assert fresh.status_code == 200, fresh.text
+
+
+def test_explain_limiter_disabled_when_rpm_zero(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """``AISOC_EXPLAIN_RPM=0`` is the documented opt-out for self-hosters."""
+ monkeypatch.setenv("AISOC_EXPLAIN_RPM", "0")
+ monkeypatch.setenv("AISOC_EXPLAIN_BURST", "0")
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+ monkeypatch.setenv("AISOC_AIRGAPPED", "true")
+
+ client = TestClient(_build_app())
+ response = client.post(
+ "/api/v1/explain",
+ json={"alert": SAMPLE_ALERT, "tenant_id": "tenant-a"},
+ )
+ assert response.status_code == 200
+ assert "X-RateLimit-Limit" not in response.headers
+ assert "X-RateLimit-Remaining" not in response.headers
+ assert "Retry-After" not in response.headers
+
+
+def test_explain_limiter_handles_invalid_env_values(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Garbage env values must fall back to defaults, not crash startup."""
+ monkeypatch.setenv("AISOC_EXPLAIN_RPM", "not-a-number")
+ monkeypatch.setenv("AISOC_EXPLAIN_BURST", "also-bad")
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+ monkeypatch.setenv("AISOC_AIRGAPPED", "true")
+
+ client = TestClient(_build_app())
+ response = client.post(
+ "/api/v1/explain",
+ json={"alert": SAMPLE_ALERT, "tenant_id": "tenant-a"},
+ )
+ assert response.status_code == 200, response.text
+ # Defaults kick in → headers are present and the limit > 0.
+ assert int(response.headers["X-RateLimit-Limit"]) > 0
+
+
+# ---------------------------------------------------------------------------
+# Frame helpers
+# ---------------------------------------------------------------------------
+
+
+def test_frame_emits_newline_terminated_json() -> None:
+ """``_frame`` must produce one NDJSON record terminated with ``\\n``."""
+ out = _frame({"kind": "delta", "section": "summary", "text": "hello "})
+ assert isinstance(out, bytes)
+ assert out.endswith(b"\n")
+ parsed = json.loads(out.decode().strip())
+ assert parsed == {"kind": "delta", "section": "summary", "text": "hello "}
+
+
+def test_frame_handles_unicode() -> None:
+ """Frames must serialise non-ASCII chars without surrogate errors."""
+ out = _frame({"kind": "delta", "section": "summary", "text": "naïve résumé "})
+ parsed = json.loads(out.decode().strip())
+ assert parsed["text"] == "naïve résumé "
diff --git a/services/agents/tests/test_rate_limit.py b/services/agents/tests/test_rate_limit.py
new file mode 100644
index 000000000..b66c7390f
--- /dev/null
+++ b/services/agents/tests/test_rate_limit.py
@@ -0,0 +1,262 @@
+"""Unit tests for the per-key token-bucket limiter used by /api/v1/explain.
+
+These tests exercise the limiter directly so we can prove the algorithm
+without dragging in FastAPI, structlog, or the explain endpoint. Endpoint-
+level assertions (correct headers, 429 status, NDJSON error frame) live in
+``test_explain_endpoint.py``.
+
+Time control
+------------
+Most assertions don't need a fake clock — the algorithm is deterministic
+once the bucket is constructed. The refill test uses a *very* short real
+sleep (≤25 ms) instead of monkeypatching ``time.monotonic`` because the
+dataclass captures the real function in ``default_factory`` at class
+definition, so patching the module's ``time`` symbol doesn't reach the
+bucket's ``last_refill`` initialiser. Real-time sleeps keep the test
+honest and avoid a brittle "patch everything" setup.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import sys
+from pathlib import Path
+
+import pytest
+
+_AGENTS_ROOT = Path(__file__).resolve().parents[1]
+if str(_AGENTS_ROOT) not in sys.path:
+ sys.path.insert(0, str(_AGENTS_ROOT))
+
+from app.core.rate_limit import ( # noqa: E402
+ RateLimitDecision,
+ TokenBucketLimiter,
+ _TokenBucket,
+)
+
+
+# ---------------------------------------------------------------------------
+# RateLimitDecision.to_headers
+# ---------------------------------------------------------------------------
+
+
+def test_to_headers_allowed_omits_retry_after() -> None:
+ decision = RateLimitDecision(
+ allowed=True, remaining=4.5, capacity=10.0, retry_after_seconds=0.0
+ )
+ headers = decision.to_headers()
+ assert headers == {"X-RateLimit-Limit": "10", "X-RateLimit-Remaining": "4"}
+ assert "Retry-After" not in headers
+
+
+def test_to_headers_denied_rounds_retry_after_up() -> None:
+ decision = RateLimitDecision(
+ allowed=False, remaining=0.0, capacity=20.0, retry_after_seconds=0.001
+ )
+ headers = decision.to_headers()
+ # 0.001s rounds up to 1 second so a client that retries at Retry-After
+ # doesn't bounce off the bucket again.
+ assert headers["Retry-After"] == "1"
+ assert headers["X-RateLimit-Limit"] == "20"
+ assert headers["X-RateLimit-Remaining"] == "0"
+
+
+def test_to_headers_denied_retry_after_handles_partial_seconds() -> None:
+ decision = RateLimitDecision(
+ allowed=False, remaining=0.3, capacity=5.0, retry_after_seconds=2.4
+ )
+ headers = decision.to_headers()
+ # 2.4 + 0.999 -> int -> 3
+ assert headers["Retry-After"] == "3"
+
+
+# ---------------------------------------------------------------------------
+# Construction guards
+# ---------------------------------------------------------------------------
+
+
+def test_capacity_must_be_positive() -> None:
+ with pytest.raises(ValueError, match="capacity must be positive"):
+ TokenBucketLimiter(capacity=0, refill_per_second=1.0)
+ with pytest.raises(ValueError, match="capacity must be positive"):
+ TokenBucketLimiter(capacity=-1.0, refill_per_second=1.0)
+
+
+def test_refill_must_be_positive() -> None:
+ with pytest.raises(ValueError, match="refill_per_second must be positive"):
+ TokenBucketLimiter(capacity=5.0, refill_per_second=0)
+ with pytest.raises(ValueError, match="refill_per_second must be positive"):
+ TokenBucketLimiter(capacity=5.0, refill_per_second=-1.0)
+
+
+# ---------------------------------------------------------------------------
+# acquire()
+# ---------------------------------------------------------------------------
+
+
+async def test_first_request_starts_full() -> None:
+ """A fresh bucket starts full so cold-start UX is not punished."""
+ limiter = TokenBucketLimiter(capacity=3.0, refill_per_second=1.0)
+ decision = await limiter.acquire("tenant:a")
+ assert decision.allowed is True
+ assert decision.capacity == 3.0
+ # Started at capacity 3, consumed 1 → 2 remaining.
+ assert decision.remaining == pytest.approx(2.0)
+ assert decision.retry_after_seconds == 0.0
+
+
+async def test_each_acquire_decrements_one_token() -> None:
+ # Use a near-zero refill so the natural sub-millisecond drift between
+ # rapid acquires can't tip ``remaining`` above the integer we expect.
+ limiter = TokenBucketLimiter(capacity=3.0, refill_per_second=0.0001)
+ for expected_remaining in (2.0, 1.0, 0.0):
+ decision = await limiter.acquire("tenant:a")
+ assert decision.allowed is True
+ assert decision.remaining == pytest.approx(expected_remaining, abs=1e-3)
+
+
+async def test_exhausted_bucket_denies_with_retry_after() -> None:
+ limiter = TokenBucketLimiter(capacity=2.0, refill_per_second=4.0)
+ # Drain the bucket.
+ await limiter.acquire("tenant:a")
+ await limiter.acquire("tenant:a")
+ # Third call is throttled.
+ decision = await limiter.acquire("tenant:a")
+ assert decision.allowed is False
+ # remaining should be < 1.0 after two drains and barely-any-refill.
+ assert decision.remaining < 1.0
+ # shortfall=1-tokens, refill=4/s, so retry_after ≈ shortfall/4 ≤ 0.25s.
+ assert 0.0 < decision.retry_after_seconds <= 0.25
+
+
+async def test_independent_buckets_per_key() -> None:
+ """Tenant A draining its bucket must not affect tenant B."""
+ limiter = TokenBucketLimiter(capacity=1.0, refill_per_second=1.0)
+ a1 = await limiter.acquire("tenant:a")
+ a2 = await limiter.acquire("tenant:a")
+ b1 = await limiter.acquire("tenant:b")
+ assert a1.allowed is True
+ assert a2.allowed is False # tenant:a drained
+ assert b1.allowed is True # tenant:b is fresh
+
+
+async def test_refill_after_real_time_passes() -> None:
+ """Tokens refill at the configured rate.
+
+ We use a high refill rate so the test stays quick. With 100 tokens/sec
+ and a 30 ms sleep we expect ~3 tokens back, which is more than enough
+ to flip the next acquire from denied to allowed.
+ """
+ limiter = TokenBucketLimiter(capacity=1.0, refill_per_second=100.0)
+ first = await limiter.acquire("tenant:a")
+ assert first.allowed is True
+ second = await limiter.acquire("tenant:a")
+ assert second.allowed is False
+ # Wait long enough for the bucket to refill at least one token.
+ await asyncio.sleep(0.03)
+ third = await limiter.acquire("tenant:a")
+ assert third.allowed is True
+
+
+async def test_refill_caps_at_capacity() -> None:
+ """A bucket sitting idle for a long time must not exceed its capacity."""
+ limiter = TokenBucketLimiter(capacity=2.0, refill_per_second=1000.0)
+ # Drain the bucket.
+ await limiter.acquire("tenant:a")
+ await limiter.acquire("tenant:a")
+ # Sleep long enough to refill thousands of tokens at the configured
+ # rate; remaining must still cap at capacity-1 after the next acquire.
+ await asyncio.sleep(0.05)
+ decision = await limiter.acquire("tenant:a")
+ assert decision.allowed is True
+ # After refill capping at 2 then consuming 1, ≤1 token is left.
+ assert decision.remaining <= 1.0
+
+
+async def test_acquire_with_zero_or_negative_cost_rejected() -> None:
+ limiter = TokenBucketLimiter(capacity=5.0, refill_per_second=1.0)
+ with pytest.raises(ValueError, match="cost must be positive"):
+ await limiter.acquire("tenant:a", cost=0)
+ with pytest.raises(ValueError, match="cost must be positive"):
+ await limiter.acquire("tenant:a", cost=-1.0)
+
+
+async def test_acquire_with_cost_above_capacity_rejected() -> None:
+ """A request that could never succeed is a programming bug, not a 429."""
+ limiter = TokenBucketLimiter(capacity=2.0, refill_per_second=1.0)
+ with pytest.raises(ValueError, match="exceeds bucket capacity"):
+ await limiter.acquire("tenant:a", cost=3.0)
+
+
+async def test_custom_cost_drains_bucket() -> None:
+ limiter = TokenBucketLimiter(capacity=10.0, refill_per_second=1.0)
+ decision = await limiter.acquire("tenant:a", cost=4.0)
+ assert decision.allowed is True
+ assert decision.remaining == pytest.approx(6.0)
+
+
+# ---------------------------------------------------------------------------
+# reset()
+# ---------------------------------------------------------------------------
+
+
+async def test_reset_specific_key_only_clears_that_key() -> None:
+ limiter = TokenBucketLimiter(capacity=1.0, refill_per_second=1.0)
+ # Drain both keys.
+ await limiter.acquire("tenant:a")
+ await limiter.acquire("tenant:b")
+ # Confirm both are throttled.
+ assert (await limiter.acquire("tenant:a")).allowed is False
+ assert (await limiter.acquire("tenant:b")).allowed is False
+ # Reset only tenant:a.
+ await limiter.reset("tenant:a")
+ assert (await limiter.acquire("tenant:a")).allowed is True
+ # tenant:b is still throttled (its bucket was not reset).
+ assert (await limiter.acquire("tenant:b")).allowed is False
+
+
+async def test_reset_all_clears_every_bucket() -> None:
+ limiter = TokenBucketLimiter(capacity=1.0, refill_per_second=1.0)
+ await limiter.acquire("tenant:a")
+ await limiter.acquire("tenant:b")
+ await limiter.reset() # nuke everything
+ assert (await limiter.acquire("tenant:a")).allowed is True
+ assert (await limiter.acquire("tenant:b")).allowed is True
+
+
+# ---------------------------------------------------------------------------
+# Concurrency
+# ---------------------------------------------------------------------------
+
+
+async def test_concurrent_acquires_never_overdraw() -> None:
+ """Per-key lock must prevent two coroutines double-spending a token."""
+ limiter = TokenBucketLimiter(capacity=5.0, refill_per_second=0.5)
+ # Fire 20 concurrent acquires against the same key.
+ decisions = await asyncio.gather(
+ *(limiter.acquire("tenant:a") for _ in range(20))
+ )
+ # Bucket starts at 5; refill at 0.5/s for sub-millisecond spread is
+ # ~negligible, so we expect exactly 5 successes (with at most a
+ # tiny epsilon worth of refill).
+ allowed_count = sum(1 for d in decisions if d.allowed)
+ assert 5 <= allowed_count <= 6, (
+ f"expected 5–6 allowed under high concurrency, got {allowed_count}"
+ )
+ denied = [d for d in decisions if not d.allowed]
+ assert all(d.retry_after_seconds > 0 for d in denied)
+
+
+# ---------------------------------------------------------------------------
+# _TokenBucket internal sanity (defensive — confirms the dataclass invariant)
+# ---------------------------------------------------------------------------
+
+
+def test_token_bucket_starts_full_even_when_field_default_is_zero() -> None:
+ """The dataclass post-init normalises tokens to capacity on construction.
+
+ This is what protects new keys from being throttled on their first
+ request.
+ """
+ bucket = _TokenBucket(capacity=7.0, refill_per_second=1.0)
+ assert bucket.tokens == 7.0