Coverage for app/util/request_meta.py: 95%

42 statements  

« prev     ^ index     » next       coverage.py v7.14.1, created at 2026-10-31 11:18 +0000

1"""Extract identifying request metadata (client IP + parsed User-Agent). 

2 

3The client IP is recovered from proxy headers set by nginx. Order of trust: 

4 1. ``CF-Connecting-IP`` — true client when behind Cloudflare (prod) 

5 2. left-most ``X-Forwarded-For`` entry — first hop is the real client 

6 3. ``X-Real-IP`` — nginx $remote_addr fallback 

7 4. the socket peer — last resort (dev / direct) 

8""" 

9 

10from dataclasses import dataclass 

11from typing import Optional 

12 

13from fastapi import Request 

14from user_agents import parse as parse_user_agent 

15 

16 

17def get_client_ip(request: Request) -> Optional[str]: 

18 """Best-effort real client IP from proxy headers.""" 

19 cf_ip = request.headers.get("cf-connecting-ip") 

20 if cf_ip: 

21 return cf_ip.strip() 

22 

23 forwarded_for = request.headers.get("x-forwarded-for") 

24 if forwarded_for: 

25 # Left-most entry is the original client; the rest are proxies. 

26 first = forwarded_for.split(",")[0].strip() 

27 if first: 

28 return first 

29 

30 real_ip = request.headers.get("x-real-ip") 

31 if real_ip: 

32 return real_ip.strip() 

33 

34 return request.client.host if request.client else None 

35 

36 

37@dataclass 

38class DeviceInfo: 

39 user_agent: Optional[str] 

40 browser: Optional[str] 

41 os: Optional[str] 

42 device_type: Optional[str] 

43 

44 

45def parse_device(user_agent: Optional[str]) -> DeviceInfo: 

46 """Parse a User-Agent string into human-friendly browser/OS/device fields.""" 

47 if not user_agent: 

48 return DeviceInfo(user_agent=None, browser=None, os=None, device_type=None) 

49 

50 ua = parse_user_agent(user_agent) 

51 

52 if ua.is_bot: 

53 device_type = "bot" 

54 elif ua.is_tablet: 

55 device_type = "tablet" 

56 elif ua.is_mobile: 

57 device_type = "mobile" 

58 elif ua.is_pc: 

59 device_type = "desktop" 

60 else: 

61 device_type = "other" 

62 

63 def _clean(value: str) -> Optional[str]: 

64 value = (value or "").strip() 

65 return value if value and value.lower() != "other" else None 

66 

67 browser = _clean(ua.get_browser()) # e.g. "Chrome 120.0.0" 

68 os = _clean(ua.get_os()) # e.g. "Mac OS X 14.0" 

69 

70 return DeviceInfo( 

71 user_agent=user_agent, 

72 browser=browser, 

73 os=os, 

74 device_type=device_type, 

75 )