domain-status 0.2.1

Concurrent URL status checker that captures comprehensive metadata in SQLite.
Documentation
//! IP address lookup functions.
//!
//! This module provides functions to look up IP addresses in the `GeoIP` databases
//! and retrieve metadata about the loaded databases.

use super::types::{GeoIpMetadata, GeoIpResult};
use crate::geoip::{GeoIpReaderCache, GEOIP_ASN_READER, GEOIP_CITY_READER};
use std::net::IpAddr;

/// Owned `GeoIP` service that can be instantiated in tests without relying on process-global state.
#[derive(Clone)]
pub struct GeoIpService {
    city_reader: GeoIpReaderCache,
    asn_reader: GeoIpReaderCache,
}

impl std::fmt::Debug for GeoIpService {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GeoIpService").finish_non_exhaustive()
    }
}

impl Default for GeoIpService {
    fn default() -> Self {
        Self {
            city_reader: std::sync::Arc::clone(&GEOIP_CITY_READER),
            asn_reader: std::sync::Arc::clone(&GEOIP_ASN_READER),
        }
    }
}

fn log_lock_poison(kind: &str, err: impl std::fmt::Display) {
    log::error!(
        "GeoIP {kind} database access failed due to lock poisoning (fatal error). \
        Please restart the application. Details: {err}"
    );
}

impl GeoIpService {
    /// Create an empty service with no `GeoIP` databases loaded.
    #[must_use]
    pub fn empty() -> Self {
        Self {
            city_reader: std::sync::Arc::new(std::sync::RwLock::new(None)),
            asn_reader: std::sync::Arc::new(std::sync::RwLock::new(None)),
        }
    }

    /// Looks up an IP address in the City and ASN databases.
    ///
    /// Returns `Some` when either database has a record. Invalid IP strings yield `None`.
    /// `is_enabled` remains City-loaded; this method does not require City data for ASN hits.
    #[must_use]
    pub fn lookup_ip(&self, ip: &str) -> Option<GeoIpResult> {
        let ip_addr: IpAddr = match ip.parse() {
            Ok(addr) => addr,
            Err(e) => {
                log::debug!("Failed to parse IP address '{ip}': {e}");
                return None;
            }
        };

        let mut geo_result = GeoIpResult::default();
        let city_hit = fill_city(&self.city_reader, ip_addr, &mut geo_result);
        let asn_hit = fill_asn(&self.asn_reader, ip_addr, &mut geo_result);
        (city_hit || asn_hit).then_some(geo_result)
    }

    /// Gets the current `GeoIP` City metadata if initialized.
    #[must_use]
    pub fn get_metadata(&self) -> Option<GeoIpMetadata> {
        let reader = self.city_reader.read().ok()?;
        reader.as_ref().map(|(_, metadata)| metadata.clone())
    }

    /// Checks if `GeoIP` is enabled (City database is loaded).
    #[must_use]
    pub fn is_enabled(&self) -> bool {
        self.city_reader
            .read()
            .ok()
            .and_then(|reader| reader.as_ref().map(|_| true))
            .unwrap_or(false)
    }
}

fn fill_city(cache: &GeoIpReaderCache, ip_addr: IpAddr, out: &mut GeoIpResult) -> bool {
    let guard = match cache.read() {
        Ok(guard) => guard,
        Err(e) => {
            log_lock_poison("City", e);
            return false;
        }
    };
    let Some((reader, _)) = guard.as_ref() else {
        return false;
    };
    let Ok(lookup) = reader.lookup(ip_addr) else {
        return false;
    };
    if !lookup.has_data() {
        return false;
    }
    let Ok(Some(city)) = lookup.decode::<maxminddb::geoip2::City>() else {
        return false;
    };

    out.country_code = city.country.iso_code.map(std::string::ToString::to_string);
    out.country_name = city
        .country
        .names
        .english
        .map(std::string::ToString::to_string);
    if let Some(subdivision) = city.subdivisions.first() {
        out.region = subdivision
            .names
            .english
            .map(std::string::ToString::to_string);
    }
    out.city = city
        .city
        .names
        .english
        .map(std::string::ToString::to_string);
    out.latitude = city.location.latitude;
    out.longitude = city.location.longitude;
    out.timezone = city
        .location
        .time_zone
        .map(std::string::ToString::to_string);
    out.postal_code = city.postal.code.map(std::string::ToString::to_string);
    true
}

fn fill_asn(cache: &GeoIpReaderCache, ip_addr: IpAddr, out: &mut GeoIpResult) -> bool {
    let guard = match cache.read() {
        Ok(guard) => guard,
        Err(e) => {
            log_lock_poison("ASN", e);
            return false;
        }
    };
    let Some((reader, _)) = guard.as_ref() else {
        return false;
    };
    let Ok(lookup) = reader.lookup(ip_addr) else {
        return false;
    };
    if !lookup.has_data() {
        return false;
    }
    let Ok(Some(asn)) = lookup.decode::<maxminddb::geoip2::Asn>() else {
        return false;
    };
    out.asn = asn.autonomous_system_number;
    out.asn_org = asn
        .autonomous_system_organization
        .map(std::string::ToString::to_string);
    true
}

/// Looks up an IP address using the default `GeoIP` service.
pub fn lookup_ip(ip: &str) -> Option<GeoIpResult> {
    GeoIpService::default().lookup_ip(ip)
}

/// Checks if `GeoIP` is enabled (database is loaded).
pub fn is_enabled() -> bool {
    GeoIpService::default().is_enabled()
}

#[cfg(test)]
impl GeoIpService {
    /// Local caches only — never the process-global `GEOIP_*` locks.
    pub(crate) fn from_caches(city_reader: GeoIpReaderCache, asn_reader: GeoIpReaderCache) -> Self {
        Self {
            city_reader,
            asn_reader,
        }
    }

    /// Synthetic-MMDB lookup suite (no production `GeoLite2` in tests).
    pub(crate) fn from_readers(
        city: Option<std::sync::Arc<maxminddb::Reader<Vec<u8>>>>,
        asn: Option<std::sync::Arc<maxminddb::Reader<Vec<u8>>>>,
    ) -> Self {
        Self::from_caches(wrap_reader(city), wrap_reader(asn))
    }
}

#[cfg(test)]
fn wrap_reader(reader: Option<std::sync::Arc<maxminddb::Reader<Vec<u8>>>>) -> GeoIpReaderCache {
    let placeholder = GeoIpMetadata {
        source: "test".to_string(),
        version: "test".to_string(),
        last_updated: std::time::SystemTime::UNIX_EPOCH,
    };
    std::sync::Arc::new(std::sync::RwLock::new(reader.map(|r| (r, placeholder))))
}

#[cfg(test)]
fn empty_cache() -> GeoIpReaderCache {
    std::sync::Arc::new(std::sync::RwLock::new(None))
}

#[cfg(test)]
fn poison_cache(cache: &GeoIpReaderCache) {
    let cache = std::sync::Arc::clone(cache);
    let _ = std::thread::spawn(move || {
        let _guard = cache.write().expect("write lock");
        panic!("poison GeoIP lock");
    })
    .join();
}

