From bdc0755d2b0d334eba044dd882ccbb6e906f2181 Mon Sep 17 00:00:00 2001 From: aegor Date: Mon, 30 Nov 2026 16:36:14 +0300 Subject: [PATCH] feat: limit login attempts and request sizes --- infra/haproxy/haproxy.cfg | 5 ++++ scripts/check_api_security.py | 44 ++++++++++++++++++++++++++++++++--- src/auth/auth.controller.ts | 3 +++ src/main.ts | 1 + 4 files changed, 50 insertions(+), 3 deletions(-) diff --git a/infra/haproxy/haproxy.cfg b/infra/haproxy/haproxy.cfg index 4683a9b..939d7f5 100644 --- a/infra/haproxy/haproxy.cfg +++ b/infra/haproxy/haproxy.cfg @@ -34,6 +34,11 @@ resolvers docker frontend public bind :8443 ssl crt /run/tls/ingress.pem + stick-table type ip size 100k expire 10s store http_req_rate(10s) + acl login path -i /api/v1/auth/sessions + http-request track-sc0 src if METH_POST login + http-request del-header X-Lab7-Login-Limited + http-request set-header X-Lab7-Login-Limited 1 if METH_POST login { sc_http_req_rate(0) gt 20 } default_backend api frontend local-health diff --git a/scripts/check_api_security.py b/scripts/check_api_security.py index e43b34d..ab228c0 100644 --- a/scripts/check_api_security.py +++ b/scripts/check_api_security.py @@ -1,16 +1,36 @@ -"""Verify attachment and user access controls over HTTPS.""" +"""Verify HTTPS permission, size, rate and session controls on synthetic users.""" import sys +import time import uuid +from concurrent.futures import ThreadPoolExecutor from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) -from client import Client, arguments, run +from client import Client, Failure, arguments, check, run def main(): - args = arguments(__doc__) + args = arguments(__doc__, lambda parser: parser.add_argument("--expiry-only", action="store_true")) client = Client(args.base_url, args.ca_file) + if args.expiry_only: + deadline = time.monotonic() + 40 + replicas = set() + while len(replicas) < 2 and time.monotonic() < deadline: + try: + response = client.call("GET", "/health/ready", schema="Health") + replicas.add(response["headers"]["X-Instance-Id"]) + except Failure: + pass + time.sleep(0.3) + check(len(replicas) >= 2, "Both API replicas must be ready for the expiry check") + actor = client.user("shortttl") + client.call("GET", "/api/v1/users/me", actor=actor, schema="User") + time.sleep(6) + client.call("GET", "/api/v1/users/me", 401, actor=actor) + print("PASS: HTTPS session expired on the stand configured with SESSION_TTL_SECONDS=5") + return + alice, bob, eve, chat = client.bootstrap() attachment, _ = client.attachment(alice, chat) attachment = client.wait_ready(alice, attachment) @@ -28,6 +48,24 @@ def main(): client.call("GET", "/api/v1/users/me", 401, actor=alice) print("PASS: private attachment metadata/content, cross-chat reference, Bearer precedence and logout") + oversized = b'{"test":"' + b"x" * (1024 * 1024) + b'"}' + client.call("POST", "/api/v1/users", 413, raw=oversized, + headers={"Content-Type": "application/json"}) + print("PASS: oversized JSON returned 413") + + path = "/api/v1/auth/sessions" + client.call("POST", path, 401, headers={"X-Lab7-Login-Limited": "1"}) + with ThreadPoolExecutor(max_workers=8) as pool: + burst = list(pool.map(lambda _: client.call("POST", path, [401, 429]), range(32))) + limited = [reply for reply in burst if reply["status"] == 429] + check(bool(limited), "Login limit did not activate during a burst") + for result in limited: + check(result["headers"].get("Retry-After") == "10", "missing or invalid Retry-After") + check(result["json"]["error"]["code"] == "rate_limited", "wrong error code for 429") + print("PASS: login rate limited with 429 and Retry-After=10; client flag stripped") + time.sleep(10) + client.call("POST", path, 401) + if __name__ == "__main__": run(main) diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.ts index ebd38d7..1ca93e5 100644 --- a/src/auth/auth.controller.ts +++ b/src/auth/auth.controller.ts @@ -30,6 +30,9 @@ export class AuthController { @Headers('authorization') authorization: string | undefined, @Req() request: FastifyRequest, ): Promise { + if (request.headers['x-lab7-login-limited'] === '1') { + throw new ApiError('rate_limited', 'too many login attempts', { 'Retry-After': '10' }); + } if (request.body !== undefined) { throw new ApiError('invalid_request', 'request body is not allowed'); } diff --git a/src/main.ts b/src/main.ts index bed07cf..dc04ae5 100644 --- a/src/main.ts +++ b/src/main.ts @@ -26,6 +26,7 @@ async function bootstrap(): Promise { rejectUnauthorized: true, minVersion: 'TLSv1.2', }, + bodyLimit: 1024 * 1024, }), { bufferLogs: true,