Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions flybot_workspace/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from dataclasses import dataclass
from http.cookies import CookieError, SimpleCookie
import hmac
import ipaddress
import json
import re
import sqlite3
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions flybot_workspace/dsbot_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 "";
}
}
Expand Down
9 changes: 8 additions & 1 deletion tests/test_dsbot_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
36 changes: 35 additions & 1 deletion tests/test_management.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading