diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d710dd8..d11e05c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,7 +10,8 @@ permissions: jobs: test: - runs-on: ubuntu-latest + # Python 3.9 is unavailable on Ubuntu 26.04 (ubuntu-latest). + runs-on: ubuntu-24.04 strategy: matrix: python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"] diff --git a/CHANGELOG.md b/CHANGELOG.md index 6fe484d..86ff5d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ All notable changes to this project are documented in this file. +## [0.2.0] - 2026-11-17 + +- Support API Schema 1.6.0 with optional `IpNetwork.domain` and `IpNetwork.range`. +- Add optional `IpLocation.continent_code`, `continent`, `postal_code`, `latitude`, and `longitude`. +- Preserve missing/null values as `None`, zero coordinates, string postal codes, frozen models, and existing positional constructors; older API responses remain compatible. +- Share the updated models between synchronous and asynchronous clients without new runtime dependencies. +- Add model and mock-transport regression coverage for all seven fields, null/missing/partial responses, anycast, IPv6, leading-zero postal codes, and immutability. +- Retain Python 3.9–3.13 compatibility and the existing CI matrix. SDK package version 0.2.0 is independent of API Schema 1.6.0. + ## [0.1.0] - 2026-09-16 Initial release. diff --git a/README.md b/README.md index 4c36796..1526672 100644 --- a/README.md +++ b/README.md @@ -136,6 +136,59 @@ result.tor # TorInfo | None -- present only when the address is a Tor relay Every `ip_risk()` call returns IP intelligence for the address: ASN, organization, network type (`residential`, `mobile`, `hosting`, `datacenter`, ...), and connection type -- everything a Python IP lookup API needs to return. `result.location` adds IP geolocation data -- country, region, city, and time zone -- at the network level (derived from routing/registration data), not device-level GPS location. +### Schema 1.6.0 network and location fields + +SDK 0.2.0 adds the following optional fields for API Schema 1.6.0. The SDK +package version and API schema version are independent. + +| API JSON field | Python attribute | Type | +| --- | --- | --- | +| `network.domain` | `result.network.domain` | `str / None` | +| `network.range` | `result.network.range` | `str / None` | +| `location.continentCode` | `location.continent_code` | `str / None` | +| `location.continent` | `location.continent` | `str / None` | +| `location.postalCode` | `location.postal_code` | `str / None` | +| `location.latitude` | `location.latitude` | `float / None` | +| `location.longitude` | `location.longitude` | `float / None` | + +```python +from netriskscan import NetRiskScan + +with NetRiskScan() as client: + result = client.ip_risk("8.8.8.8") + + print("Risk Index:", result.risk.index) + print("Domain:", result.network.domain) + print("Range:", result.network.range) + + if result.location is not None: + location = result.location + print("Continent:", location.continent) + print("Continent Code:", location.continent_code) + print("Postal Code:", location.postal_code) + + if location.latitude is not None and location.longitude is not None: + print("Coordinates:", location.latitude, location.longitude) +``` + +`domain` is the network operator's trusted primary domain, such as `google.com`; +it does not identify a hosted website, cloud customer, or PTR hostname, and the +SDK never guesses a domain from an ASN name. `range` is the server's canonical +CIDR containing the queried IP, for IPv4 or IPv6; the SDK preserves it unchanged. + +Coordinates describe an approximate network location, not device GPS. Anycast +addresses may have no coordinates. Latitude ranges from -90 to 90 and longitude +from -180 to 180, as guaranteed by the server. Check explicitly for `None`: +`0.0` is a valid coordinate, and `None` is distinct from both `False` and numeric +zero. Postal codes stay strings, preserving leading zeros such as `"00501"`. + +Older servers may omit these fields; missing fields and explicit JSON `null` +both become `None`. The entire `location` may also be `None`. The SDK performs +no risk scoring, geolocation inference, or missing-value completion. Both clients +use the same immutable, publicly exported `IpNetwork`, `IpLocation`, and +`IpRiskResult` models. With `AsyncNetRiskScan`, access the same fields on +`result = await client.ip_risk("8.8.8.8")`. + ### Proxy, VPN, and Tor detection `result.flags` carries anonymous IP detection signals for the address: `proxy`, `vpn`, and `tor` (Tor *exit* node specifically -- see `result.tor` for relay/exit/bad-exit detail), plus `datacenter` for hosting/datacenter network identification. Each flag is tri-state (see "`None` is not `False`" below): `True` means detected, `False` means checked and clear, `None` means not evaluated this round. diff --git a/pyproject.toml b/pyproject.toml index 536d3e0..72826bb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "netriskscan" -version = "0.1.0" +version = "0.2.0" description = "Official Python SDK for IP risk scoring, IP reputation, IP lookup, proxy/VPN/Tor detection and network intelligence using the NetRiskScan API." readme = "README.md" license = "MIT" diff --git a/src/netriskscan/models/risk.py b/src/netriskscan/models/risk.py index 89b95b6..026282f 100644 --- a/src/netriskscan/models/risk.py +++ b/src/netriskscan/models/risk.py @@ -74,6 +74,10 @@ class IpNetwork: ``profile`` and ``service`` are ``None`` both when the server omits them (no first-party record) and when it sends an explicit null -- both mean the same thing: nothing to report. + + ``domain`` is the trusted primary domain of the network operator, not a + hosted website or PTR hostname. ``range`` is the server-provided CIDR + containing the queried address (IPv4 or IPv6). Neither is inferred here. """ type: str | None @@ -82,6 +86,8 @@ class IpNetwork: organization: str | None profile: str | None = None service: str | None = None + domain: str | None = None + range: str | None = None @classmethod def _from_json(cls, data: dict[str, Any]) -> IpNetwork: @@ -92,6 +98,8 @@ def _from_json(cls, data: dict[str, Any]) -> IpNetwork: organization=_get(data, "organization"), profile=_get(data, "profile"), service=_get(data, "service"), + domain=_get(data, "domain"), + range=_get(data, "range"), ) @@ -139,7 +147,12 @@ def _from_json(cls, data: dict[str, Any]) -> IpFlags: @dataclass(frozen=True) class IpLocation: - """Network-level geolocation (registration/routing), not device GPS.""" + """Network-level geolocation (registration/routing), not device GPS. + + Missing fields and explicit null map to ``None``. Coordinates may be + unavailable for anycast; ``0.0`` is a valid coordinate. ``postal_code`` + stays a string, including leading zeros. Values are never inferred here. + """ country_code: str | None country: str | None @@ -147,6 +160,11 @@ class IpLocation: region: str | None city: str | None time_zone: str | None + continent_code: str | None = None + continent: str | None = None + postal_code: str | None = None + latitude: float | None = None + longitude: float | None = None @classmethod def _from_json(cls, data: dict[str, Any]) -> IpLocation: @@ -157,6 +175,11 @@ def _from_json(cls, data: dict[str, Any]) -> IpLocation: region=_get(data, "region"), city=_get(data, "city"), time_zone=_get(data, "timeZone"), + continent_code=_get(data, "continentCode"), + continent=_get(data, "continent"), + postal_code=_get(data, "postalCode"), + latitude=_get(data, "latitude"), + longitude=_get(data, "longitude"), ) diff --git a/src/netriskscan/version.py b/src/netriskscan/version.py index 1cf6267..6c5007c 100644 --- a/src/netriskscan/version.py +++ b/src/netriskscan/version.py @@ -1 +1 @@ -VERSION = "0.1.0" +VERSION = "0.2.0" diff --git a/tests/conftest.py b/tests/conftest.py index 79e4df1..a2fe116 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -7,13 +7,21 @@ from __future__ import annotations import json +from copy import deepcopy from typing import Any, Callable import httpx +import pytest Handler = Callable[[httpx.Request], httpx.Response] +@pytest.fixture(autouse=True) +def isolate_api_key_environment(monkeypatch: pytest.MonkeyPatch) -> None: + """Keep anonymous tests independent of credentials on the host machine.""" + monkeypatch.delenv("NETRISKSCAN_API_KEY", raising=False) + + def json_response( status_code: int, payload: dict[str, Any], @@ -92,6 +100,23 @@ def make_sync_transport(handler: Handler) -> httpx.MockTransport: "location": None, } + +@pytest.fixture +def schema_160_body() -> dict[str, Any]: + """Synthetic unicast response, independent of live IP geolocation.""" + body = deepcopy(SAMPLE_IP_RISK_BODY) + body["ip"] = "192.0.2.10" + body["network"].update(domain="operator.example", range="192.0.2.0/24") + body["location"].update( + continentCode="NA", + continent="North America", + postalCode="00501", + latitude=40.81, + longitude=-73.04, + ) + return body + + SAMPLE_USAGE_BODY: dict[str, Any] = { "plan": "growth", "period": {"start": "2026-09-01T00:00:00Z", "end": "2026-10-01T00:00:00Z"}, diff --git a/tests/test_async_client.py b/tests/test_async_client.py index 5613748..27dad24 100644 --- a/tests/test_async_client.py +++ b/tests/test_async_client.py @@ -3,7 +3,7 @@ import httpx import pytest -from netriskscan import AsyncNetRiskScan, ValidationError, get_response_meta +from netriskscan import AsyncNetRiskScan, NetRiskScan, ValidationError, get_response_meta from .conftest import SAMPLE_IP_RISK_BODY, SAMPLE_USAGE_BODY, json_response @@ -76,3 +76,35 @@ async def test_async_context_manager_closes_owned_client(): async with owned_client: assert owned_client._owns_client is True assert owned_client._client.is_closed is True + + +@pytest.mark.parametrize("legacy", [False, True], ids=["schema-1.6.0", "legacy"]) +async def test_schema_160_fields_match_sync_with_one_request(schema_160_body, legacy): + body = SAMPLE_IP_RISK_BODY if legacy else schema_160_body + requests = [] + + def handler(request: httpx.Request) -> httpx.Response: + requests.append(request) + return json_response(200, body) + + async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http_client: + async with AsyncNetRiskScan(http_client=http_client) as client: + result = await client.ip_risk(body["ip"]) + + assert len(requests) == 1 + assert requests[0].method == "GET" + assert requests[0].url.path == f"/v1/ip-risk/{body['ip']}" + assert result.network.domain == (None if legacy else "operator.example") + assert result.network.range == (None if legacy else "192.0.2.0/24") + assert result.location is not None + assert result.location.continent_code == (None if legacy else "NA") + assert result.location.continent == (None if legacy else "North America") + assert result.location.postal_code == (None if legacy else "00501") + assert result.location.latitude == (None if legacy else 40.81) + assert result.location.longitude == (None if legacy else -73.04) + + requests.clear() + with httpx.Client(transport=httpx.MockTransport(handler)) as sync_http_client: + with NetRiskScan(http_client=sync_http_client) as sync_client: + assert result == sync_client.ip_risk(body["ip"]) + assert len(requests) == 1 diff --git a/tests/test_client.py b/tests/test_client.py index 8a6d513..440433b 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -187,3 +187,33 @@ def test_context_manager_closes_only_the_client_it_created(): with owned_client: assert owned_client._owns_client is True assert owned_client._client.is_closed is True + + +@pytest.mark.parametrize("legacy", [False, True], ids=["schema-1.6.0", "legacy"]) +def test_schema_160_fields_with_one_request(schema_160_body, legacy): + body = SAMPLE_IP_RISK_BODY if legacy else schema_160_body + requests = [] + + def handler(request: httpx.Request) -> httpx.Response: + requests.append(request) + return json_response(200, body) + + with httpx.Client(transport=httpx.MockTransport(handler)) as http_client: + with NetRiskScan(http_client=http_client) as client: + result = client.ip_risk(body["ip"]) + + assert len(requests) == 1 + assert requests[0].method == "GET" + assert requests[0].url.path == f"/v1/ip-risk/{body['ip']}" + assert result.network.domain == (None if legacy else "operator.example") + assert result.network.range == (None if legacy else "192.0.2.0/24") + assert result.location is not None + assert result.location.continent_code == (None if legacy else "NA") + assert result.location.continent == (None if legacy else "North America") + assert result.location.postal_code == (None if legacy else "00501") + assert result.location.latitude == (None if legacy else 40.81) + assert result.location.longitude == (None if legacy else -73.04) + assert result.risk.index == 95 + assert result.flags.proxy is False + assert result.network.organization == "Google LLC" + assert result.location.country_code == "US" diff --git a/tests/test_models.py b/tests/test_models.py index 5dc21b9..da6cf1d 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -1,5 +1,10 @@ from __future__ import annotations +from dataclasses import FrozenInstanceError + +import pytest + +from netriskscan import IpLocation, IpNetwork from netriskscan.models.risk import IpRiskResult from netriskscan.models.usage import UsageResult @@ -90,3 +95,180 @@ def test_usage_result_parses_full_shape(): assert result.period.start == "2026-09-01T00:00:00Z" assert result.units.used == 1200 assert result.rate_limit.requests_per_minute == 120 + + +def test_schema_160_all_fields(schema_160_body): + result = IpRiskResult._from_json(schema_160_body) + assert result.network.domain == "operator.example" + assert result.network.range == "192.0.2.0/24" + assert result.location is not None + assert result.location.continent_code == "NA" + assert result.location.continent == "North America" + assert result.location.postal_code == "00501" + assert isinstance(result.location.postal_code, str) + assert result.location.latitude == 40.81 + assert result.location.longitude == -73.04 + assert type(result.location.latitude) is float + assert type(result.location.longitude) is float + + +@pytest.mark.parametrize("explicit_null", [False, True], ids=["missing", "null"]) +def test_schema_160_unknown_fields_default_to_none(explicit_null): + body = dict(SAMPLE_IP_RISK_BODY) + if explicit_null: + body["network"] = dict(body["network"], domain=None, range=None) + body["location"] = dict( + body["location"], + continentCode=None, + continent=None, + postalCode=None, + latitude=None, + longitude=None, + ) + result = IpRiskResult._from_json(body) + assert result.network.domain is None + assert result.network.range is None + assert result.network.profile == "public_dns_resolver" + assert result.network.service == "Google Public DNS" + assert result.network.asn == "AS15169" + assert result.location is not None + assert result.location.country_code == "US" + assert result.location.time_zone == "America/Chicago" + assert result.location.continent_code is None + assert result.location.continent is None + assert result.location.postal_code is None + assert result.location.latitude is None + assert result.location.longitude is None + + +@pytest.mark.parametrize("latitude,longitude", [(0.0, 0.0), (-90.0, -180.0), (90.0, 180.0)]) +def test_coordinates_preserve_zero_and_boundaries(schema_160_body, latitude, longitude): + schema_160_body["location"].update(latitude=latitude, longitude=longitude) + location = IpRiskResult._from_json(schema_160_body).location + assert location is not None + assert location.latitude == latitude + assert location.longitude == longitude + assert type(location.latitude) is float + assert type(location.longitude) is float + + +def test_anycast_coordinates_are_not_inferred(schema_160_body): + schema_160_body["network"].update(profile="public_dns_resolver") + schema_160_body["location"].update(latitude=None, longitude=None, postalCode=None) + location = IpRiskResult._from_json(schema_160_body).location + assert location is not None + assert location.country_code == "US" + assert location.continent == "North America" + assert location.latitude is None + assert location.longitude is None + assert location.postal_code is None + + +def test_ipv6_range_is_preserved(schema_160_body): + schema_160_body["ip"] = "2001:db8::10" + schema_160_body["network"]["range"] = "2001:db8::/48" + result = IpRiskResult._from_json(schema_160_body) + assert result.ip == "2001:db8::10" + assert result.network.range == "2001:db8::/48" + + +@pytest.mark.parametrize( + "location_data,expected", + [ + ({"countryCode": "US", "country": "United States"}, ("US", None, None, None)), + ( + {"continentCode": "NA", "continent": "North America"}, + (None, "NA", "North America", None), + ), + ({"latitude": None, "longitude": None}, (None, None, None, None)), + (None, None), + ], + ids=["country-only", "continent-without-city", "null-coordinates", "no-location"], +) +def test_partial_locations(schema_160_body, location_data, expected): + schema_160_body["location"] = location_data + location = IpRiskResult._from_json(schema_160_body).location + if expected is None: + assert location is None + else: + assert location is not None + assert ( + location.country_code, + location.continent_code, + location.continent, + location.city, + ) == expected + assert location.latitude is None + assert location.longitude is None + assert location.postal_code is None + + +@pytest.mark.parametrize( + "domain,network_range", [(None, "192.0.2.0/24"), ("operator.example", None)] +) +def test_partial_network_fields(schema_160_body, domain, network_range): + schema_160_body["network"].update(domain=domain, range=network_range) + network = IpRiskResult._from_json(schema_160_body).network + assert network.domain == domain + assert network.range == network_range + + +@pytest.mark.parametrize( + "section,attribute", + [ + ("network", "domain"), + ("network", "range"), + ("location", "continent_code"), + ("location", "continent"), + ("location", "postal_code"), + ("location", "latitude"), + ("location", "longitude"), + ], +) +def test_new_fields_are_frozen(schema_160_body, section, attribute): + model = getattr(IpRiskResult._from_json(schema_160_body), section) + with pytest.raises(FrozenInstanceError): + setattr(model, attribute, None) + + +def test_legacy_positional_constructors_and_public_exports(): + from netriskscan import IpRiskResult as PublicResult + from netriskscan.models import IpLocation as ModelLocation + from netriskscan.models import IpNetwork as ModelNetwork + + assert PublicResult is IpRiskResult + assert ModelNetwork is IpNetwork + assert ModelLocation is IpLocation + for network in ( + IpNetwork("hosting", "direct", "AS64500", "Example"), + IpNetwork("hosting", "direct", "AS64500", "Example", "profile", "service"), + ): + assert network.organization == "Example" + assert network.domain is None + assert network.range is None + assert network.profile == "profile" + assert network.service == "service" + location = IpLocation("US", "United States", "NY", "New York", "Example", "America/New_York") + assert location.city == "Example" + assert location.time_zone == "America/New_York" + assert location.continent_code is None + assert location.continent is None + assert location.postal_code is None + assert location.latitude is None + assert location.longitude is None + + +@pytest.mark.parametrize("index", [0, None]) +@pytest.mark.parametrize("proxy", [True, False, None]) +def test_schema_160_preserves_score_and_flag_semantics(schema_160_body, index, proxy): + schema_160_body["risk"].update(index=index) + schema_160_body["flags"].update(proxy=proxy) + schema_160_body["network"]["futureField"] = {"value": True} + schema_160_body["location"]["futureField"] = [1, 2, 3] + result = IpRiskResult._from_json(schema_160_body) + assert result.risk.index is index + assert result.flags.proxy is proxy + assert result.risk.reasons == [] + assert result.network.domain == "operator.example" + assert result.location is not None + assert result.location.postal_code == "00501"