diff --git a/flybot_workspace/app.py b/flybot_workspace/app.py index 8812c4790..d673390f9 100644 --- a/flybot_workspace/app.py +++ b/flybot_workspace/app.py @@ -2,6 +2,7 @@ from dataclasses import dataclass from http.cookies import CookieError, SimpleCookie import hmac +import ipaddress import json import re import sqlite3 @@ -30,6 +31,33 @@ def refuse(status, code, message): raise APIError(status, code, message) +def client_address(env): + """The client the authentication limits count against. + + The app listens on loopback only, behind the edge nginx, so REMOTE_ADDR is the edge and every browser + would share one bucket. The edge overwrites X-Forwarded-For with the address it accepted the connection + from, and this header is believed only from a loopback peer: a direct caller elsewhere cannot pick its + own bucket with a made-up header. + """ + peer = env.get('REMOTE_ADDR', '') + if len(peer) > 128: + refuse(400, 'invalid', 'Invalid client address') + try: + loopback = ipaddress.ip_address(peer).is_loopback + except ValueError: + loopback = False + forwarded = env.get('HTTP_X_FORWARDED_FOR', '') if loopback else '' + if not forwarded: + return peer + if len(forwarded) > 128: + refuse(400, 'invalid', 'Invalid client address') + try: + ipaddress.ip_address(forwarded) + except ValueError: + refuse(400, 'invalid', 'Invalid client address') + return forwarded + + @dataclass(frozen=True) class Config: origin: str @@ -209,9 +237,7 @@ def authenticated(self, db, env, now): return session def rate_limit(self, env, username, now): - peer = env.get('REMOTE_ADDR', '') - if len(peer) > 128: - refuse(400, 'invalid', 'Invalid client address') + peer = client_address(env) limits = [('peer:' + peer, self.config.auth_peer_limit), ('name:' + username, self.config.auth_name_limit), ('global', self.config.auth_global_limit)] blocked = False diff --git a/flybot_workspace/dsbot_gateway.py b/flybot_workspace/dsbot_gateway.py index 4f5c00d31..b54cb4e91 100644 --- a/flybot_workspace/dsbot_gateway.py +++ b/flybot_workspace/dsbot_gateway.py @@ -769,6 +769,9 @@ def composed(env, start_response): location / { proxy_pass http://__PLATFORM__; proxy_set_header Host $host; + # Overwrite, never append: the platform believes this header only from its loopback peer, so it must + # carry the address this edge accepted, not a value the caller put in front of it. + proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-OT-Gateway-Key ""; } } diff --git a/tests/test_dsbot_gateway.py b/tests/test_dsbot_gateway.py index 31304b98f..a2017180d 100644 --- a/tests/test_dsbot_gateway.py +++ b/tests/test_dsbot_gateway.py @@ -568,7 +568,14 @@ def test_nginx_sets_runtime_owner_from_the_authorization_response(self): self.assertIn('proxy_set_header X-OT-Owner-Username $ot_owner_username;', browser) self.assertIn('proxy_set_header X-OT-Owner-Username "";', external) - def test_bot_social_socket_routes_only_shared_runtime_api(self): + def test_nginx_hands_the_edge_the_client_address_to_the_auth_limits(self): + conf = gw.nginx_config(gw.load_routes(), '127.0.0.1:8080', 8081, key='k' * 40) + block = conf.split('\n location / {', 1)[1].split('\n }', 1)[0] + self.assertIn('proxy_set_header X-Forwarded-For $remote_addr;', block) + # Appending keeps a caller-supplied address in front of the one this edge accepted. + self.assertNotIn('$proxy_add_x_forwarded_for', block) + + routes = gw.load_routes() conf = gw.nginx_config(routes, '127.0.0.1:8080', 8081, key=KEY, bot_social='bot-social:8787', bot_social_socket=True) diff --git a/tests/test_management.py b/tests/test_management.py index 095a380d7..310d29de2 100644 --- a/tests/test_management.py +++ b/tests/test_management.py @@ -305,7 +305,41 @@ def test_retry_after_only_describes_auth_rate_limits_not_persistent_quotas(self) self.assertEqual(limited['body']['error']['code'], 'rate_limited') self.assertEqual(dict(limited['headers'])['Retry-After'], str(self.config.auth_window)) - def test_origin_configuration_requires_explicit_loopback_cookie_downgrade(self): + def test_peer_rate_limit_counts_each_client_behind_the_edge(self): + self.app.config = replace(self.app.config, auth_peer_limit=1) + + def attempt(username, forwarded): + return Client(self.app).call('POST', '/v1/auth/register', + {'username': username, 'password': PASSWORD}, + {'HTTP_X_FORWARDED_FOR': forwarded}) + + self.assertEqual(attempt('alice', '198.51.100.1')['status'], 201) + # A different client behind the same loopback edge gets its own bucket... + self.assertEqual(attempt('bob', '198.51.100.2')['status'], 201) + # ...while the first client's next request is still limited against its own address. + limited = attempt('carol', '198.51.100.1') + self.assertEqual(limited['status'], 429) + self.assertEqual(limited['body']['error']['code'], 'rate_limited') + + def test_peer_rate_limit_ignores_a_forwarded_header_from_a_direct_caller(self): + self.client.register() + self.app.config = replace(self.app.config, auth_peer_limit=1) + direct = Client(self.app, peer='203.0.113.9') + first = direct.call('POST', '/v1/auth/login', {'username': 'alice', 'password': 'not-the-passphrase-1'}, + {'HTTP_X_FORWARDED_FOR': '198.51.100.7'}) + second = direct.call('POST', '/v1/auth/login', {'username': 'alice', 'password': 'not-the-passphrase-2'}, + {'HTTP_X_FORWARDED_FOR': '198.51.100.8'}) + self.assertEqual(first['status'], 401) + # The header did not split the bucket: both attempts counted against the one connecting address. + self.assertEqual(second['status'], 429) + + def test_forwarded_header_from_the_edge_must_be_one_address(self): + bad = Client(self.app).call('POST', '/v1/auth/register', {'username': 'alice', 'password': PASSWORD}, + {'HTTP_X_FORWARDED_FOR': '198.51.100.1, 10.0.0.1'}) + self.assertEqual(bad['status'], 400) + self.assertEqual(bad['body']['error']['code'], 'invalid') + + for origin in ['http://example.test', 'https://user:pass@example.test', 'https://example.test/path', 'https://example.test?x=y']: with self.assertRaises(ValueError): Config(origin)