"""Tests for the XFF-aware rate-limit principal key.""" from unittest.mock import patch from abacus_common_logic.constants.constants import DEFAULT_USER_ID from flask import Flask from werkzeug.middleware.proxy_fix import ProxyFix from core.config import Config from core.hardening.client_ip import install_proxyfix, principal_key def _ctx(app: Flask, **headers: str) -> object: return app.test_request_context(headers=headers) def test_install_proxyfix_trusts_configured_hops() -> None: """install_proxyfix wraps the app, trusting config.PROXYFIX_X_FOR forwarded hops.""" class _Cfg(Config): PROXYFIX_X_FOR = 2 app = Flask(__name__) install_proxyfix(app, _Cfg) assert isinstance(app.wsgi_app, ProxyFix) assert app.wsgi_app.x_for == 2 def test_principal_key_uses_identity_when_present() -> None: """A real authenticated identity keys the limit as a principal.""" app = Flask(__name__) with ( _ctx(app), patch('core.hardening.client_ip.get_flask_user_id', return_value='user-42'), ): assert principal_key() == ('user-42', 'principal') def test_principal_key_falls_back_to_service_then_ip() -> None: """With no real identity, fall through to the requestor service, then the client IP.""" app = Flask(__name__) with ( _ctx(app, **{'Orchard-Requestor-Service': 'ows-abacus-event'}), patch( 'core.hardening.client_ip.get_flask_user_id', return_value=DEFAULT_USER_ID ), ): assert principal_key() == ('ows-abacus-event', 'service') # No identity and no requestor service: key on the client IP. ProxyFix has already # resolved remote_addr by this point, so principal_key just reads it. with ( app.test_request_context(environ_base={'REMOTE_ADDR': '203.0.113.7'}), patch( 'core.hardening.client_ip.get_flask_user_id', return_value=DEFAULT_USER_ID ), ): assert principal_key() == ('203.0.113.7', 'ip') def test_principal_key_unknown_when_no_identity_service_or_ip() -> None: """A falsy user id and no service header or remote_addr collapse to the ('unknown', 'ip') bucket.""" app = Flask(__name__) with ( app.test_request_context(), # no REMOTE_ADDR patch('core.hardening.client_ip.get_flask_user_id', return_value=None), ): assert principal_key() == ('unknown', 'ip')