internetdata 2.11.0__tar.gz → 2.12.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {internetdata-2.11.0 → internetdata-2.12.0}/PKG-INFO +1 -1
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/__init__.py +1 -1
- internetdata-2.12.0/src/internetdata/middleware/__init__.py +50 -0
- internetdata-2.12.0/src/internetdata/middleware/condition.py +177 -0
- internetdata-2.12.0/src/internetdata/middleware/core.py +374 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/testdata/testdata.json +5142 -0
- internetdata-2.12.0/tests/test_middleware.py +392 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/.gitignore +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/LICENSE +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/README.md +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/pyproject.toml +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/scripts/download-spec.sh +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/scripts/generate.sh +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/scripts/publish.sh +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/scripts/v2_subset.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/spec/openapi.yaml +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_bogons.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_core.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/__init__.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/__init__.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/account/__init__.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/account/account_identity.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/api_keys/__init__.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/api_keys/account_create_apikey.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/api_keys/account_list_apikeys.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/api_keys/account_reveal_apikey.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/api_keys/account_revoke_apikey.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/api_keys/account_rotate_apikey.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/authorization/__init__.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/authorization/oauth_authorize.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/authorization/oauth_device_authorization.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/authorization/oauth_metadata.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/authorization/oauth_register.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/authorization/oauth_revoke.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/authorization/oauth_token.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/database_v_2/__init__.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/database_v_2/database_checksum_v2.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/database_v_2/database_metadata_v2.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/database_v_2/download_database_v2.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/database_v_2/list_databases.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/database_v_2/list_downloads.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/entitlement/__init__.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/entitlement/my_entitlement.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/lookup/__init__.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/lookup/lookup_asn.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/lookup/lookup_batch.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/lookup/lookup_domain.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/lookup/lookup_ip.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/lookup/lookup_my_ip.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/organization/__init__.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/organization/account_org.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/api/organization/account_org_members.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/client.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/errors.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/__init__.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/abuse_contact.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/account_create_apikey_request.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/account_created_apikey.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/account_org.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/account_org_ref.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/account_org_wrap.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/account_rc.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/account_revealed_apikey.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/account_user.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/apikey_detail.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/apikey_list.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/asn.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/asn_lookup_response.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/asn_lookup_response_whois.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/asn_prefix.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/batch_lookup_error.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/batch_lookup_request.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/batch_lookup_response.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/batch_lookup_response_errors.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/batch_lookup_response_results.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/bit_torrent_detail.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/carrier_detail.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/class_detail.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/client_registration.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/client_registration_request.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/company.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/database.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/database_checksum_v2_response_200.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/database_format.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/database_license_type_type_1.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/database_license_type_type_2_type_1.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/database_license_type_type_3_type_1.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/database_metadata.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/database_metadata_column.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/database_metadata_sample.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/database_metadata_sample_additional_property_item.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/database_metadata_sample_size.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/database_metadata_schema.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/database_metadata_size.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/database_version.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/db_checksums.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/device_authorization.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/device_authorization_request.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/disposable_detail.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/dns_address_record.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/dns_cname_record.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/dns_mx_record.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/dns_ns_record.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/dns_resolver_detail.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/domain_dns.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/domain_ip_range.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/domain_ip_ranges.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/domain_lookup_response.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/download.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/download_outcome.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/entitlement.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/entitlement_apikey.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/entitlement_error.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/entitlement_plan.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/entitlement_plan_tier.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/entitlement_usage.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/error.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/hosted_domains.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/identity.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/list_databases_response_200.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/list_downloads_response_200.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/location.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/lookup_error.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/lookup_response.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/oauth_authorize_code_challenge_method.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/oauth_authorize_response_type.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/oauth_error.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/oauth_metadata.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/oauth_revoke_response_200.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/proxy_detail.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/pubproxy_detail.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/revoke_request.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/rwhois.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/satellite_detail.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/smtp_detail.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/ssh_detail.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/standing.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/token_request.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/token_response.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/web_detail.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/models/whois.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/_generated/types.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/aio.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/bogon.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/client.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/errors.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/models.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/src/internetdata/py.typed +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/testdata/bogons.json +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/tests/conftest.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/tests/helpers.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/tests/test_client.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/tests/test_conformance.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/tests/test_download.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/tests/test_lookup.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/tests/test_oauth.py +0 -0
- {internetdata-2.11.0 → internetdata-2.12.0}/tests/test_sharing.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: internetdata
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.12.0
|
|
4
4
|
Summary: Official Python client library for the InternetData API. Look up IP addresses, ASNs and domains, and download licensed IP databases.
|
|
5
5
|
Project-URL: Homepage, https://internetdata.io
|
|
6
6
|
Project-URL: Documentation, https://docs.internetdata.io
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""The framework-agnostic half of a web middleware.
|
|
2
|
+
|
|
3
|
+
What the framework adapters - internetdata-django, internetdata-flask,
|
|
4
|
+
internetdata-fastapi - are built on. Using it directly is how you support a framework
|
|
5
|
+
none of them cover.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from .condition import (
|
|
9
|
+
BlockCondition,
|
|
10
|
+
Conditions,
|
|
11
|
+
constraint_count,
|
|
12
|
+
matches,
|
|
13
|
+
missing_members,
|
|
14
|
+
validate,
|
|
15
|
+
)
|
|
16
|
+
from .core import (
|
|
17
|
+
DEFAULT_RETRIES,
|
|
18
|
+
DEFAULT_TIMEOUT,
|
|
19
|
+
AsyncCore,
|
|
20
|
+
Core,
|
|
21
|
+
Guard,
|
|
22
|
+
IpSelector,
|
|
23
|
+
Lookup,
|
|
24
|
+
MissingFieldAction,
|
|
25
|
+
Options,
|
|
26
|
+
RequestView,
|
|
27
|
+
Selectors,
|
|
28
|
+
bind_selectors,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"DEFAULT_RETRIES",
|
|
33
|
+
"DEFAULT_TIMEOUT",
|
|
34
|
+
"AsyncCore",
|
|
35
|
+
"BlockCondition",
|
|
36
|
+
"Conditions",
|
|
37
|
+
"Core",
|
|
38
|
+
"Guard",
|
|
39
|
+
"IpSelector",
|
|
40
|
+
"Lookup",
|
|
41
|
+
"MissingFieldAction",
|
|
42
|
+
"Options",
|
|
43
|
+
"RequestView",
|
|
44
|
+
"Selectors",
|
|
45
|
+
"bind_selectors",
|
|
46
|
+
"constraint_count",
|
|
47
|
+
"matches",
|
|
48
|
+
"missing_members",
|
|
49
|
+
"validate",
|
|
50
|
+
]
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""Deciding whether an answer is worth blocking.
|
|
2
|
+
|
|
3
|
+
The condition is written in the shape of a `Result` and keyed by the same names the
|
|
4
|
+
API uses, so what you write here reads like what you get back.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import dataclasses
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"BlockCondition",
|
|
14
|
+
"Conditions",
|
|
15
|
+
"constraint_count",
|
|
16
|
+
"matches",
|
|
17
|
+
"missing_members",
|
|
18
|
+
"validate",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
#: What makes a request worth blocking. Only the members you name are considered, and
|
|
22
|
+
#: they must all hold.
|
|
23
|
+
#:
|
|
24
|
+
#: A value may be a scalar (equality, strings without regard to case), a list meaning
|
|
25
|
+
#: any-of, a dict of ``gte``/``gt``/``lte``/``lt`` bounding a number, or a nested
|
|
26
|
+
#: condition. A member set to ``False`` or ``None`` is ignored entirely - a condition
|
|
27
|
+
#: states the positive signals you act on, so there is no way to write "block when this
|
|
28
|
+
#: is false", which would otherwise read as blocking everybody::
|
|
29
|
+
#:
|
|
30
|
+
#: {"location": {"country": ["CU", "IR", "KP"]}}
|
|
31
|
+
#: {"asn": {"type": "hosting"}}
|
|
32
|
+
#: {"is_vpn": True, "vpn": {"provider": "nordvpn"}}
|
|
33
|
+
#: {"is_resproxy": True, "resproxy": {"hits": {"gte": 5}}}
|
|
34
|
+
BlockCondition = dict[str, Any]
|
|
35
|
+
|
|
36
|
+
#: One condition, or a list of them meaning any one blocking is enough.
|
|
37
|
+
Conditions = BlockCondition | list[BlockCondition]
|
|
38
|
+
|
|
39
|
+
_BOUND_KEYS = frozenset({"gte", "gt", "lte", "lt"})
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def matches(condition: Conditions, result: Any) -> bool:
|
|
43
|
+
"""Whether an answer satisfies the condition, and should therefore be blocked."""
|
|
44
|
+
for one in _as_list(condition):
|
|
45
|
+
if _matches_object(one, result):
|
|
46
|
+
return True
|
|
47
|
+
return False
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def missing_members(condition: Conditions, result: Any) -> list[str]:
|
|
51
|
+
"""The members a condition names that this answer did not carry: a top-level member,
|
|
52
|
+
or a paid one inside an object every plan gets, by its path (``location.city``).
|
|
53
|
+
|
|
54
|
+
A field your plan does not include is absent rather than false, so a condition
|
|
55
|
+
naming one can never match and the block would silently never fire. A detail object
|
|
56
|
+
present but empty (every field None) is a real answer meaning the flag above it is
|
|
57
|
+
false, so nothing inside one is reported: ``vpn`` empty is not a plan gap. A
|
|
58
|
+
populated object carries every member the plan includes, so a member missing there
|
|
59
|
+
is one.
|
|
60
|
+
|
|
61
|
+
A locally answered bogon needs no special case: it is synthesized in the widest
|
|
62
|
+
shape, so every member is present and nothing reads as missing.
|
|
63
|
+
"""
|
|
64
|
+
missing: list[str] = []
|
|
65
|
+
for one in _as_list(condition):
|
|
66
|
+
_collect_missing(one, result, "", missing)
|
|
67
|
+
return missing
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def validate(condition: Conditions | None) -> None:
|
|
71
|
+
"""Refuse a condition that constrains nothing.
|
|
72
|
+
|
|
73
|
+
Ignoring ``False`` means ``{"is_vpn": False}`` and ``{}`` have no terms left to
|
|
74
|
+
satisfy, so they would match every answer and block all traffic. Nobody writes that
|
|
75
|
+
on purpose, and failing when the middleware is built beats discovering it in
|
|
76
|
+
production.
|
|
77
|
+
"""
|
|
78
|
+
if condition is None:
|
|
79
|
+
return
|
|
80
|
+
for one in _as_list(condition):
|
|
81
|
+
if constraint_count(one) == 0:
|
|
82
|
+
raise ValueError(
|
|
83
|
+
f"internetdata: block condition {one!r} constrains nothing, which would "
|
|
84
|
+
"block every request; a member set to False or None is ignored, so state "
|
|
85
|
+
"the positive signals you act on"
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def constraint_count(condition: Any) -> int:
|
|
90
|
+
"""How many leaf constraints a condition actually carries."""
|
|
91
|
+
if condition is None or condition is False:
|
|
92
|
+
return 0
|
|
93
|
+
if isinstance(condition, dict):
|
|
94
|
+
if _is_bound(condition):
|
|
95
|
+
return 1
|
|
96
|
+
return sum(constraint_count(value) for value in condition.values())
|
|
97
|
+
if isinstance(condition, (list, tuple, set, frozenset)):
|
|
98
|
+
return sum(constraint_count(entry) for entry in condition)
|
|
99
|
+
return 1
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _as_list(condition: Conditions) -> list[BlockCondition]:
|
|
103
|
+
if isinstance(condition, list):
|
|
104
|
+
return condition
|
|
105
|
+
return [condition]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _collect_missing(
|
|
109
|
+
condition: BlockCondition, value: Any, prefix: str, missing: list[str]
|
|
110
|
+
) -> None:
|
|
111
|
+
for member, want in condition.items():
|
|
112
|
+
if constraint_count(want) == 0:
|
|
113
|
+
continue
|
|
114
|
+
path = f"{prefix}{member}"
|
|
115
|
+
got = getattr(value, member, None)
|
|
116
|
+
if got is None:
|
|
117
|
+
if path not in missing:
|
|
118
|
+
missing.append(path)
|
|
119
|
+
continue
|
|
120
|
+
if isinstance(want, dict) and not _is_bound(want) and _populated(got):
|
|
121
|
+
_collect_missing(want, got, f"{path}.", missing)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _populated(value: Any) -> bool:
|
|
125
|
+
"""Whether a member is an object holding at least one field: an empty detail object
|
|
126
|
+
is the answer under a false flag, never a plan gap."""
|
|
127
|
+
if not dataclasses.is_dataclass(value) or isinstance(value, type):
|
|
128
|
+
return False
|
|
129
|
+
return any(getattr(value, field.name) is not None for field in dataclasses.fields(value))
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _matches_object(condition: BlockCondition, value: Any) -> bool:
|
|
133
|
+
for member, want in condition.items():
|
|
134
|
+
if constraint_count(want) == 0:
|
|
135
|
+
continue
|
|
136
|
+
if not _matches_value(want, getattr(value, member, None)):
|
|
137
|
+
return False
|
|
138
|
+
return True
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _matches_value(want: Any, got: Any) -> bool:
|
|
142
|
+
"""Whether one value satisfies one want.
|
|
143
|
+
|
|
144
|
+
An ABSENT member arrives here as ``None``, which is exactly what "not in your plan"
|
|
145
|
+
looks like. Every branch below must therefore reject it, which is what makes an
|
|
146
|
+
unserved member fail a match rather than pass it. A new branch that does not would
|
|
147
|
+
silently let a member nobody was served block a request.
|
|
148
|
+
"""
|
|
149
|
+
if isinstance(want, (list, tuple, set, frozenset)):
|
|
150
|
+
return any(_matches_value(entry, got) for entry in want)
|
|
151
|
+
if isinstance(want, dict):
|
|
152
|
+
if _is_bound(want):
|
|
153
|
+
return _matches_bound(want, got)
|
|
154
|
+
return _matches_object(want, got)
|
|
155
|
+
if isinstance(want, str) and isinstance(got, str):
|
|
156
|
+
# Providers are lowercase slugs and countries uppercase codes on the wire, and a
|
|
157
|
+
# caller should not have to know which, so a string compares without case.
|
|
158
|
+
return want.casefold() == got.casefold()
|
|
159
|
+
if isinstance(want, bool) or isinstance(got, bool):
|
|
160
|
+
return want is got
|
|
161
|
+
return bool(want == got)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _matches_bound(bound: dict[str, Any], got: Any) -> bool:
|
|
165
|
+
if isinstance(got, bool) or not isinstance(got, (int, float)):
|
|
166
|
+
return False
|
|
167
|
+
if "gte" in bound and got < bound["gte"]:
|
|
168
|
+
return False
|
|
169
|
+
if "gt" in bound and got <= bound["gt"]:
|
|
170
|
+
return False
|
|
171
|
+
if "lte" in bound and got > bound["lte"]:
|
|
172
|
+
return False
|
|
173
|
+
return not ("lt" in bound and got >= bound["lt"])
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _is_bound(value: dict[str, Any]) -> bool:
|
|
177
|
+
return len(value) > 0 and _BOUND_KEYS.issuperset(value)
|
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
"""The framework-agnostic half of a web middleware.
|
|
2
|
+
|
|
3
|
+
An adapter - internetdata-django, internetdata-flask, internetdata-fastapi - keeps
|
|
4
|
+
only the parts that are genuinely framework-shaped and shares everything here, so the
|
|
5
|
+
shared conformance corpus is asserted once for Python rather than once per framework.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from typing import Generic, Literal, TypeVar
|
|
14
|
+
|
|
15
|
+
from .._core import DEFAULT_BASE_URL, check_timeout
|
|
16
|
+
from ..aio import AsyncInternetData
|
|
17
|
+
from ..bogon import is_bogon
|
|
18
|
+
from ..client import InternetData
|
|
19
|
+
from ..errors import InternetDataError
|
|
20
|
+
from ..models import Result
|
|
21
|
+
from .condition import Conditions, matches, missing_members, validate
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"AsyncCore",
|
|
25
|
+
"Core",
|
|
26
|
+
"Guard",
|
|
27
|
+
"IpSelector",
|
|
28
|
+
"Lookup",
|
|
29
|
+
"Options",
|
|
30
|
+
"RequestView",
|
|
31
|
+
"Selectors",
|
|
32
|
+
"bind_selectors",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
Req = TypeVar("Req")
|
|
36
|
+
|
|
37
|
+
#: How the client address is decided.
|
|
38
|
+
#:
|
|
39
|
+
#: There is no portable answer: a framework's own accessor may return the socket peer,
|
|
40
|
+
#: or may already have walked a proxy chain, depending on the framework and on how the
|
|
41
|
+
#: application configured it. You know your framework and your edge, so this is yours
|
|
42
|
+
#: to choose.
|
|
43
|
+
IpSelector = Callable[[Req], "str | None"]
|
|
44
|
+
|
|
45
|
+
#: What to do when a condition names a member the plan does not serve.
|
|
46
|
+
MissingFieldAction = Literal["warn", "raise", "ignore"]
|
|
47
|
+
|
|
48
|
+
_log = logging.getLogger("internetdata")
|
|
49
|
+
|
|
50
|
+
# Defaults set for a request path rather than for a script: failing open quickly beats
|
|
51
|
+
# holding a visitor while we try again.
|
|
52
|
+
DEFAULT_TIMEOUT = 2.5
|
|
53
|
+
DEFAULT_RETRIES = 0
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True, slots=True)
|
|
57
|
+
class RequestView:
|
|
58
|
+
"""Enough of an incoming request for a selector to work with, whatever framework it
|
|
59
|
+
came from. An adapter supplies one of these per request."""
|
|
60
|
+
|
|
61
|
+
#: A request header by name, case-insensitively.
|
|
62
|
+
header: Callable[[str], str | None]
|
|
63
|
+
#: The framework's own client-address accessor, whatever that resolves to here.
|
|
64
|
+
framework_ip: Callable[[], str | None]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass(frozen=True, slots=True)
|
|
68
|
+
class Lookup:
|
|
69
|
+
"""What a middleware attached to the request, whether or not it succeeded."""
|
|
70
|
+
|
|
71
|
+
#: Whether the condition matched. Always False when no condition was configured.
|
|
72
|
+
blocked: bool
|
|
73
|
+
#: The address that was classified, as the selector resolved it.
|
|
74
|
+
ip: str | None = None
|
|
75
|
+
#: The answer. None when the lookup failed.
|
|
76
|
+
result: Result | None = None
|
|
77
|
+
#: Why the lookup failed. None when it succeeded.
|
|
78
|
+
error: Exception | None = None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass(slots=True)
|
|
82
|
+
class Options(Generic[Req]):
|
|
83
|
+
"""How a middleware behaves. Everything is optional, though a server almost
|
|
84
|
+
certainly wants an api_key: without one a lookup is on Unlimited, the free plan, and
|
|
85
|
+
every lookup shares the per-minute limit of the server's one address."""
|
|
86
|
+
|
|
87
|
+
#: An existing client to use. Prefer this if you already hold one: two clients mean
|
|
88
|
+
#: two caches, and a cache is per instance because two keys can be on different
|
|
89
|
+
#: plans and entitled to different fields.
|
|
90
|
+
client: InternetData | AsyncInternetData | None = None
|
|
91
|
+
api_key: str | None = None
|
|
92
|
+
base_url: str | None = None
|
|
93
|
+
#: How long a lookup may hold the request, in seconds. Defaults to 2.5, a much
|
|
94
|
+
#: tighter bound than a client's own. Applied to each lookup rather than to the
|
|
95
|
+
#: client, so it holds for a ``client`` you pass in without changing that client's
|
|
96
|
+
#: timeout for anything else it does. Anything that is not a finite number above
|
|
97
|
+
#: 0 is a ``ValueError`` when the middleware is built.
|
|
98
|
+
timeout: float = DEFAULT_TIMEOUT
|
|
99
|
+
#: Retry attempts for a transient failure. Defaults to 0, unlike the client's 2.
|
|
100
|
+
retries: int = DEFAULT_RETRIES
|
|
101
|
+
#: How the client address is decided. Defaults to the framework's own accessor.
|
|
102
|
+
ip_selector: IpSelector[Req] | None = None
|
|
103
|
+
#: What to block on. Leave it None to only enrich the request and leave the
|
|
104
|
+
#: decision to your own code.
|
|
105
|
+
block_condition: Conditions | None = None
|
|
106
|
+
#: Block when the lookup itself fails. Defaults to False, so our outage does not
|
|
107
|
+
#: become yours.
|
|
108
|
+
fail_closed: bool = False
|
|
109
|
+
#: What to do when the condition names a member your plan does not serve.
|
|
110
|
+
on_missing_field: MissingFieldAction = "warn"
|
|
111
|
+
#: Skip classification for this request entirely.
|
|
112
|
+
skip: Callable[[Req], bool] | None = None
|
|
113
|
+
#: Where warnings go. Defaults to the "internetdata" logger.
|
|
114
|
+
on_warn: Callable[[str], None] | None = None
|
|
115
|
+
_warned: set[str] = field(default_factory=set, repr=False)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class _Base(Generic[Req]):
|
|
119
|
+
def __init__(self, options: Options[Req], default_ip_selector: IpSelector[Req]) -> None:
|
|
120
|
+
validate(options.block_condition)
|
|
121
|
+
check_timeout(options.timeout)
|
|
122
|
+
self._options = options
|
|
123
|
+
self._condition = options.block_condition
|
|
124
|
+
self._selector = options.ip_selector or default_ip_selector
|
|
125
|
+
self._warned: set[str] = set()
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def blocking(self) -> bool:
|
|
129
|
+
"""Whether a condition was configured at all."""
|
|
130
|
+
return self._condition is not None
|
|
131
|
+
|
|
132
|
+
def _warn(self, message: str) -> None:
|
|
133
|
+
_warn_once(self._warned, self._options.on_warn, message)
|
|
134
|
+
|
|
135
|
+
def _resolve(self, request: Req) -> str | Lookup:
|
|
136
|
+
ip = (self._selector(request) or "").strip()
|
|
137
|
+
if not ip:
|
|
138
|
+
self._warn(
|
|
139
|
+
"could not resolve a client address from this request; pass an "
|
|
140
|
+
"ip_selector that knows where yours comes from"
|
|
141
|
+
)
|
|
142
|
+
return Lookup(
|
|
143
|
+
blocked=self._options.fail_closed,
|
|
144
|
+
error=InternetDataError("bad_request", "no client address on the request"),
|
|
145
|
+
)
|
|
146
|
+
if is_bogon(ip):
|
|
147
|
+
# Expected in local development. Anywhere else it means a proxy sits in
|
|
148
|
+
# front and its own address is what reached us.
|
|
149
|
+
self._warn(
|
|
150
|
+
f"resolved the client address as {ip}, which is not a public address. "
|
|
151
|
+
"If this application runs behind a proxy or load balancer, configure "
|
|
152
|
+
"its trusted-proxy setting or pass an ip_selector that reads your "
|
|
153
|
+
"edge's header."
|
|
154
|
+
)
|
|
155
|
+
return ip
|
|
156
|
+
|
|
157
|
+
def _decide(self, ip: str, result: Result) -> Lookup:
|
|
158
|
+
if self._condition is not None:
|
|
159
|
+
self._report_missing(result)
|
|
160
|
+
return Lookup(
|
|
161
|
+
blocked=self._condition is not None and matches(self._condition, result),
|
|
162
|
+
ip=ip,
|
|
163
|
+
result=result,
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
def _failed(self, ip: str, error: Exception) -> Lookup:
|
|
167
|
+
return Lookup(blocked=self._options.fail_closed, ip=ip, error=error)
|
|
168
|
+
|
|
169
|
+
def _report_missing(self, result: Result) -> None:
|
|
170
|
+
if self._condition is None:
|
|
171
|
+
return
|
|
172
|
+
_report_missing(
|
|
173
|
+
"block_condition", self._condition, result, self._options.on_missing_field, self._warn
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class Core(_Base[Req]):
|
|
178
|
+
"""Resolve an address, classify it, and decide whether the condition matched.
|
|
179
|
+
|
|
180
|
+
For a WSGI framework - Django, Flask - where the request path is synchronous.
|
|
181
|
+
"""
|
|
182
|
+
|
|
183
|
+
def __init__(self, options: Options[Req], default_ip_selector: IpSelector[Req]) -> None:
|
|
184
|
+
super().__init__(options, default_ip_selector)
|
|
185
|
+
client = options.client
|
|
186
|
+
if client is None:
|
|
187
|
+
client = InternetData(
|
|
188
|
+
api_key=options.api_key, base_url=options.base_url or DEFAULT_BASE_URL
|
|
189
|
+
)
|
|
190
|
+
if isinstance(client, AsyncInternetData):
|
|
191
|
+
raise TypeError("Core needs a InternetData; use AsyncCore for an async client")
|
|
192
|
+
self._client = client
|
|
193
|
+
|
|
194
|
+
def evaluate(self, request: Req) -> Lookup | None:
|
|
195
|
+
"""Classify one request. Answers None when skip claimed it."""
|
|
196
|
+
if self._options.skip is not None and self._options.skip(request):
|
|
197
|
+
return None
|
|
198
|
+
resolved = self._resolve(request)
|
|
199
|
+
if isinstance(resolved, Lookup):
|
|
200
|
+
return resolved
|
|
201
|
+
try:
|
|
202
|
+
result = self._client.lookup(
|
|
203
|
+
resolved, retries=self._options.retries, timeout=self._options.timeout
|
|
204
|
+
)
|
|
205
|
+
except Exception as error: # noqa: BLE001 - a failed lookup must never propagate
|
|
206
|
+
return self._failed(resolved, error)
|
|
207
|
+
return self._decide(resolved, result)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
class AsyncCore(_Base[Req]):
|
|
211
|
+
"""The same, for an ASGI framework - FastAPI, Starlette, Litestar."""
|
|
212
|
+
|
|
213
|
+
def __init__(self, options: Options[Req], default_ip_selector: IpSelector[Req]) -> None:
|
|
214
|
+
super().__init__(options, default_ip_selector)
|
|
215
|
+
client = options.client
|
|
216
|
+
if client is None:
|
|
217
|
+
client = AsyncInternetData(
|
|
218
|
+
api_key=options.api_key, base_url=options.base_url or DEFAULT_BASE_URL
|
|
219
|
+
)
|
|
220
|
+
if not isinstance(client, AsyncInternetData):
|
|
221
|
+
raise TypeError("AsyncCore needs an AsyncInternetData; use Core for a sync client")
|
|
222
|
+
self._client = client
|
|
223
|
+
|
|
224
|
+
async def evaluate(self, request: Req) -> Lookup | None:
|
|
225
|
+
"""Classify one request. Answers None when skip claimed it."""
|
|
226
|
+
if self._options.skip is not None and self._options.skip(request):
|
|
227
|
+
return None
|
|
228
|
+
resolved = self._resolve(request)
|
|
229
|
+
if isinstance(resolved, Lookup):
|
|
230
|
+
return resolved
|
|
231
|
+
try:
|
|
232
|
+
result = await self._client.lookup(
|
|
233
|
+
resolved, retries=self._options.retries, timeout=self._options.timeout
|
|
234
|
+
)
|
|
235
|
+
except Exception as error: # noqa: BLE001 - a failed lookup must never propagate
|
|
236
|
+
return self._failed(resolved, error)
|
|
237
|
+
return self._decide(resolved, result)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
class Guard:
|
|
241
|
+
"""A block condition for one view, judged against the answer a middleware already
|
|
242
|
+
attached to the request.
|
|
243
|
+
|
|
244
|
+
A middleware is one instance for the whole application, so its ``block_condition``
|
|
245
|
+
refuses on every view. An adapter's per-view check holds one of these instead: it
|
|
246
|
+
reads the attached :class:`Lookup` and makes no request of its own, so a visitor is
|
|
247
|
+
still looked up once however many views judge them.
|
|
248
|
+
"""
|
|
249
|
+
|
|
250
|
+
def __init__(
|
|
251
|
+
self,
|
|
252
|
+
condition: Conditions,
|
|
253
|
+
*,
|
|
254
|
+
fail_closed: bool = False,
|
|
255
|
+
on_missing_field: MissingFieldAction = "warn",
|
|
256
|
+
on_warn: Callable[[str], None] | None = None,
|
|
257
|
+
name: str = "block condition",
|
|
258
|
+
) -> None:
|
|
259
|
+
if condition is None:
|
|
260
|
+
raise ValueError("internetdata: a per-view check needs a condition to block on")
|
|
261
|
+
validate(condition)
|
|
262
|
+
self._condition = condition
|
|
263
|
+
self._fail_closed = fail_closed
|
|
264
|
+
self._on_missing_field = on_missing_field
|
|
265
|
+
self._on_warn = on_warn
|
|
266
|
+
self._name = name
|
|
267
|
+
self._warned: set[str] = set()
|
|
268
|
+
|
|
269
|
+
def blocks(self, lookup: Lookup) -> bool:
|
|
270
|
+
"""Whether this view refuses the visitor the middleware classified.
|
|
271
|
+
|
|
272
|
+
A failed lookup carries no answer to judge, so it blocks only with
|
|
273
|
+
``fail_closed``. A condition naming a member the plan does not serve is reported
|
|
274
|
+
once, as the middleware reports its own.
|
|
275
|
+
"""
|
|
276
|
+
if lookup.result is None:
|
|
277
|
+
return self._fail_closed
|
|
278
|
+
_report_missing(
|
|
279
|
+
self._name,
|
|
280
|
+
self._condition,
|
|
281
|
+
lookup.result,
|
|
282
|
+
self._on_missing_field,
|
|
283
|
+
lambda message: _warn_once(self._warned, self._on_warn, message),
|
|
284
|
+
)
|
|
285
|
+
return matches(self._condition, lookup.result)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _report_missing(
|
|
289
|
+
name: str,
|
|
290
|
+
condition: Conditions,
|
|
291
|
+
result: Result,
|
|
292
|
+
action: MissingFieldAction,
|
|
293
|
+
warn: Callable[[str], None],
|
|
294
|
+
) -> None:
|
|
295
|
+
if action == "ignore":
|
|
296
|
+
return
|
|
297
|
+
missing = missing_members(condition, result)
|
|
298
|
+
if not missing:
|
|
299
|
+
return
|
|
300
|
+
message = (
|
|
301
|
+
f"{name} names {', '.join(missing)}, which your plan does not include, so those "
|
|
302
|
+
'terms can never match. An absent member means "not in your plan", not "checked, '
|
|
303
|
+
'and no".'
|
|
304
|
+
)
|
|
305
|
+
if action == "raise":
|
|
306
|
+
raise ValueError(f"internetdata: {message}")
|
|
307
|
+
warn(message)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
# A misconfiguration is the same on every request, so saying so once is a warning and
|
|
311
|
+
# saying so a million times is an outage of its own.
|
|
312
|
+
def _warn_once(warned: set[str], on_warn: Callable[[str], None] | None, message: str) -> None:
|
|
313
|
+
if message in warned:
|
|
314
|
+
return
|
|
315
|
+
warned.add(message)
|
|
316
|
+
if on_warn is not None:
|
|
317
|
+
on_warn(message)
|
|
318
|
+
else:
|
|
319
|
+
_log.warning("%s", message)
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
@dataclass(frozen=True, slots=True)
|
|
323
|
+
class Selectors(Generic[Req]):
|
|
324
|
+
"""The shared selectors, bound to one framework's request type."""
|
|
325
|
+
|
|
326
|
+
#: The framework's own client-address accessor. What that resolves to depends on
|
|
327
|
+
#: the framework and on how you configured it.
|
|
328
|
+
default: IpSelector[Req]
|
|
329
|
+
#: An address from ``X-Forwarded-For``.
|
|
330
|
+
#:
|
|
331
|
+
#: The LEFT-MOST entry is whatever the caller sent, because proxies append, so a
|
|
332
|
+
#: visitor who sets the header themselves appears first and this returns their
|
|
333
|
+
#: forgery. It is only trustworthy when an edge you control overwrites the header.
|
|
334
|
+
#: When you know how many proxies sit in front, count from the right with ``depth``:
|
|
335
|
+
#: 1 is the address your nearest proxy saw.
|
|
336
|
+
xff: Callable[..., IpSelector[Req]]
|
|
337
|
+
#: An address from a single-value header, for an edge that writes one -
|
|
338
|
+
#: ``header("CF-Connecting-IP")`` behind Cloudflare. Falls back to the framework's
|
|
339
|
+
#: accessor when the header is absent.
|
|
340
|
+
header: Callable[[str], IpSelector[Req]]
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def bind_selectors(view: Callable[[Req], RequestView]) -> Selectors[Req]:
|
|
344
|
+
"""Give an adapter the shared selectors under its own request type.
|
|
345
|
+
|
|
346
|
+
The adapter passes a function exposing its request once, so a caller writing a
|
|
347
|
+
custom selector still works with the object they know.
|
|
348
|
+
"""
|
|
349
|
+
|
|
350
|
+
def default(request: Req) -> str | None:
|
|
351
|
+
return view(request).framework_ip()
|
|
352
|
+
|
|
353
|
+
def xff(depth: int = 0) -> IpSelector[Req]:
|
|
354
|
+
def select(request: Req) -> str | None:
|
|
355
|
+
seen = view(request)
|
|
356
|
+
raw = seen.header("X-Forwarded-For") or ""
|
|
357
|
+
chain = [entry.strip() for entry in raw.split(",") if entry.strip()]
|
|
358
|
+
if not chain:
|
|
359
|
+
return seen.framework_ip()
|
|
360
|
+
if depth <= 0 or depth > len(chain):
|
|
361
|
+
return chain[0]
|
|
362
|
+
return chain[-depth]
|
|
363
|
+
|
|
364
|
+
return select
|
|
365
|
+
|
|
366
|
+
def header(name: str) -> IpSelector[Req]:
|
|
367
|
+
def select(request: Req) -> str | None:
|
|
368
|
+
seen = view(request)
|
|
369
|
+
value = (seen.header(name) or "").strip()
|
|
370
|
+
return value or seen.framework_ip()
|
|
371
|
+
|
|
372
|
+
return select
|
|
373
|
+
|
|
374
|
+
return Selectors(default=default, xff=xff, header=header)
|