#[cfg(test)]
fn reader_from_bytes(bytes: &[u8]) -> std::sync::Arc<maxminddb::Reader<Vec<u8>>> {
    std::sync::Arc::new(maxminddb::Reader::from_source(bytes.to_vec()).expect("synthetic MMDB"))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_empty_service_reports_disabled() {
        let service = GeoIpService::empty();
        assert!(!service.is_enabled());
        assert!(service.get_metadata().is_none());
    }

    #[test]
    fn test_empty_service_returns_none_for_valid_ip() {
        let service = GeoIpService::empty();
        assert!(service.lookup_ip("8.8.8.8").is_none());
        assert!(service.lookup_ip("2001:4860:4860::8888").is_none());
    }

    #[test]
    fn test_lookup_ip_invalid_input_returns_none() {
        let service = GeoIpService::empty();
        for ip in [
            "",
            "   ",
            "not.an.ip",
            "1.2.3.4.5",
            "1.2.3",
            "256.1.1.1",
            "8.8.8.8\n",
            "8.8.8.8\t",
            " 8.8.8.8 ",
            "-1.0.0.0",
            "0xdead",
            "::g",
            "2001:db8::1%",
            "fe80::1%eth0",
        ] {
            assert!(
                service.lookup_ip(ip).is_none(),
                "expected None for invalid input {ip:?}"
            );
        }
    }

    const TEST_IP: &str = "192.0.2.1";

    // Tiny IPv4 MMDB: 192.0.2.1/32 → country.iso_code=US, no city/subdivision.
    const COUNTRY_ONLY_CITY_MMDB: &[u8] = &[
        0x00, 0x00, 0x20, 0x00, 0x00, 0x01, 0x00, 0x00, 0x20, 0x00, 0x00, 0x02, 0x00, 0x00, 0x03,
        0x00, 0x00, 0x20, 0x00, 0x00, 0x04, 0x00, 0x00, 0x20, 0x00, 0x00, 0x05, 0x00, 0x00, 0x20,
        0x00, 0x00, 0x06, 0x00, 0x00, 0x20, 0x00, 0x00, 0x07, 0x00, 0x00, 0x20, 0x00, 0x00, 0x08,
        0x00, 0x00, 0x20, 0x00, 0x00, 0x09, 0x00, 0x00, 0x20, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x20,
        0x00, 0x00, 0x0b, 0x00, 0x00, 0x20, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x20, 0x00, 0x00, 0x0d,
        0x00, 0x00, 0x20, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x20, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x20,
        0x00, 0x00, 0x10, 0x00, 0x00, 0x20, 0x00, 0x00, 0x11, 0x00, 0x00, 0x20, 0x00, 0x00, 0x12,
        0x00, 0x00, 0x20, 0x00, 0x00, 0x13, 0x00, 0x00, 0x20, 0x00, 0x00, 0x14, 0x00, 0x00, 0x20,
        0x00, 0x00, 0x15, 0x00, 0x00, 0x20, 0x00, 0x00, 0x16, 0x00, 0x00, 0x20, 0x00, 0x00, 0x20,
        0x00, 0x00, 0x17, 0x00, 0x00, 0x18, 0x00, 0x00, 0x20, 0x00, 0x00, 0x19, 0x00, 0x00, 0x20,
        0x00, 0x00, 0x1a, 0x00, 0x00, 0x20, 0x00, 0x00, 0x1b, 0x00, 0x00, 0x20, 0x00, 0x00, 0x1c,
        0x00, 0x00, 0x20, 0x00, 0x00, 0x1d, 0x00, 0x00, 0x20, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x20,
        0x00, 0x00, 0x1f, 0x00, 0x00, 0x20, 0x00, 0x00, 0x20, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe1, 0x47,
        0x63, 0x6f, 0x75, 0x6e, 0x74, 0x72, 0x79, 0xe1, 0x48, 0x69, 0x73, 0x6f, 0x5f, 0x63, 0x6f,
        0x64, 0x65, 0x42, 0x55, 0x53, 0xab, 0xcd, 0xef, 0x4d, 0x61, 0x78, 0x4d, 0x69, 0x6e, 0x64,
        0x2e, 0x63, 0x6f, 0x6d, 0xe9, 0x5b, 0x62, 0x69, 0x6e, 0x61, 0x72, 0x79, 0x5f, 0x66, 0x6f,
        0x72, 0x6d, 0x61, 0x74, 0x5f, 0x6d, 0x61, 0x6a, 0x6f, 0x72, 0x5f, 0x76, 0x65, 0x72, 0x73,
        0x69, 0x6f, 0x6e, 0xa1, 0x02, 0x5b, 0x62, 0x69, 0x6e, 0x61, 0x72, 0x79, 0x5f, 0x66, 0x6f,
        0x72, 0x6d, 0x61, 0x74, 0x5f, 0x6d, 0x69, 0x6e, 0x6f, 0x72, 0x5f, 0x76, 0x65, 0x72, 0x73,
        0x69, 0x6f, 0x6e, 0xa0, 0x4b, 0x62, 0x75, 0x69, 0x6c, 0x64, 0x5f, 0x65, 0x70, 0x6f, 0x63,
        0x68, 0x01, 0x02, 0x01, 0x4d, 0x64, 0x61, 0x74, 0x61, 0x62, 0x61, 0x73, 0x65, 0x5f, 0x74,
        0x79, 0x70, 0x65, 0x4d, 0x47, 0x65, 0x6f, 0x4c, 0x69, 0x74, 0x65, 0x32, 0x2d, 0x43, 0x69,
        0x74, 0x79, 0x4b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0xe1,
        0x42, 0x65, 0x6e, 0x44, 0x74, 0x65, 0x73, 0x74, 0x4a, 0x69, 0x70, 0x5f, 0x76, 0x65, 0x72,
        0x73, 0x69, 0x6f, 0x6e, 0xa1, 0x04, 0x49, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65,
        0x73, 0x01, 0x04, 0x42, 0x65, 0x6e, 0x4a, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x63, 0x6f, 0x75,
        0x6e, 0x74, 0xc1, 0x20, 0x4b, 0x72, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x5f, 0x73, 0x69, 0x7a,
        0x65, 0xa1, 0x18,
    ];

    // Tiny IPv4 MMDB: 192.0.2.1/32 → AS64496 Example ASN.
    const ASN_ONLY_MMDB: &[u8] = &[
        0x00, 0x00, 0x20, 0x00, 0x00, 0x01, 0x00, 0x00, 0x20, 0x00, 0x00, 0x02, 0x00, 0x00, 0x03,
        0x00, 0x00, 0x20, 0x00, 0x00, 0x04, 0x00, 0x00, 0x20, 0x00, 0x00, 0x05, 0x00, 0x00, 0x20,
        0x00, 0x00, 0x06, 0x00, 0x00, 0x20, 0x00, 0x00, 0x07, 0x00, 0x00, 0x20, 0x00, 0x00, 0x08,
        0x00, 0x00, 0x20, 0x00, 0x00, 0x09, 0x00, 0x00, 0x20, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x20,
        0x00, 0x00, 0x0b, 0x00, 0x00, 0x20, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x20, 0x00, 0x00, 0x0d,
        0x00, 0x00, 0x20, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x20, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x20,
        0x00, 0x00, 0x10, 0x00, 0x00, 0x20, 0x00, 0x00, 0x11, 0x00, 0x00, 0x20, 0x00, 0x00, 0x12,
        0x00, 0x00, 0x20, 0x00, 0x00, 0x13, 0x00, 0x00, 0x20, 0x00, 0x00, 0x14, 0x00, 0x00, 0x20,
        0x00, 0x00, 0x15, 0x00, 0x00, 0x20, 0x00, 0x00, 0x16, 0x00, 0x00, 0x20, 0x00, 0x00, 0x20,
        0x00, 0x00, 0x17, 0x00, 0x00, 0x18, 0x00, 0x00, 0x20, 0x00, 0x00, 0x19, 0x00, 0x00, 0x20,
        0x00, 0x00, 0x1a, 0x00, 0x00, 0x20, 0x00, 0x00, 0x1b, 0x00, 0x00, 0x20, 0x00, 0x00, 0x1c,
        0x00, 0x00, 0x20, 0x00, 0x00, 0x1d, 0x00, 0x00, 0x20, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x20,
        0x00, 0x00, 0x1f, 0x00, 0x00, 0x20, 0x00, 0x00, 0x20, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe2, 0x58,
        0x61, 0x75, 0x74, 0x6f, 0x6e, 0x6f, 0x6d, 0x6f, 0x75, 0x73, 0x5f, 0x73, 0x79, 0x73, 0x74,
        0x65, 0x6d, 0x5f, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0xc2, 0xfb, 0xf0, 0x5d, 0x01, 0x61,
        0x75, 0x74, 0x6f, 0x6e, 0x6f, 0x6d, 0x6f, 0x75, 0x73, 0x5f, 0x73, 0x79, 0x73, 0x74, 0x65,
        0x6d, 0x5f, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4b,
        0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x20, 0x41, 0x53, 0x4e, 0xab, 0xcd, 0xef, 0x4d,
        0x61, 0x78, 0x4d, 0x69, 0x6e, 0x64, 0x2e, 0x63, 0x6f, 0x6d, 0xe9, 0x5b, 0x62, 0x69, 0x6e,
        0x61, 0x72, 0x79, 0x5f, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x5f, 0x6d, 0x61, 0x6a, 0x6f,
        0x72, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0xa1, 0x02, 0x5b, 0x62, 0x69, 0x6e,
        0x61, 0x72, 0x79, 0x5f, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x5f, 0x6d, 0x69, 0x6e, 0x6f,
        0x72, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0xa0, 0x4b, 0x62, 0x75, 0x69, 0x6c,
        0x64, 0x5f, 0x65, 0x70, 0x6f, 0x63, 0x68, 0x01, 0x02, 0x01, 0x4d, 0x64, 0x61, 0x74, 0x61,
        0x62, 0x61, 0x73, 0x65, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x4c, 0x47, 0x65, 0x6f, 0x4c, 0x69,
        0x74, 0x65, 0x32, 0x2d, 0x41, 0x53, 0x4e, 0x4b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70,
        0x74, 0x69, 0x6f, 0x6e, 0xe1, 0x42, 0x65, 0x6e, 0x44, 0x74, 0x65, 0x73, 0x74, 0x4a, 0x69,
        0x70, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0xa1, 0x04, 0x49, 0x6c, 0x61, 0x6e,
        0x67, 0x75, 0x61, 0x67, 0x65, 0x73, 0x01, 0x04, 0x42, 0x65, 0x6e, 0x4a, 0x6e, 0x6f, 0x64,
        0x65, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0xc1, 0x20, 0x4b, 0x72, 0x65, 0x63, 0x6f, 0x72,
        0x64, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0xa1, 0x18,
    ];

    /// Kills: `fill_city` / `fill_asn` panicking on a poisoned `RwLock` instead of
    /// returning `false` so `lookup_ip` is `None`.
    #[test]
    fn test_poisoned_locks_soft_fail() {
        let city = empty_cache();
        let asn = empty_cache();
        poison_cache(&city);
        poison_cache(&asn);
        let service = GeoIpService::from_caches(city, asn);
        assert!(!service.is_enabled());
        assert!(service.get_metadata().is_none());
        assert!(service.lookup_ip(TEST_IP).is_none());
    }

    /// Kills: `fill_city` treating poison as fatal so a working ASN cache is ignored.
    #[test]
    fn test_poisoned_city_still_returns_asn() {
        let city = empty_cache();
        poison_cache(&city);
        let service =
            GeoIpService::from_caches(city, wrap_reader(Some(reader_from_bytes(ASN_ONLY_MMDB))));
        let got = service
            .lookup_ip(TEST_IP)
            .expect("ASN hit must survive City lock poison");
        assert_eq!(got.asn, Some(64_496));
        assert_eq!(got.asn_org.as_deref(), Some("Example ASN"));
        assert!(got.country_code.is_none());
        assert!(got.city.is_none());
        assert!(!service.is_enabled());
        assert!(service.get_metadata().is_none());
    }

    /// Kills: treating a country-only City record as a miss (`fill_city` → `false`)
    /// or requiring city/subdivision names.
    #[test]
    fn test_partial_city_record_keeps_country_omits_city() {
        let service =
            GeoIpService::from_readers(Some(reader_from_bytes(COUNTRY_ONLY_CITY_MMDB)), None);
        let got = service
            .lookup_ip(TEST_IP)
            .expect("country-only City record must be a hit");
        assert_eq!(got.country_code.as_deref(), Some("US"));
        assert!(got.country_name.is_none());
        assert!(got.city.is_none());
        assert!(got.region.is_none());
        assert!(got.asn.is_none());
        assert!(service.is_enabled());
    }

    /// Kills: `lookup_ip` requiring a City hit (`city_hit || asn_hit` → `city_hit`).
    #[test]
    fn test_asn_only_lookup_without_city() {
        let service = GeoIpService::from_readers(None, Some(reader_from_bytes(ASN_ONLY_MMDB)));
        let got = service
            .lookup_ip(TEST_IP)
            .expect("ASN-only record must be a hit");
        assert_eq!(got.asn, Some(64_496));
        assert_eq!(got.asn_org.as_deref(), Some("Example ASN"));
        assert!(got.country_code.is_none());
        assert!(got.city.is_none());
        assert!(!service.is_enabled());
    }
}