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.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
fix(auth): throttle and lock out repeated credential failures (#1075)
Beenu Arora5d7f977fe306
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b8a782e08..c02a3597d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Security++- **Fifty wrong passwords for one account returned fifty 401s, with no delay and no lockout.** `POST /api/v1/auth/login` did a `SELECT`, a `verify_password`, and a 401. `SECURITY.md` pointed readers at `services/api/app/middleware/` "for rate limiting, audit logging, and request hardening", and that directory holds exactly two files, neither of which is a limiter. Rate limiting did exist in this service — on the explain endpoint, on lake queries and on the public waitlist form — and the login route consulted none of it. That is the shape this repository keeps finding: a mechanism that exists, is tested, and has no caller on the path that needs it.++ `services/api/app/services/login_throttle.py` counts failures against **two** principals, because one counter cannot catch both attacks. An account counter catches one source guessing many passwords. A source counter catches one source spraying one common password across many accounts, which never trips an account counter at all, since each account sees a single failure.++ **A success clears the account counter and deliberately not the source counter.** An attacker who guesses one password out of a thousand attempts would otherwise reset their own budget with it and carry on from zero, which turns a successful compromise into a free pass for the next nine hundred guesses.++ The refusal is identical for an account that exists and one that does not, and the throttle runs *before* the database is consulted so it cannot know which it is. A throttle that engaged only for real accounts would answer 429 for those and 401 for the rest, and that difference is a user list — a worse defect than the one being fixed.++ Below the threshold nothing happens, so someone who mistypes twice gets the ordinary 401. Past it, a 429 carrying `Retry-After` whose delay doubles per failure up to a ceiling; past the lockout threshold, a fixed cool-off. Doubling rather than a flat window, because a flat window is a rate an attacker can schedule around. Redis keys hold a SHA-256 of the address rather than the address, since an email in a key is an email in `KEYS *` and in every backup of that Redis.++ When Redis is unavailable the limiter falls back to per-replica counting and says so at `warning`. Failing closed would lock every operator out of their own console over a Redis blip; failing silently open would remove the control exactly when an attacker is most likely to have caused the outage. Per-replica counting is weaker than shared counting and is documented as weaker rather than described as equivalent.++ The passkey assertion route is throttled per source as well, and its failures are counted rather than only checked — a limiter whose counter nothing increments never refuses anything.++ Measured in both directions: 22 cases, of which the four route-level ones fail on the pre-fix tree as `assert 429 in [401, 401, 401, ...]`. The control — that the first two attempts still answer 401 — passes on both trees, which is what stops the suite being satisfied by a route that refuses everyone.++### BREAKING- **An unauthenticated request is no longer an administrator, and `AISOC_DEV_MODE` no longer admits an uncredentialed caller.** If you rely on either, here is what changes and how to get it back.diff --git a/ROADMAP.md b/ROADMAP.mdindex 047911149..85474e479 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -44,7 +44,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.-The claim-to-gate matrix stands at **243 rows — 243 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).+The claim-to-gate matrix stands at **244 rows — 244 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).## v4.0 — Shippeddiff --git a/SECURITY.md b/SECURITY.mdindex e197235c1..743000bc1 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -63,7 +63,8 @@ If you operate AiSOC, please review:- [`docs/runbooks/HARDENING.md`](docs/runbooks/HARDENING.md) for production hardening steps- [`infra/helm/aisoc/values.yaml`](infra/helm/aisoc/values.yaml) for the security-related defaults- [`services/api/app/core/security.py`](services/api/app/core/security.py) and [`services/api/app/auth/`](services/api/app/auth/) for our auth, RBAC, and SSO primitives-- [`services/api/app/middleware/`](services/api/app/middleware/) for rate limiting, audit logging, and request hardening+- [`services/api/app/middleware/`](services/api/app/middleware/) for audit logging and request hardening+- [`services/api/app/services/login_throttle.py`](services/api/app/services/login_throttle.py) for sign-in throttling and lockout, and the `*_rate_limit.py` modules beside it for the explain, lake and waitlist limits. This line used to say rate limiting lived in the middleware directory, which holds two files and neither is a limiter## Federated Threat Intel Mesh disclosurediff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex d0ae3c6cc..8bf97e4b0 100644--- a/apps/docs/docs/compliance/evidence-pack.md+++ b/apps/docs/docs/compliance/evidence-pack.md@@ -33,7 +33,7 @@ and says so.| Prompt-injection resistance | Three adversarial corpora: 32 payloads scanned in isolation and 71 incident pairs whose payloads are placed in attacker-controllable fields, both against a clean twin with a recall floor and a false-positive ceiling, plus 34 held-out pairs authored after the guard was frozen and carrying no floor at all, on which the guard measures 7.1% | `services/agents/tests/adversarial/` || Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |-The last row is the one worth reading first. It is the honest index: 243 rows+The last row is the one worth reading first. It is the honest index: 244 rows`GATED`, 0 `PARTIAL`, and a ratchet that refuses to let a row sit at`NO GATE`. Re-read the figure from the table rather than from here — a countcopied into prose goes stale in silence, which is whydiff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 05ac9a80f..5c5713370 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -251,10 +251,11 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| A published Helm chart version names one chart forever | `apps/docs/docs/deployment/kubernetes.md` (The chart's version); `infra/helm/aisoc/Chart.yaml` | `helm.yml :: version` + `release.yml :: chart-publish` (`check_chart_version.py` — four checks that need no network: `appVersion` moved while the chart's own `version` did not, any tracked chart file moved with no version bump (with Chart.yaml's own `version:` masked, so the bump cannot justify itself), a version that moved backward, and one chart version declared at two release tags with differing content. Plus one that asks GHCR: the version about to be pushed already exists holding content this tree does not. The registry comparison is on **unpacked files**, because `helm package` is not byte-reproducible — `Chart.yaml` is compared parsed since helm re-serialises it, and the tracked subchart `.tgz` are expanded the way helm expands them, a mapping measured exact against the published 5.9.2 at 146 files. On a release it runs with `--require-network`, before `helm push`, because the push overwrites silently and there is no after. 16 self-test cases, and the gate refuses a checkout with no tags rather than concluding no release ever declared a version) | GATED | **Proven against the pre-fix tree**: at `2db6ce73` (the v13.0.0 release commit) it exits 1 naming `appversion-moved-alone` — `v12.3.2` -> `v13.0.0` with `version` held at 5.9.2 — and exits 0 at `9d3225c6` after the bump to 6.0.0. **Two things it deliberately does not decide.** Whether a bump is the right *size*: nothing in a diff knows if a renamed `values.yaml` key breaks somebody's values file, so the gate enforces forward, never how far. And the overwrite that already happened: republishing replaced the bytes, so the registry's 5.9.2 and the tree that overwrote it are now byte-identical — measured, 146 files, zero differences — which is why the retro-detection reads git rather than the registry, and why the pre-fix proof runs through the baseline check. `5.9.2` and `5.2.0` are recorded in `KNOWN_COLLISIONS` as unrepairable, checked in both directions so an entry that stops being detectable fails || Every console call to an AiSOC API carries a credential | `apps/web/src/lib/api.ts` (the credentialed client); `SECURITY.md` (authentication) | `ci.yml :: Python — Lint & Type-check` (`check_console_auth_headers.py` — parses every `fetch(` and `useSWR(` call under `apps/web/src` and requires the credential to be visible on the same expression, so hiding it behind a local `const headers` a few lines up does not count. `X-Tenant-Id` alone and `credentials: 'include'` are both findings, because neither authenticates against a bearer-token API. 15 self-test cases, of which three pin blind spots in the gate's own first draft — a generic type argument hid both real SWR sites, a multi-line arrow fetcher was truncated at the first newline, and an inline fetcher whose URL is the SWR key has no API path at the call site — and four are controls that must not fire. It refuses a tree with no console sources, and separately refuses one where the console makes no API call at all, since a broken matcher and a console that stopped calling the API print the same clean line) | GATED | **Proven against the pre-fix tree**: 61 findings across 21 files at `079fdb69` (45 bare fetches, 16 SWR fetchers), 0 after. One allowlisted exception, the public `/r/<slug>` replay permalink, which is unauthenticated by design and is kept safe by `replay_redaction.py` rather than by a header; the allowlist may only shrink and a stale entry fails the gate. One limit stated rather than implied: the gate reads the console, so it proves the credential is sent, not that the server requires it — `check_route_auth.py` and `check_route_authz.py` are the other half || An unauthenticated request is never an administrator, and never acts in a real tenant | `SECURITY.md` (authentication); `apps/docs/docs/deployment/single-host.md` | `ci.yml :: Python — Tests` (`services/api/tests/test_anonymous_bypass_requires_optin.py`, 36 cases: the four names in `AUTH_BYPASS_ENVIRONMENTS` each refuse on their own; the explicit `AISOC_DEV_AUTH_BYPASS` opt-in admits; five truthy and five falsy spellings of it; the flag does not re-enable the shim outside a dev environment; five reachable published addresses refuse and five loopback forms admit; one reachable address among several refuses; the demo tenant is not the bootstrap tenant and the canonical id did not move; and every refusal names the condition that withheld it) + the nine vendored copies of `services/fusion/tests/test_tenant_scope.py` kept in lockstep by `sync_vendored_tenant_scope.py --check` + `services/realtime/test/push-tenant.test.ts` | GATED | **Proven against the pre-fix tree**: 35 of 36 API cases fail at `079fdb69` and all 36 pass after, with the tenant-sharing assertion failing as `assert UUID('…0001') != UUID('…0001')`; 4 of 8 realtime cases fail pre-fix, the other 4 being controls that must pass both ways. Two limits stated rather than implied. The loopback check is only as good as what compose passes in `AISOC_PUBLISHED_BIND_ADDRS`: an unset list is treated as a local run, because refusing on an empty list would break `uvicorn app.main:app` for contributors, which is the case the shim exists for — the deployment-path gate is what stops a published stack leaving it unset. And a hostname that is not obviously loopback is treated as reachable, so a DNS name resolving to 127.0.0.1 refuses the bypass; that is the safe direction for an undecidable question, and it is a false refusal, never a false admission |+| Repeated credential failures are throttled and eventually locked out | `SECURITY.md` (what to review) | `ci.yml :: Python — Tests` (`services/api/tests/test_login_throttle.py`, 18 cases, and `services/api/tests/test_login_route_throttled.py`, 4 that drive the real route — because a gate on the limiter alone passes over a route that never calls it, and that was the defect: three limiters existed in this service and login consulted none of them. Asserted in both directions: a success clears the account counter and not the source counter; password spraying trips the source counter without ever tripping an account counter; an address that does not exist is refused identically to one that does; and Redis being down degrades to per-replica counting rather than locking everyone out) | GATED | **Proven against the pre-fix tree**: the four route cases fail at `4f4ba326` as `assert 429 in [401, 401, 401, ...]`, and the control — the first two attempts still answering 401 — passes on both trees, so the suite cannot be satisfied by a route that refuses everyone. Two limits stated rather than implied. The source counter is evadable where `X-Forwarded-For` is not stripped by a trusted proxy, since an attacker can rotate it for a fresh bucket per request; that is why the account counter is the primary control, and why the source counter is aimed at spraying, where per-request rotation is not something an attacker expects to need. And the fallback is per-replica, so an attacker spread across replicas gets one budget per replica — weaker than shared counting, and recorded as weaker |## Summary-- GATED: 243+- GATED: 244- PARTIAL: 0- NO GATE: 0 (**every claim is backed by a failing test, and none is now a named deferral either.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The last two PARTIAL rows closed with `scripts/check_live_agent_floor.py` and a floor derived from ten runs across two environments, not by relabelling. Recount with `scripts/check_claim_gate_matrix.py` rather than trusting these three numbers: they move weekly, and a count copied into prose goes stale in silence.)diff --git a/services/api/app/api/v1/endpoints/auth.py b/services/api/app/api/v1/endpoints/auth.pyindex ba2905607..da55f178a 100644--- a/services/api/app/api/v1/endpoints/auth.py+++ b/services/api/app/api/v1/endpoints/auth.py@@ -1,10 +1,11 @@"""Authentication endpoints: login, refresh, logout, user preferences."""+import loggingimport uuidfrom datetime import UTC, datetimefrom typing import Any-from fastapi import APIRouter, HTTPException, status+from fastapi import APIRouter, HTTPException, Request, statusfrom pydantic import BaseModel, EmailStrfrom sqlalchemy import select, update@@ -20,6 +21,9 @@ from app.core.security import (verify_password,)from app.models.tenant import User+from app.services.login_throttle import client_ip, get_login_throttle++logger = logging.getLogger(__name__)router = APIRouter(prefix="/auth", tags=["auth"])@@ -58,19 +62,48 @@ class PreferencesPatch(BaseModel):preferences: dict[str, Any]+# The throttle runs *before* the password is verified, and answers the same+# whether the account exists or not. A throttle that engaged only for real+# accounts would reply 429 for those and 401 for the rest, and that difference+# is a user list.+#+# The explanation lives here rather than in the docstring because the+# docstring is published as the operation's `description` in+# `docs/openapi.yaml`, and an API description should say what the endpoint+# does, not what it used to do wrong.@router.post("/login", response_model=TokenResponse)-async def login(request: LoginRequest, db: DBSession) -> TokenResponse:+async def login(request: LoginRequest, http_request: Request, db: DBSession) -> TokenResponse:"""Authenticate with email/password, return JWT tokens."""+ throttle = get_login_throttle()+ source = client_ip(http_request)+ decision = await throttle.check(email=request.email, source_ip=source)+ if not decision.allowed:+ raise HTTPException(+ status_code=status.HTTP_429_TOO_MANY_REQUESTS,+ detail=decision.detail,+ headers={"Retry-After": str(decision.retry_after_seconds)},+ )+result = await db.execute(select(User).where(User.email == request.email, User.is_active.is_(True)))user = result.scalar_one_or_none()if user is None or not verify_password(request.password, user.hashed_password):+ locked = await throttle.record_failure(email=request.email, source_ip=source)+ if locked.locked_out:+ logger.warning(+ "login lockout: %s principal locked after %d failures (ip=%s)",+ locked.scope,+ locked.failures,+ str(source).replace("\r", "").replace("\n", " ")[:64],+ )raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail="Incorrect email or password",headers={"WWW-Authenticate": "Bearer"},)+ await throttle.record_success(email=request.email, source_ip=source)+# Update last loginawait db.execute(update(User).where(User.id == user.id).values(last_login=datetime.now(UTC)))diff --git a/services/api/app/api/v1/endpoints/passkeys.py b/services/api/app/api/v1/endpoints/passkeys.pyindex 1532eefa5..0e3fa068d 100644--- a/services/api/app/api/v1/endpoints/passkeys.py+++ b/services/api/app/api/v1/endpoints/passkeys.py@@ -40,7 +40,7 @@ import uuidfrom datetime import UTC, datetime, timedeltafrom typing import Any-from fastapi import APIRouter, HTTPException, status+from fastapi import APIRouter, HTTPException, Request, statusfrom pydantic import BaseModel, EmailStr, Fieldfrom sqlalchemy import and_, select, update@@ -50,6 +50,7 @@ from app.core.security import create_access_token, create_refresh_tokenfrom app.db.rls import TenantDBSessionfrom app.models.responder import PasskeyChallenge, PasskeyCredentialfrom app.models.tenant import User+from app.services.login_throttle import client_ip, get_login_throttlelogger = logging.getLogger(__name__)@@ -374,11 +375,32 @@ async def passkey_authenticate_begin(@router.post("/authenticate/finish", response_model=AuthenticateFinishResponse)async def passkey_authenticate_finish(body: FinishRequest,+ http_request: Request,db: DBSession,) -> AuthenticateFinishResponse:"""Verify a passkey assertion and mint JWTs."""+ # Throttled per source, and not per account: this route is given a+ # credential id rather than an address, so there is no account to count+ # against until the lookup succeeds. A passkey assertion is far harder to+ # brute-force than a password, so the limit bounds the work an+ # unauthenticated caller can make this service do rather than stopping+ # guessing.+ #+ # In a comment because the docstring is published as this operation's+ # `description` in `docs/openapi.yaml`, and an API description should say+ # what the endpoint does.webauthn, _ = _import_webauthn()+ throttle = get_login_throttle()+ source = client_ip(http_request)+ decision = await throttle.check(email="", source_ip=source)+ if not decision.allowed:+ raise HTTPException(+ status_code=status.HTTP_429_TOO_MANY_REQUESTS,+ detail=decision.detail,+ headers={"Retry-After": str(decision.retry_after_seconds)},+ )+await _consume_challenge(db, encoded=body.challenge, purpose="authenticate")raw_credential_id = body.credential.get("id") or body.credential.get("rawId")@@ -397,6 +419,10 @@ async def passkey_authenticate_finish()).scalar_one_or_none()if cred_row is None:+ # Fed, not merely checked. A limiter whose counter nothing increments+ # never refuses anything, which is the shape the console-credential+ # work found repeatedly: a mechanism with no caller on the path.+ await throttle.record_failure(email="", source_ip=source)raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,detail="Unknown or revoked passkey",diff --git a/services/api/app/services/login_throttle.py b/services/api/app/services/login_throttle.pynew file mode 100644index 000000000..0a39870b0--- /dev/null+++ b/services/api/app/services/login_throttle.py@@ -0,0 +1,373 @@+"""Throttle and lock out repeated credential failures.++Fifty wrong passwords for one account inside a minute all returned 401, with+no delay and no lockout. `SECURITY.md` pointed readers at+`services/api/app/middleware/` "for rate limiting, audit logging, and request+hardening", and that directory holds exactly two files, neither of which is a+limiter. Rate limiting did exist in this service, but only on three unrelated+surfaces: the explain endpoint, lake queries and the public waitlist form.++Two counters, not one+---------------------+An **account** counter and a **source** counter, because they catch different+attacks and a single counter cannot do both:++* one address guessing many passwords is caught by the account counter;+* one source spraying one common password across many accounts never trips an+ account counter at all, because each account sees a single failure.++A success clears the account counter and **not** the source counter. That is+deliberate and is the subtle half: an attacker who guesses one password out of+a thousand attempts would otherwise reset their own budget with it and carry+on from zero.++Backoff, then lockout+---------------------+Below the threshold, nothing. Past it, a refusal carrying `Retry-After` whose+delay doubles per failure up to a ceiling; past the lockout threshold, a fixed+cool-off. Doubling rather than a flat window because a flat window is a rate+an attacker can simply schedule around, and the early doubling steps are short+enough that someone who mistyped their password twice does not notice.++The reply is deliberately the same for an account that exists and one that+does not. A throttle that only engages for real accounts is a user-enumeration+oracle, which is a worse defect than the one it fixes.++When Redis is unavailable+-------------------------+Falls back to an in-process counter and says so at `warning`. Failing closed+would lock every operator out of their own console over a Redis blip, and+failing silently open would leave the control absent exactly when an attacker+is most likely to have caused the outage. Per-replica counting is weaker than+shared counting and is documented as such rather than described as equivalent.+"""++from __future__ import annotations++import hashlib+import logging+import os+import time+from dataclasses import dataclass, field++logger = logging.getLogger(__name__)++#: Failures before a refusal begins. Three is a mistyped password twice plus+#: one, which is where a person starts to think rather than keep typing.+DEFAULT_FAILURE_THRESHOLD = 5++#: Failures before the fixed cool-off replaces the doubling delay.+DEFAULT_LOCKOUT_THRESHOLD = 10++#: Seconds of delay at the first refusal; doubles per failure after that.+DEFAULT_BASE_DELAY_SECONDS = 2.0++#: Ceiling on the doubling, so the delay stays bounded before lockout.+DEFAULT_MAX_DELAY_SECONDS = 60.0++#: How long a lockout lasts.+DEFAULT_LOCKOUT_SECONDS = 900.0++#: How long a failure counts against a principal. Without expiry, one typo a+#: month would eventually lock an account that nobody is attacking.+DEFAULT_WINDOW_SECONDS = 900.0++#: A source may fail more than an account before it is throttled: an office+#: behind one NAT address is many people, and several of them mistype.+SOURCE_MULTIPLIER = 6+++def _env_float(name: str, default: float) -> float:+ raw = os.getenv(name, "").strip()+ if not raw:+ return default+ try:+ value = float(raw)+ except ValueError:+ logger.warning("%s is not a number (%r); using %s", name, raw, default)+ return default+ if value <= 0:+ logger.warning("%s must be positive (%r); using %s", name, raw, default)+ return default+ return value+++@dataclass(frozen=True)+class ThrottleDecision:+ """Whether this attempt may proceed, and what to tell the caller."""++ allowed: bool+ retry_after_seconds: int = 0+ locked_out: bool = False+ #: Which counter refused: "account" or "source". Named so an audit row+ #: distinguishes one account under attack from one source spraying many.+ scope: str = ""+ failures: int = 0++ @property+ def detail(self) -> str:+ if self.allowed:+ return ""+ if self.locked_out:+ return f"Too many failed sign-in attempts. This account is temporarily locked. Try again in {self.retry_after_seconds} seconds."+ return f"Too many failed sign-in attempts. Try again in {self.retry_after_seconds} seconds."+++@dataclass+class _Counter:+ failures: int = 0+ first_seen: float = 0.0+ locked_until: float = 0.0+++@dataclass+class _InProcessStore:+ """The fallback. Per-replica, which is weaker than shared and is said so."""++ counters: dict[str, _Counter] = field(default_factory=dict)++ def get(self, key: str, window: float, now: float) -> _Counter:+ counter = self.counters.get(key)+ if counter is None or (counter.locked_until <= now and now - counter.first_seen > window):+ counter = _Counter(first_seen=now)+ self.counters[key] = counter+ return counter++ def clear(self, key: str) -> None:+ self.counters.pop(key, None)+++def client_ip(request: object) -> str:+ """The source address, trusting the proxy chain in front of the API.++ Mirrors the resolver the waitlist limiter uses, with one caveat that+ matters more here than it does there: where `X-Forwarded-For` is not+ stripped by a trusted proxy, an attacker can rotate it and give+ themselves a fresh source bucket per request. That does not let them+ exhaust somebody else's budget, but it does let them evade the source+ counter. Which is why the **account** counter is the primary control and+ the source counter is the one that catches password spraying, where the+ attacker has no reason to expect per-request rotation to be needed.+ """+ headers = getattr(request, "headers", {})+ forwarded = (headers.get("x-forwarded-for", "") if hasattr(headers, "get") else "").strip()+ if forwarded:+ first = forwarded.split(",", 1)[0].strip()+ if first:+ return first+ peer = getattr(request, "client", None)+ host = getattr(peer, "host", None)+ return host or "unknown"+++def _principal_key(scope: str, value: str) -> str:+ """A Redis key that does not contain the address or the source itself.++ An email in a key is an email in `KEYS *`, in a memory dump and in any+ backup of that Redis. The counter needs identity, not the identifier.+ """+ digest = hashlib.sha256(value.strip().lower().encode("utf-8")).hexdigest()[:32]+ return f"aisoc:login:{scope}:{digest}"+++class LoginThrottle:+ """Counts credential failures per account and per source."""++ def __init__(self, redis_client: object | None = None) -> None:+ self._redis = redis_client+ self._fallback = _InProcessStore()+ self._warned_about_fallback = False++ # ── tuning, read at call time so an operator can widen without a redeploy+ @property+ def failure_threshold(self) -> int:+ return int(_env_float("AISOC_LOGIN_FAILURE_THRESHOLD", DEFAULT_FAILURE_THRESHOLD))++ @property+ def lockout_threshold(self) -> int:+ return int(_env_float("AISOC_LOGIN_LOCKOUT_THRESHOLD", DEFAULT_LOCKOUT_THRESHOLD))++ @property+ def base_delay(self) -> float:+ return _env_float("AISOC_LOGIN_BASE_DELAY_SECONDS", DEFAULT_BASE_DELAY_SECONDS)++ @property+ def max_delay(self) -> float:+ return _env_float("AISOC_LOGIN_MAX_DELAY_SECONDS", DEFAULT_MAX_DELAY_SECONDS)++ @property+ def lockout_seconds(self) -> float:+ return _env_float("AISOC_LOGIN_LOCKOUT_SECONDS", DEFAULT_LOCKOUT_SECONDS)++ @property+ def window_seconds(self) -> float:+ return _env_float("AISOC_LOGIN_WINDOW_SECONDS", DEFAULT_WINDOW_SECONDS)++ def _delay_for(self, failures: int, threshold: int) -> float:+ """Doubling delay past the threshold, capped."""+ over = failures - threshold+ if over <= 0:+ return 0.0+ return min(self.base_delay * (2 ** (over - 1)), self.max_delay)++ async def _counter(self, key: str, now: float) -> _Counter:+ if self._redis is None:+ return self._fallback.get(key, self.window_seconds, now)+ try:+ raw = await self._redis.hgetall(key) # type: ignore[attr-defined]+ except Exception as exc: # noqa: BLE001 - any client error is a fallback+ self._warn_fallback(exc)+ self._redis = None+ return self._fallback.get(key, self.window_seconds, now)+ if not raw:+ return _Counter(first_seen=now)+ return _Counter(+ failures=int(raw.get("failures", 0)),+ first_seen=float(raw.get("first_seen", now)),+ locked_until=float(raw.get("locked_until", 0)),+ )++ async def _store(self, key: str, counter: _Counter) -> None:+ if self._redis is None:+ self._fallback.counters[key] = counter+ return+ try:+ await self._redis.hset( # type: ignore[attr-defined]+ key,+ mapping={+ "failures": counter.failures,+ "first_seen": counter.first_seen,+ "locked_until": counter.locked_until,+ },+ )+ # The key outlives the window by the lockout, so a lockout is not+ # cleared early by the window expiring underneath it.+ await self._redis.expire(key, int(self.window_seconds + self.lockout_seconds)) # type: ignore[attr-defined]+ except Exception as exc: # noqa: BLE001+ self._warn_fallback(exc)+ self._redis = None+ self._fallback.counters[key] = counter++ async def _clear(self, key: str) -> None:+ if self._redis is None:+ self._fallback.clear(key)+ return+ try:+ await self._redis.delete(key) # type: ignore[attr-defined]+ except Exception as exc: # noqa: BLE001+ self._warn_fallback(exc)+ self._redis = None+ self._fallback.clear(key)++ def _warn_fallback(self, exc: Exception) -> None:+ if self._warned_about_fallback:+ return+ self._warned_about_fallback = True+ logger.warning(+ "login throttle: Redis unavailable (%s). Falling back to per-replica "+ "counting, which is weaker: an attacker spread across replicas gets "+ "one budget per replica. Sign-in stays available rather than failing "+ "closed, which would lock every operator out over a Redis blip.",+ exc,+ )++ async def check(self, *, email: str, source_ip: str | None) -> ThrottleDecision:+ """Whether this attempt may proceed. Call before verifying a password."""+ now = time.time()+ for scope, value, threshold in (+ ("account", email, self.failure_threshold),+ ("source", source_ip or "", self.failure_threshold * SOURCE_MULTIPLIER),+ ):+ if not value:+ continue+ counter = await self._counter(_principal_key(scope, value), now)+ if counter.locked_until > now:+ return ThrottleDecision(+ allowed=False,+ retry_after_seconds=max(1, int(counter.locked_until - now)),+ locked_out=True,+ scope=scope,+ failures=counter.failures,+ )+ delay = self._delay_for(counter.failures, threshold)+ if delay > 0:+ waited = now - counter.first_seen+ # The delay is measured from the most recent failure, which is+ # what `first_seen` becomes once a refusal has been issued.+ if waited < delay:+ return ThrottleDecision(+ allowed=False,+ retry_after_seconds=max(1, int(delay - waited)),+ scope=scope,+ failures=counter.failures,+ )+ return ThrottleDecision(allowed=True)++ async def record_failure(self, *, email: str, source_ip: str | None) -> ThrottleDecision:+ """Count a failure against both principals, and lock out if warranted."""+ now = time.time()+ worst = ThrottleDecision(allowed=True)+ for scope, value, threshold in (+ ("account", email, self.lockout_threshold),+ ("source", source_ip or "", self.lockout_threshold * SOURCE_MULTIPLIER),+ ):+ if not value:+ continue+ key = _principal_key(scope, value)+ counter = await self._counter(key, now)+ counter.failures += 1+ counter.first_seen = now+ if counter.failures >= threshold:+ counter.locked_until = now + self.lockout_seconds+ await self._store(key, counter)+ if counter.locked_until > now and not worst.locked_out:+ worst = ThrottleDecision(+ allowed=False,+ retry_after_seconds=int(self.lockout_seconds),+ locked_out=True,+ scope=scope,+ failures=counter.failures,+ )+ return worst++ async def record_success(self, *, email: str, source_ip: str | None) -> None:+ """Clear the account counter. Deliberately not the source counter.++ An attacker who guesses one password out of a thousand attempts would+ otherwise reset their own budget with it and carry on from zero. The+ source counter expires on its own window instead.+ """+ del source_ip # named for symmetry, and to make the omission explicit+ if email:+ await self._clear(_principal_key("account", email))+++_throttle: LoginThrottle | None = None+++def get_login_throttle() -> LoginThrottle:+ global _throttle # noqa: PLW0603 - one limiter per process, by design+ if _throttle is None:+ _throttle = LoginThrottle(_redis_client())+ return _throttle+++def reset_login_throttle_for_tests() -> None:+ """Drop the process-wide limiter. Tests only."""+ global _throttle # noqa: PLW0603+ _throttle = None+++def _redis_client() -> object | None:+ try:+ from redis.asyncio import from_url++ from app.core.config import settings++ return from_url(str(settings.REDIS_URL), decode_responses=True)+ except Exception as exc: # noqa: BLE001 - no Redis configured is not fatal+ logger.warning(+ "login throttle: no Redis client (%s). Counting per replica; see the module docstring for why this is not fail-closed.",+ exc,+ )+ return Nonediff --git a/services/api/tests/test_login_route_throttled.py b/services/api/tests/test_login_route_throttled.pynew file mode 100644index 000000000..0dd90fa99--- /dev/null+++ b/services/api/tests/test_login_route_throttled.py@@ -0,0 +1,112 @@+"""The login route itself refuses repeated failures.++`test_login_throttle.py` exercises the limiter. This file exercises the+*route*, because the defect was never that no limiter existed — three of them+did, on the explain endpoint, lake queries and the public waitlist form. The+defect was that `POST /api/v1/auth/login` consulted none of them, so fifty+wrong passwords for one account inside a minute returned fifty 401s with no+delay and no lockout.++A gate on the limiter alone would pass over a route that never calls it,+which is the shape this repository keeps finding: a mechanism that exists, is+unit-tested, and has no caller on the path that needs it.+"""++from __future__ import annotations++import pytest+from app.api.v1.endpoints import auth as auth_module+from app.services import login_throttle+from fastapi import FastAPI+from fastapi.testclient import TestClient++[email protected](autouse=True)+def _tight_thresholds(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("AISOC_LOGIN_FAILURE_THRESHOLD", "3")+ monkeypatch.setenv("AISOC_LOGIN_LOCKOUT_THRESHOLD", "50")+ monkeypatch.setenv("AISOC_LOGIN_BASE_DELAY_SECONDS", "5")+ monkeypatch.setenv("AISOC_LOGIN_MAX_DELAY_SECONDS", "60")+ monkeypatch.setenv("AISOC_LOGIN_WINDOW_SECONDS", "600")+ login_throttle.reset_login_throttle_for_tests()+ # No Redis in a unit test: the documented per-replica fallback, which is+ # the same code path the route drives.+ monkeypatch.setattr(login_throttle, "_redis_client", lambda: None)+++class _NoUser:+ """A session whose every lookup finds nothing.++ That is the important case: the throttle has to engage for an address+ that does not exist, or the difference between 429 and 401 is a user+ list.+ """++ async def execute(self, *_args, **_kwargs):+ class _Result:+ @staticmethod+ def scalar_one_or_none():+ return None++ return _Result()+++def client(monkeypatch: pytest.MonkeyPatch) -> TestClient:+ app = FastAPI()+ app.include_router(auth_module.router, prefix="/api/v1")+ from app.api.v1.deps import get_db++ async def _db():+ yield _NoUser()++ app.dependency_overrides[get_db] = _db+ return TestClient(app, raise_server_exceptions=False)+++def _attempt(client: TestClient) -> int:+ return client.post(+ "/api/v1/auth/login",+ json={"email": "[email protected]", "password": "wrong"},+ ).status_code+++class TestTheRouteConsultsTheThrottle:+ def test_fifty_wrong_passwords_are_not_all_401(self, client: TestClient) -> None:+ """The defect, stated as a test.++ On the pre-fix tree every one of these is a 401: no delay, no+ lockout, no counter. `SECURITY.md` pointed readers at+ `services/api/app/middleware/` for rate limiting, and that directory+ holds two files, neither of which is a limiter.+ """+ codes = [_attempt(client) for _ in range(50)]+ assert 429 in codes, f"fifty wrong passwords for one account produced no refusal at all; status codes seen: {sorted(set(codes))}"++ def test_the_first_attempts_still_answer_401(self, client: TestClient) -> None:+ """Someone who mistypes their password twice gets the ordinary+ answer, not a rate-limit page."""+ assert _attempt(client) == 401+ assert _attempt(client) == 401++ def test_the_refusal_carries_retry_after(self, client: TestClient) -> None:+ for _ in range(10):+ response = client.post(+ "/api/v1/auth/login",+ json={"email": "[email protected]", "password": "wrong"},+ )+ if response.status_code == 429:+ assert response.headers.get("Retry-After"), "a 429 with no Retry-After is not actionable"+ assert int(response.headers["Retry-After"]) >= 1+ return+ pytest.fail("the route never refused")++ def test_an_address_that_does_not_exist_is_throttled_too(self, client: TestClient) -> None:+ """The session double finds no user for any address, so every attempt+ here is against a non-existent account — and it is still refused.++ A throttle that engaged only for real accounts would answer 429 for+ those and 401 for the rest, and that difference is a user list.+ """+ codes = [_attempt(client) for _ in range(20)]+ assert 429 in codesdiff --git a/services/api/tests/test_login_throttle.py b/services/api/tests/test_login_throttle.pynew file mode 100644index 000000000..c693db457--- /dev/null+++ b/services/api/tests/test_login_throttle.py@@ -0,0 +1,274 @@+"""Repeated credential failures are throttled and eventually locked out.++Fifty wrong passwords for one account inside a minute all returned 401, with+no delay and no lockout, and `SECURITY.md` told readers rate limiting lived in+`services/api/app/middleware/` — a directory holding exactly two files,+neither of which is a limiter.++Four properties are asserted here, and three of them are the ones a throttle+usually gets wrong:++* the reply is identical for an account that exists and one that does not,+ because a throttle that only engages for real accounts is a+ user-enumeration oracle;+* a success clears the **account** counter and not the **source** counter, so+ an attacker who guesses one password out of a thousand attempts cannot+ reset their own budget with it;+* password spraying trips the source counter without ever tripping an account+ counter, which is the attack a single per-account limiter misses entirely;+* Redis being down degrades to per-replica counting rather than locking every+ operator out of their own console.+"""++from __future__ import annotations++import time++import pytest+from app.services import login_throttle+from app.services.login_throttle import LoginThrottle, ThrottleDecision++[email protected](autouse=True)+def _tight_thresholds(monkeypatch: pytest.MonkeyPatch) -> None:+ """Small numbers, so a test does not have to fail fifty times."""+ monkeypatch.setenv("AISOC_LOGIN_FAILURE_THRESHOLD", "3")+ monkeypatch.setenv("AISOC_LOGIN_LOCKOUT_THRESHOLD", "5")+ monkeypatch.setenv("AISOC_LOGIN_BASE_DELAY_SECONDS", "2")+ monkeypatch.setenv("AISOC_LOGIN_MAX_DELAY_SECONDS", "30")+ monkeypatch.setenv("AISOC_LOGIN_LOCKOUT_SECONDS", "600")+ monkeypatch.setenv("AISOC_LOGIN_WINDOW_SECONDS", "600")+ login_throttle.reset_login_throttle_for_tests()+++def _throttle() -> LoginThrottle:+ """No Redis: the in-process store, which is the documented fallback."""+ return LoginThrottle(redis_client=None)+++async def _fail(throttle: LoginThrottle, times: int, *, email: str, ip: str | None) -> None:+ for _ in range(times):+ await throttle.record_failure(email=email, source_ip=ip)+++class TestTheDefect:+ @pytest.mark.asyncio+ async def test_repeated_failures_are_eventually_refused(self) -> None:+ """The assertion that fails on the pre-fix tree: nothing refused."""+ throttle = _throttle()+ assert (await throttle.check(email="[email protected]", source_ip="10.0.0.1")).allowed++ await _fail(throttle, 4, email="[email protected]", ip="10.0.0.1")++ decision = await throttle.check(email="[email protected]", source_ip="10.0.0.1")+ assert not decision.allowed+ assert decision.retry_after_seconds >= 1++ @pytest.mark.asyncio+ async def test_the_first_few_failures_are_not_refused(self) -> None:+ """Someone who mistypes twice must not be told to wait."""+ throttle = _throttle()+ await _fail(throttle, 2, email="[email protected]", ip="10.0.0.1")+ assert (await throttle.check(email="[email protected]", source_ip="10.0.0.1")).allowed++ @pytest.mark.asyncio+ async def test_the_delay_doubles(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """Lockout is pushed out of the way, or it arrives before the second+ doubling step and the test measures one delay rather than a curve."""+ monkeypatch.setenv("AISOC_LOGIN_LOCKOUT_THRESHOLD", "99")+ throttle = _throttle()+ delays = []+ for _ in range(7):+ await throttle.record_failure(email="[email protected]", source_ip=None)+ decision = await throttle.check(email="[email protected]", source_ip=None)+ delays.append(decision.retry_after_seconds)+ refusals = [d for d in delays if d > 0]+ assert refusals == sorted(refusals), f"delays did not increase: {delays}"+ assert len(refusals) >= 3, f"expected several refusals, saw {delays}"+ assert refusals[-1] > refusals[0], f"the delay did not grow: {delays}"++ @pytest.mark.asyncio+ async def test_the_delay_is_capped(self) -> None:+ """Unbounded doubling would lock an account out for years by accident."""+ throttle = _throttle()+ await _fail(throttle, 3, email="[email protected]", ip=None)+ assert throttle._delay_for(40, 3) <= throttle.max_delay++ @pytest.mark.asyncio+ async def test_enough_failures_lock_the_account_out(self) -> None:+ throttle = _throttle()+ locked = ThrottleDecision(allowed=True)+ for _ in range(6):+ locked = await throttle.record_failure(email="[email protected]", source_ip=None)+ assert locked.locked_out+ assert locked.scope == "account"+ decision = await throttle.check(email="[email protected]", source_ip=None)+ assert decision.locked_out+ assert decision.retry_after_seconds > 60+++class TestItIsNotAnEnumerationOracle:+ @pytest.mark.asyncio+ async def test_an_unknown_address_is_throttled_identically(self) -> None:+ """The throttle sees an address, not an account.++ It runs before the database is consulted, so it cannot know whether+ the account exists — which is the point. A throttle that engaged only+ for real accounts would answer 429 for those and 401 for the rest,+ and that difference is a user list.+ """+ throttle = _throttle()+ await _fail(throttle, 4, email="[email protected]", ip="10.0.0.1")+ refused = await throttle.check(email="[email protected]", source_ip="10.0.0.1")++ other = _throttle()+ await _fail(other, 4, email="[email protected]", ip="10.0.0.2")+ real = await other.check(email="[email protected]", source_ip="10.0.0.2")++ assert refused.allowed == real.allowed+ assert refused.locked_out == real.locked_out+++class TestTheTwoCountersCatchDifferentAttacks:+ @pytest.mark.asyncio+ async def test_spraying_trips_the_source_counter(self) -> None:+ """One password against many accounts never trips an account counter.++ Each account sees exactly one failure, so a per-account limiter alone+ does not see this attack at all.+ """+ throttle = _throttle()+ for index in range(20):+ await throttle.record_failure(email=f"user{index}@example.com", source_ip="10.0.0.9")++ fresh_account = await throttle.check(email="[email protected]", source_ip="10.0.0.9")+ assert not fresh_account.allowed, "a spraying source was not refused"+ assert fresh_account.scope == "source"++ @pytest.mark.asyncio+ async def test_one_sources_failures_do_not_refuse_another(self) -> None:+ throttle = _throttle()+ await _fail(throttle, 30, email="[email protected]", ip="10.0.0.9")+ assert (await throttle.check(email="[email protected]", source_ip="10.0.0.10")).allowed+++class TestSuccessClearsTheAccountCounterOnly:+ @pytest.mark.asyncio+ async def test_a_success_clears_the_account(self) -> None:+ throttle = _throttle()+ await _fail(throttle, 4, email="[email protected]", ip="10.0.0.1")+ assert not (await throttle.check(email="[email protected]", source_ip=None)).allowed++ await throttle.record_success(email="[email protected]", source_ip="10.0.0.1")+ assert (await throttle.check(email="[email protected]", source_ip=None)).allowed++ @pytest.mark.asyncio+ async def test_a_success_does_not_clear_the_source(self) -> None:+ """The subtle half.++ An attacker who guesses one password out of a thousand attempts would+ otherwise reset their own source budget with it and carry on from+ zero, which turns a successful compromise into a free pass for the+ next nine hundred guesses.+ """+ throttle = _throttle()+ for index in range(20):+ await throttle.record_failure(email=f"user{index}@example.com", source_ip="10.0.0.9")++ await throttle.record_success(email="[email protected]", source_ip="10.0.0.9")++ still_refused = await throttle.check(email="[email protected]", source_ip="10.0.0.9")+ assert not still_refused.allowed, "one success reset the spraying source's budget"+++class TestTheKeyspaceHoldsNoAddresses:+ def test_the_key_does_not_contain_the_email(self) -> None:+ """An email in a key is an email in `KEYS *` and in every backup."""+ key = login_throttle._principal_key("account", "[email protected]")+ assert "someone" not in key+ assert "example.com" not in key+ assert key.startswith("aisoc:login:account:")++ def test_the_key_is_stable_across_case_and_whitespace(self) -> None:+ assert login_throttle._principal_key("account", " [email protected] ") == login_throttle._principal_key("account", "[email protected]")+++class TestRedisFailureDegradesRatherThanLocksEveryoneOut:+ @pytest.mark.asyncio+ async def test_a_broken_client_falls_back_instead_of_refusing(self, caplog) -> None:+ class _Broken:+ async def hgetall(self, *_args, **_kwargs):+ raise ConnectionError("redis is down")++ async def hset(self, *_args, **_kwargs):+ raise ConnectionError("redis is down")++ async def expire(self, *_args, **_kwargs):+ raise ConnectionError("redis is down")++ async def delete(self, *_args, **_kwargs):+ raise ConnectionError("redis is down")++ throttle = LoginThrottle(redis_client=_Broken())+ with caplog.at_level("WARNING"):+ assert (await throttle.check(email="[email protected]", source_ip="10.0.0.1")).allowed+ assert any("Redis unavailable" in record.message for record in caplog.records)++ @pytest.mark.asyncio+ async def test_the_fallback_still_counts(self) -> None:+ """Weaker than shared counting is not the same as absent."""++ class _Broken:+ async def hgetall(self, *_args, **_kwargs):+ raise ConnectionError("redis is down")++ async def hset(self, *_args, **_kwargs):+ raise ConnectionError("redis is down")++ async def expire(self, *_args, **_kwargs):+ raise ConnectionError("redis is down")++ async def delete(self, *_args, **_kwargs):+ raise ConnectionError("redis is down")++ throttle = LoginThrottle(redis_client=_Broken())+ await _fail(throttle, 4, email="[email protected]", ip="10.0.0.1")+ assert not (await throttle.check(email="[email protected]", source_ip="10.0.0.1")).allowed+++class TestTheClientAddressResolver:+ def test_it_prefers_the_forwarded_header(self) -> None:+ class _Request:+ headers = {"x-forwarded-for": "203.0.113.7, 10.0.0.1"}+ client = type("C", (), {"host": "10.0.0.1"})()++ assert login_throttle.client_ip(_Request()) == "203.0.113.7"++ def test_it_falls_back_to_the_socket(self) -> None:+ class _Request:+ headers: dict[str, str] = {}+ client = type("C", (), {"host": "10.0.0.1"})()++ assert login_throttle.client_ip(_Request()) == "10.0.0.1"++ def test_it_never_returns_empty(self) -> None:+ """An empty key would put every unattributable caller in one bucket."""++ class _Request:+ headers: dict[str, str] = {}+ client = None++ assert login_throttle.client_ip(_Request()) == "unknown"+++class TestTheWindowExpires:+ @pytest.mark.asyncio+ async def test_failures_age_out(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """One typo a month must not eventually lock an unattacked account."""+ monkeypatch.setenv("AISOC_LOGIN_WINDOW_SECONDS", "1")+ throttle = _throttle()+ await _fail(throttle, 4, email="[email protected]", ip=None)+ assert not (await throttle.check(email="[email protected]", source_ip=None)).allowed++ time.sleep(1.2)+ assert (await throttle.check(email="[email protected]", source_ip=None)).allowed