Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
53 changes: 53 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
25 changes: 24 additions & 1 deletion src/netriskscan/models/risk.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand All @@ -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"),
)


Expand Down Expand Up @@ -139,14 +147,24 @@ 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
region_code: str | None
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:
Expand All @@ -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"),
)


Expand Down
2 changes: 1 addition & 1 deletion src/netriskscan/version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
VERSION = "0.1.0"
VERSION = "0.2.0"
25 changes: 25 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand Down Expand Up @@ -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"},
Expand Down
34 changes: 33 additions & 1 deletion tests/test_async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
30 changes: 30 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Loading