uvicorn does not trust forwarded headers from a peer outside forwarded_allow_ips, so request.client.host was the web gateway for every request. The auth-source bucket therefore counted all customers together: 60 failed logins from one attacker locked out everyone. Security events recorded the gateway address, which made the audit trail useless for attribution. The gateway now overwrites X-Forwarded-For with the peer address it observed instead of appending to whatever the client sent, so the header carries one value the client cannot choose, and client_ip() resolves it with a fallback to the connection peer. The guest-session limiter was keyed on the environment name, making it one global bucket of 120 per 15 minutes: roughly eight new visitors a minute for the whole site before legitimate traffic started receiving 429. It is now per source, and the ceiling is deliberately generous because offices and mobile carriers put many real customers behind a single address. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
62 lines
3.4 KiB
Python
62 lines
3.4 KiB
Python
"""Run inside API container: permissions, hashing and fail-closed scanner unit checks."""
|
|
import hashlib
|
|
from unittest.mock import patch
|
|
from botocore.exceptions import ClientError
|
|
from .db import connect
|
|
from .adapters import LocalS3Storage
|
|
from .auth import client_ip, password_hash, password_matches
|
|
from .scanning import ClamAV, require_clean
|
|
from fastapi import HTTPException
|
|
|
|
class FakeRequest:
|
|
def __init__(self, headers=None, peer='10.0.0.2'):
|
|
self.headers=headers or {}
|
|
self.client=type('C',(),{'host':peer})() if peer else None
|
|
|
|
def check_client_ip():
|
|
"""The gateway hands one address; a direct peer falls back to its own."""
|
|
# Gateway-set header wins over the connection peer, which is the gateway.
|
|
assert client_ip(FakeRequest({'x-forwarded-for':'198.51.100.9'}))=='198.51.100.9'
|
|
# Only the first entry is used, and it is length-capped.
|
|
assert client_ip(FakeRequest({'x-forwarded-for':'198.51.100.9, 10.0.0.2'}))=='198.51.100.9'
|
|
assert len(client_ip(FakeRequest({'x-forwarded-for':'a'*500})))<=64
|
|
# No header: the peer address, never a constant shared by every request.
|
|
assert client_ip(FakeRequest(peer='192.0.2.5'))=='192.0.2.5'
|
|
assert client_ip(FakeRequest({'x-forwarded-for':' '},peer='192.0.2.5'))=='192.0.2.5'
|
|
assert client_ip(FakeRequest(peer=None))=='unknown'
|
|
print('PASS: client address resolution for rate-limit buckets and audit events')
|
|
|
|
def run():
|
|
check_client_ip()
|
|
with connect() as c:
|
|
role=c.execute('SELECT rolsuper,rolcreatedb,rolcreaterole,rolbypassrls FROM pg_roles WHERE rolname=current_user').fetchone()
|
|
assert not any(role.values()),role
|
|
assert not c.execute("SELECT has_schema_privilege(current_user,'dtf_local','CREATE') AS allowed").fetchone()['allowed']
|
|
storage=LocalS3Storage()
|
|
storage.health()
|
|
visible={bucket['Name'] for bucket in storage.client.list_buckets()['Buckets']}
|
|
assert visible=={storage.bucket},visible
|
|
for call in (lambda:storage.client.get_bucket_policy(Bucket=storage.bucket),
|
|
lambda:storage.client.get_object(Bucket=storage.bucket,Key='outside-runtime-prefix/test.cdr')):
|
|
try:call();raise AssertionError('Runtime storage credentials have excessive privilege')
|
|
except ClientError as error:assert error.response['ResponseMetadata']['HTTPStatusCode']==403
|
|
password='test-password-for-hash'
|
|
salt='00'*16
|
|
old='scrypt$'+salt+'$'+hashlib.scrypt(password.encode(),salt=bytes.fromhex(salt),n=16384,r=8,p=1).hex()
|
|
assert password_matches(password,old)
|
|
new=password_hash(password)
|
|
assert new.startswith('scrypt-v2$') and password_matches(password,new)
|
|
assert not password_matches('wrong',new)
|
|
for state in ('pending','error','rejected'):
|
|
try:require_clean({'complete':True,'scan_state':state});raise AssertionError('Unscanned file released')
|
|
except HTTPException as error:assert error.status_code==409
|
|
require_clean({'complete':True,'scan_state':'clean'})
|
|
assert ClamAV().ping() and ClamAV().version().startswith('ClamAV ')
|
|
assert ClamAV().scan(None,134217729)[0]=='rejected'
|
|
with patch('local.scanning.socket.create_connection',side_effect=OSError('offline')):
|
|
try:ClamAV().scan(None,1);raise AssertionError('Offline scanner returned success')
|
|
except OSError:pass
|
|
print('PASS: runtime DB/S3 least privilege, legacy/current password hashes, quarantine states and scanner size/offline behavior')
|
|
|
|
if __name__=='__main__':run()
|