Coverage for app/util/geoip.py: 94%

47 statements  

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

1"""Offline IP geolocation via MaxMind GeoLite2. 

2 

3Best-effort and privacy-preserving: lookups happen against a local database, so 

4no third party ever sees user IPs. Degrades gracefully to ``None`` when: 

5 - ``GEOIP_DB_PATH`` is unset or the DB file is missing (no license configured), 

6 - the IP is private/loopback (e.g. docker-internal addresses in dev), or 

7 - the address is not found in the database. 

8""" 

9 

10import ipaddress 

11import logging 

12from dataclasses import dataclass 

13from typing import Optional 

14 

15from app.config import settings 

16 

17logger = logging.getLogger(__name__) 

18 

19 

20@dataclass 

21class GeoLocation: 

22 city: Optional[str] 

23 country: Optional[str] # ISO 3166-1 alpha-2 

24 latitude: Optional[float] = None 

25 longitude: Optional[float] = None 

26 

27 

28# Cache only a *successfully* opened reader, keyed by path. A DB that doesn't 

29# exist yet at first lookup (e.g. the geoipupdate sidecar is still downloading 

30# it) must not be cached as a permanent failure, or geolocation stays disabled 

31# until the process restarts even after the file appears. `lookup()` is only 

32# called once per login, so retrying a missing/unreadable file each time is 

33# cheap. 

34_reader_cache: dict = {} 

35 

36 

37def _reader(): 

38 """Lazily open the GeoLite2 reader; cache the open reader, not a failure.""" 

39 path = settings.GEOIP_DB_PATH 

40 if not path: 

41 return None 

42 

43 cached = _reader_cache.get(path) 

44 if cached is not None: 

45 return cached 

46 

47 try: 

48 import geoip2.database 

49 

50 reader = geoip2.database.Reader(path) 

51 _reader_cache[path] = reader 

52 return reader 

53 except FileNotFoundError: 

54 logger.warning("GeoIP database not found at %s; geolocation disabled", path) 

55 return None 

56 except Exception as e: # pragma: no cover - defensive 

57 logger.warning("Failed to open GeoIP database: %s", e) 

58 return None 

59 

60 

61def _is_public(ip: str) -> bool: 

62 try: 

63 addr = ipaddress.ip_address(ip) 

64 except ValueError: 

65 return False 

66 return not ( 

67 addr.is_private 

68 or addr.is_loopback 

69 or addr.is_link_local 

70 or addr.is_reserved 

71 or addr.is_multicast 

72 ) 

73 

74 

75def lookup(ip: Optional[str]) -> GeoLocation: 

76 """Resolve an IP to an approximate city/country, or empty GeoLocation.""" 

77 empty = GeoLocation(city=None, country=None) 

78 if not ip or not _is_public(ip): 

79 return empty 

80 

81 reader = _reader() 

82 if reader is None: 

83 return empty 

84 

85 try: 

86 import geoip2.errors 

87 

88 response = reader.city(ip) 

89 return GeoLocation( 

90 city=response.city.name, 

91 country=response.country.iso_code, 

92 latitude=response.location.latitude, 

93 longitude=response.location.longitude, 

94 ) 

95 except geoip2.errors.AddressNotFoundError: 

96 return empty 

97 except Exception as e: # pragma: no cover - defensive 

98 logger.warning("GeoIP lookup failed for %s: %s", ip, e) 

99 return empty