diff --git a/CHANGELOG.md b/CHANGELOG.md index d1183dd..2dfe657 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,23 @@ # Changelog +## 0.4.0 + +- Added `str` enums for the fixed values the API and webhooks send: + `Signal`, `SuspectLevel`, `Confidence`, `EventState`, `Environment`, + `AttestationState`, `AttestationStatus`, `AttestSkippedReason`, + `VerifyReason` and `WebhookEventType`. Every member equals and hashes like + its raw string, so `event.suspect_level == SuspectLevel.HIGH` and + `Signal.FINGERPRINT_SUPPRESSED in signals` work on parsed events. Model + fields stay typed `str` and hold the value as sent, so a value a newer + server adds still parses as a plain string. +- `VerifyReason` is an enum class instead of a `Literal` alias, and + `VerifyResult.reason` is a `VerifyReason` member: `VerifyReason.OK` (equal + to `""`) when `ok`, otherwise the failed check. This is a breaking change + for type checkers; the runtime values are the same strings. +- `Signal` and `SIGNAL_NAMES` match the server: they include + `repeated_reinstall`, `device_activity_high` and + `device_activity_very_high`, and no longer list `app_attest_key_churn`. + ## 0.3.0 - Added `fingerly.events.verify(request_id, max_age_seconds=300, tag=None, diff --git a/README.md b/README.md index e4b8cfb..1f6689f 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ Two clients share one API: `Fingerly` for synchronous code such as Django and Fl **2. Install.** ```sh -pip install "fingerly>=0.3.0" +pip install "fingerly>=0.4.0" ``` **3. Read an event.** @@ -71,7 +71,7 @@ import os from flask import Flask, abort, request -from fingerly import verify_webhook +from fingerly import WebhookEventType, verify_webhook app = Flask(__name__) @@ -86,7 +86,8 @@ def fingerly_webhook(): ): abort(400) delivery = request.get_json() - print(delivery["type"]) + if delivery["type"] == WebhookEventType.VISITOR_SUSPECT: + print(delivery["data"]) return "", 204 ``` @@ -151,7 +152,16 @@ The archived `document` arrives moments after the event itself, so check `has_do - `ip_network` is the network the request came from (an IPv4 /24 or an IPv6 /40, such as `203.0.113.0/24`); the API never returns the address. - When a submission is unidentifiable (`event.identifiable is False`, such as insufficient entropy, a genuine embedded WebView, or an unmatched high-risk Web payload), `event.visitor_id` is `""`. There are no `deferred_token`, `deferred_signals` or `supplements` fields in `v: 3`. - `document`, when available, is an allow-listed view of the archived request with no raw signals, user agent or address. `event.parse_document()` decodes it into a typed `EventDocument` (including `attestation: Optional[Attestation]`). A native `Attestation` also carries `attest_skipped` (the app's reason for sending no proof) and `downgrade` (the report named an install an attested device owns). -- `SIGNAL_NAMES` lists the canonical signal identifiers, including the `v: 3` anti-spoofing and integrity signals `"attestation_failed"`, `"attestation_downgrade"`, `"device_inconsistent"`, `"report_incomplete"`, `"probe_errors"`, `"fetch_metadata_missing"`, `"web_ticket_missing"`, `"web_ticket_invalid"`, `"tampering"`, `"custom_root_ca"` and `"secondary_user_profile"`. +- `suspect_level`, `state`, `environment`, each trigger's `signal` and `confidence`, and an `Attestation`'s `state`, `status` and `attest_skipped` hold the string the API sent. Compare them with the matching enum: `SuspectLevel`, `EventState`, `Environment`, `Signal`, `Confidence`, `AttestationState`, `AttestationStatus` and `AttestSkippedReason`. Every member is a `str` equal to its value, so `event.suspect_level == SuspectLevel.HIGH` and `Signal.FINGERPRINT_SUPPRESSED in signals` work on plain strings, and a value a newer server adds still parses. Compare rather than convert: `SuspectLevel(value)` raises `ValueError` for a value this release does not know. +- `Signal` names every signal group and detector, including the `v: 3` anti-spoofing and integrity signals `ATTESTATION_FAILED`, `ATTESTATION_DOWNGRADE`, `DEVICE_INCONSISTENT`, `REPORT_INCOMPLETE`, `PROBE_ERRORS`, `FETCH_METADATA_MISSING`, `WEB_TICKET_MISSING`, `WEB_TICKET_INVALID`, `TAMPERING`, `CUSTOM_ROOT_CA` and `SECONDARY_USER_PROFILE`. `SIGNAL_NAMES` holds the same values as plain strings. + +```python +from fingerly import Signal, SuspectLevel + +signals = [trigger.signal for trigger in event.triggers] +if event.suspect_level == SuspectLevel.HIGH or Signal.FINGERPRINT_SUPPRESSED in signals: + send_to_review(event) +``` - `suspect_score` is `None` when the request was not scored, and must not be treated as zero. - `project_id` is the UUID string of the Fingerly project the event belongs to, on both `events.get` and the rows of `events.list`; it is `None` when an older server does not send it. - `Event` declares every documented field as an attribute and falls back to the decoded body for fields added later, so a new server field needs no SDK upgrade. @@ -164,24 +174,28 @@ The archived `document` arrives moments after the event itself, so check `has_do Send the browser's `requestId` to your server and verify it there with a server-only key. `fingerly.events.verify` reads the event and runs these checks in order, stopping at the first that fails: -| Order | Reason | Fails when | -| --- | --- | --- | -| 1 | `not_found` | The event does not exist for this key's environment. | -| 2 | `too_old` | It occurred more than `max_age_seconds` ago (300 by default). A missing or unreadable `occurred_at` fails too. | -| 3 | `tag_mismatch` | You passed `tag` and the event's tag is not exactly that. | -| 4 | `unidentifiable` | The event has no visitor id. | -| 5 | `unscored` | The event has no `suspect_score`. | -| 6 | `already_consumed` | The event was consumed before. | +| Order | Reason | `VerifyReason` | Fails when | +| --- | --- | --- | --- | +| 1 | `not_found` | `NOT_FOUND` | The event does not exist for this key's environment. | +| 2 | `too_old` | `TOO_OLD` | It occurred more than `max_age_seconds` ago (300 by default). A missing or unreadable `occurred_at` fails too. | +| 3 | `tag_mismatch` | `TAG_MISMATCH` | You passed `tag` and the event's tag is not exactly that. | +| 4 | `unidentifiable` | `UNIDENTIFIABLE` | The event has no visitor id. | +| 5 | `unscored` | `UNSCORED` | The event has no `suspect_score`. | +| 6 | `already_consumed` | `ALREADY_CONSUMED` | The event was consumed before. | -Consumption comes last, only when every other check passed, so one event backs one decision: a replayed `requestId` answers `already_consumed`. Pass `consume=False` to check without consuming. The result is a `VerifyResult` with `ok`, `reason` (`""` when `ok`) and `event` (`None` only for `not_found`). +Consumption comes last, only when every other check passed, so one event backs one decision: a replayed `requestId` answers `already_consumed`. Pass `consume=False` to check without consuming. The result is a `VerifyResult` with `ok`, `reason` (a `VerifyReason`, `VerifyReason.OK` or `""` when `ok`, and equal to the strings above otherwise) and `event` (`None` only for `not_found`). `verify` never judges the score: that policy stays with you. Check `suspect_level` or `suspect_score` after `ok`. ```python +from fingerly import SuspectLevel, VerifyReason + result = fingerly.events.verify(request_id, tag="checkout") -if not result.ok: +if result.reason == VerifyReason.ALREADY_CONSUMED: + refuse_replay() +elif not result.ok: refuse(result.reason) -elif result.event.suspect_level == "high": +elif result.event.suspect_level == SuspectLevel.HIGH: send_to_review(result.event) else: allow() @@ -234,7 +248,7 @@ A `503` or a transport failure leaves the token held, and the SDK retries the id The example under [Getting started](#getting-started) verifies a delivery in Flask. -`identification.completed` and `visitor.suspect` deliveries carry the event's project as `data["project_id"]`; `identification.refused` carries it only when the refused request named a known key. The SDK passes the payload through unmodelled, so read it from the parsed JSON. +`identification.completed` and `visitor.suspect` deliveries carry the event's project as `data["project_id"]`; `identification.refused` carries it only when the refused request named a known key. The SDK passes the payload through unmodelled, so read it from the parsed JSON. Compare its `type` with `WebhookEventType` (`IDENTIFICATION_COMPLETED`, `IDENTIFICATION_REFUSED`, `VISITOR_SUSPECT`, `BILLING_STATUS_CHANGED`, `USAGE_DAILY_SETTLED`, and `WEBHOOK_TEST` from **Send test event**), and ignore types you do not handle. Verify the exact raw bytes before JSON parsing. Signatures cover the timestamp and body. The default replay tolerance is 300 seconds; persist processed webhook IDs to deduplicate deliveries. During signing-secret rotation, any matching signature in the comma-separated header is accepted; only the first 32 are read. The function never raises for malformed input: bad input is a failed verification, not an exception. @@ -301,7 +315,7 @@ Responses are marked `no-store`. A redirect is never followed, whatever transpor Incoming headers follow the sanitize-and-restore sequence: all incoming `x-fingerly-*`, `cookie` and `authorization` headers are stripped, restoring `x-fingerly-sdk-platform` only when it matches an exact lowercase native or bridge platform (`ios`, `android`, `react-native`, `react-native-ios`, `react-native-android`, `flutter`, `flutter-ios`, `flutter-android`, `lynx-ios`, `lynx-android`, `capacitor`, `kotlin-multiplatform`). Requests carrying neither `Origin` nor a validated `x-fingerly-sdk-platform` are rejected locally with `400` (`missing_origin`), and `x-fingerly-origin` is never synthesized from `Host`, `Referer` or the request URL. Exactly one channel goes upstream: a request with an `Origin` is forwarded as a browser call with `x-fingerly-origin` and without the platform header, as the API treats the same request sent to it directly. -Alongside verified proxy metadata (`x-fingerly-host` included), only `content-type`, `x-api-key`, `user-agent`, `idempotency-key`, `sec-fetch-*` and `sec-ch-ua-*` are forwarded. Customer cookies and authorization headers are never passed on. The proxy reports itself upstream as `python/0.3.0` in `x-fingerly-proxy-version`, which the dashboard shows per proxy, and sends `fingerly-python/0.3.0` as its user agent. +Alongside verified proxy metadata (`x-fingerly-host` included), only `content-type`, `x-api-key`, `user-agent`, `idempotency-key`, `sec-fetch-*` and `sec-ch-ua-*` are forwarded. Customer cookies and authorization headers are never passed on. The proxy reports itself upstream as `python/0.4.0` in `x-fingerly-proxy-version`, which the dashboard shows per proxy, and sends `fingerly-python/0.4.0` as its user agent. Back to the browser it relays only `content-type`, `x-request-id`, `ratelimit-limit`, `ratelimit-remaining` and `retry-after`, plus its own `cache-control: no-store` and a `content-length` for the decoded body. A content blocker can match a response header by name, so an allowlist is what keeps anything naming Fingerly off the page. @@ -609,7 +623,7 @@ The vendored synthetic contract snapshot makes tests independent of sibling repo
Source structure -`_client.py` holds both clients and their event reads. `_http.py` is the connection pool both clients and the proxy send through, with its deadline and body cap. `_transport.py` builds requests and interprets responses, so the two clients share one definition of what a request is and what a failure means. `_models.py` owns `Event`, `EventPage` and their parsing. `_webhooks.py` verifies signatures. `_proxy.py` owns every proxy decision, with `_asgi.py` and `_wsgi.py` as thin adapters that only read a request and write a response, so the two standards cannot drift apart. `_config.py` validates every caller-supplied option: keys, origins, API versions and durations, all before any network access. `_errors.py` holds the exception hierarchy. `_version.py` holds the version everything else reads. `__init__.py` only exposes the public API. +`_client.py` holds both clients and their event reads. `_http.py` is the connection pool both clients and the proxy send through, with its deadline and body cap. `_transport.py` builds requests and interprets responses, so the two clients share one definition of what a request is and what a failure means. `_models.py` owns `Event`, `EventPage` and their parsing. `_enums.py` holds the string enums the models and webhooks compare against. `_webhooks.py` verifies signatures. `_proxy.py` owns every proxy decision, with `_asgi.py` and `_wsgi.py` as thin adapters that only read a request and write a response, so the two standards cannot drift apart. `_config.py` validates every caller-supplied option: keys, origins, API versions and durations, all before any network access. `_errors.py` holds the exception hierarchy. `_version.py` holds the version everything else reads. `__init__.py` only exposes the public API.
diff --git a/src/fingerly/__init__.py b/src/fingerly/__init__.py index e3e7c56..f6d9c6d 100644 --- a/src/fingerly/__init__.py +++ b/src/fingerly/__init__.py @@ -20,6 +20,18 @@ Events, Fingerly, ) +from ._enums import ( + AttestationState, + AttestationStatus, + AttestSkippedReason, + Confidence, + Environment, + EventState, + Signal, + SuspectLevel, + VerifyReason, + WebhookEventType, +) from ._errors import ( FingerlyAPIError, FingerlyConnectionError, @@ -39,7 +51,6 @@ EventDocument, EventPage, EventTrigger, - VerifyReason, VerifyResult, ) from ._proxy import FingerlyProxy, ProxyRequest @@ -51,14 +62,20 @@ "AsyncDeviceCheck", "AsyncEvents", "AsyncFingerly", + "AttestSkippedReason", "Attestation", + "AttestationState", + "AttestationStatus", + "Confidence", "ConsumeResult", "DeviceCheck", "DeviceCheckBits", "DeviceCheckWriteResult", + "Environment", "Event", "EventDocument", "EventPage", + "EventState", "EventTrigger", "Events", "Fingerly", @@ -71,8 +88,11 @@ "FingerlyProxy", "FingerlyTimeoutError", "ProxyRequest", + "Signal", + "SuspectLevel", "VerifyReason", "VerifyResult", + "WebhookEventType", "__version__", "verify_webhook", ] diff --git a/src/fingerly/_client.py b/src/fingerly/_client.py index de7eaf9..f544ae8 100644 --- a/src/fingerly/_client.py +++ b/src/fingerly/_client.py @@ -22,6 +22,7 @@ parse_key, positive_seconds, ) +from ._enums import VerifyReason from ._errors import ( FingerlyAPIError, FingerlyConnectionError, @@ -216,7 +217,7 @@ def verify( payload = self._client._request(path) except FingerlyAPIError as error: if is_not_found(error): - return VerifyResult(ok=False, reason="not_found") + return VerifyResult(ok=False, reason=VerifyReason.NOT_FOUND) raise event, occurred = parse_verified_event(payload) reason = failed_check(event, occurred, _now(), max_age_seconds, tag) @@ -226,12 +227,14 @@ def verify( try: self._client._request(path + "/consume", method="POST") except FingerlyEventAlreadyConsumedError: - return VerifyResult(ok=False, reason="already_consumed", event=event) + return VerifyResult( + ok=False, reason=VerifyReason.ALREADY_CONSUMED, event=event + ) except FingerlyAPIError as error: if is_not_found(error): - return VerifyResult(ok=False, reason="not_found") + return VerifyResult(ok=False, reason=VerifyReason.NOT_FOUND) raise - return VerifyResult(ok=True, reason="", event=event) + return VerifyResult(ok=True, reason=VerifyReason.OK, event=event) def list( self, @@ -250,7 +253,8 @@ def list( page: 1-based page number. limit: Rows per page, at most 200. visitor: Restrict to one exact visitor id. - level: Restrict to ``low``, ``medium`` or ``high``. + level: Restrict to ``low``, ``medium`` or ``high``; a + :class:`SuspectLevel` member works too. Raises: TypeError: If a bound, page or limit is unusable. @@ -293,7 +297,7 @@ async def verify( payload = await self._client._request(path) except FingerlyAPIError as error: if is_not_found(error): - return VerifyResult(ok=False, reason="not_found") + return VerifyResult(ok=False, reason=VerifyReason.NOT_FOUND) raise event, occurred = parse_verified_event(payload) reason = failed_check(event, occurred, _now(), max_age_seconds, tag) @@ -303,12 +307,14 @@ async def verify( try: await self._client._request(path + "/consume", method="POST") except FingerlyEventAlreadyConsumedError: - return VerifyResult(ok=False, reason="already_consumed", event=event) + return VerifyResult( + ok=False, reason=VerifyReason.ALREADY_CONSUMED, event=event + ) except FingerlyAPIError as error: if is_not_found(error): - return VerifyResult(ok=False, reason="not_found") + return VerifyResult(ok=False, reason=VerifyReason.NOT_FOUND) raise - return VerifyResult(ok=True, reason="", event=event) + return VerifyResult(ok=True, reason=VerifyReason.OK, event=event) async def list( self, diff --git a/src/fingerly/_enums.py b/src/fingerly/_enums.py new file mode 100644 index 0000000..367708f --- /dev/null +++ b/src/fingerly/_enums.py @@ -0,0 +1,218 @@ +"""Named constants for the closed string sets the API and webhooks use. + +Every member is a ``str``: it compares equal to, and hashes like, the raw +value, so ``event.suspect_level == SuspectLevel.HIGH`` and +``Signal.TOR in {"tor"}`` both hold. ``str()`` and f-strings give the raw +value on every supported Python, not ``"SuspectLevel.HIGH"``. + +The models keep these fields typed ``str`` and hold the value exactly as the +API sent it, so a value a newer server adds parses instead of raising. Compare +against the members; do not convert with ``SuspectLevel(value)``, which raises +``ValueError`` for a value this release does not know. +""" + +from __future__ import annotations + +from enum import Enum + + +class _StrEnum(str, Enum): + """A ``str`` enum whose text is its value on every Python from 3.9.""" + + def __str__(self) -> str: + return str.__str__(self) + + def __format__(self, format_spec: str) -> str: + return str.__format__(str.__str__(self), format_spec) + + +class Signal(_StrEnum): + """Risk signal and signal-group identifiers. + + ``EventTrigger.signal`` is one of the group names (such as ``VPN``, + ``BOT`` or ``ATTESTATION_FAILED``); archived risk reports also carry the + raw detector names that feed each group (such as ``VPN_TIMEZONE``). + """ + + TOR = "tor" + DATACENTER_PROXY = "datacenter_proxy" + PROXY = "proxy" + DATACENTER_IP = "datacenter_ip" + RESIDENTIAL_PROXY = "residential_proxy" + RESIDENTIAL_PROXY_LOW_CONFIDENCE = "residential_proxy_low_confidence" + RESIDENTIAL_PROXY_MEDIUM_CONFIDENCE = "residential_proxy_medium_confidence" + RESIDENTIAL_PROXY_HIGH_CONFIDENCE = "residential_proxy_high_confidence" + VPN = "vpn" + VPN_PUBLIC = "vpn_public" + VPN_TIMEZONE = "vpn_timezone" + VPN_RELAY = "vpn_relay" + VPN_MOBILE = "vpn_mobile" + VPN_OS_MISMATCH = "vpn_os_mismatch" + VPN_LOW_CONFIDENCE = "vpn_low_confidence" + VPN_MEDIUM_CONFIDENCE = "vpn_medium_confidence" + VPN_HIGH_CONFIDENCE = "vpn_high_confidence" + IP_BLOCKLIST = "ip_blocklist" + IP_BLOCKLIST_EMAIL_SPAM = "ip_blocklist_email_spam" + IP_BLOCKLIST_ATTACK_SOURCE = "ip_blocklist_attack_source" + IP_REPUTATION = "ip_reputation" + IP_ABUSER = "ip_abuser" + NETWORK_ANOMALY = "network_anomaly" + BOGON_IP = "bogon_ip" + ANYCAST_IP = "anycast_ip" + LOCATION_SPOOFING = "location_spoofing" + GEO_MISMATCH = "geo_mismatch" + IOS_SIMULATOR = "ios_simulator" + SIMULATOR = "simulator" + ANDROID_EMULATOR = "android_emulator" + EMULATOR = "emulator" + VIRTUAL_MACHINE = "virtual_machine" + JAILBROKEN_DEVICE = "jailbroken_device" + JAILBREAK = "jailbreak" + ROOTED_DEVICE = "rooted_device" + ROOT_APPS = "root_apps" + PLAY_DEVICE_INTEGRITY_FAILED = "play_device_integrity_failed" + CLONED_APP = "cloned_app" + APP_CLONER = "app_cloner" + PLAY_APP_UNRECOGNIZED = "play_app_unrecognized" + DEVICE_FARM = "device_farm" + REPEATED_REINSTALL = "repeated_reinstall" + DEVICE_ACTIVITY_HIGH = "device_activity_high" + DEVICE_ACTIVITY_VERY_HIGH = "device_activity_very_high" + MITM_ATTACK = "mitm_attack" + FRIDA_DETECTED = "frida_detected" + FRIDA = "frida" + BROWSER_TAMPERING = "browser_tampering" + TAMPERING = "tampering" + ANTIDETECT_BROWSER = "antidetect_browser" + FINGERPRINT_SUPPRESSED = "fingerprint_suppressed" + DEVELOPER_TOOLS = "developer_tools" + REMOTE_CONTROL = "remote_control" + BOT = "bot" + AUTOMATION = "automation" + BAD_BOT = "bad_bot" + FETCH_METADATA_MISSING = "fetch_metadata_missing" + WEB_TICKET_MISSING = "web_ticket_missing" + WEB_TICKET_INVALID = "web_ticket_invalid" + HIGH_ACTIVITY = "high_activity" + INCOGNITO_MODE = "incognito_mode" + INCOGNITO = "incognito" + PRIVACY_SETTINGS = "privacy_settings" + EMBEDDED_WEB_VIEW = "embedded_web_view" + ACTIVE_CALL = "active_call" + ATTESTATION_MISSING = "attestation_missing" + ATTESTATION_FAILED = "attestation_failed" + ATTESTATION_DOWNGRADE = "attestation_downgrade" + DEVICE_INCONSISTENT = "device_inconsistent" + REPORT_INCOMPLETE = "report_incomplete" + PROBE_ERRORS = "probe_errors" + CUSTOM_ROOT_CA = "custom_root_ca" + SECONDARY_USER_PROFILE = "secondary_user_profile" + + +class SuspectLevel(_StrEnum): + """The band ``Event.suspect_level`` puts the suspect score in.""" + + LOW = "low" + MEDIUM = "medium" + HIGH = "high" + + +class Confidence(_StrEnum): + """How sure a detection is, as in ``EventTrigger.confidence``.""" + + LOW = "low" + MEDIUM = "medium" + HIGH = "high" + + +class EventState(_StrEnum): + """How far a submission has got, as in ``Event.state``. + + A read returns an ``ENRICHED`` or ``UNAVAILABLE`` event; ``PENDING`` is + what the API answers while it has not finished, which this SDK raises as + ``FingerlyEventPendingError``. + """ + + PENDING = "pending" + ENRICHED = "enriched" + UNAVAILABLE = "unavailable" + + +class Environment(_StrEnum): + """The key environment an event was recorded in, as in ``Event.environment``.""" + + PRODUCTION = "production" + STAGING = "staging" + DEVELOPMENT = "development" + + +class AttestationState(_StrEnum): + """The server's single hardware attestation verdict, ``Attestation.state``.""" + + ATTESTED = "attested" + NOT_ATTESTED = "not_attested" + FAILED = "failed" + + +class AttestationStatus(_StrEnum): + """The detail behind the verdict, ``Attestation.status``.""" + + VERIFIED = "verified" + INDETERMINATE = "indeterminate" + INVALID = "invalid" + ABSENT = "absent" + UNCONFIGURED = "unconfigured" + + +class AttestSkippedReason(_StrEnum): + """The app's own reason for sending no attestation, ``Attestation.attest_skipped``. + + Diagnostic only; it never lowers the score. + """ + + NOT_OFFERED = "not_offered" + UNSUPPORTED = "unsupported" + CHALLENGE_UNAVAILABLE = "challenge_unavailable" + KEY_ERROR = "key_error" + TIMEOUT = "timeout" + BACKOFF = "backoff" + INSTALL_UNAVAILABLE = "install_unavailable" + + +class VerifyReason(_StrEnum): + """Why :meth:`Events.verify` refused an event, or ``OK`` (``""``) when it passed. + + Members, in the order the checks run: + + - ``NOT_FOUND``: no event for the request id (``404 event_not_found``). + - ``TOO_OLD``: it occurred more than ``max_age_seconds`` ago, or its + ``occurred_at`` is missing or unreadable. + - ``TAG_MISMATCH``: its ``tag`` is not exactly the ``tag`` asked for. + - ``UNIDENTIFIABLE``: its ``visitor_id`` is empty. + - ``UNSCORED``: its ``suspect_score`` is ``None``. + - ``ALREADY_CONSUMED``: an earlier call consumed it. + """ + + OK = "" + NOT_FOUND = "not_found" + TOO_OLD = "too_old" + TAG_MISMATCH = "tag_mismatch" + UNIDENTIFIABLE = "unidentifiable" + UNSCORED = "unscored" + ALREADY_CONSUMED = "already_consumed" + + +class WebhookEventType(_StrEnum): + """The ``type`` of a webhook delivery. + + ``WEBHOOK_TEST`` is sent only on **Send test event** for one endpoint and + cannot be subscribed to. Ignore types you do not handle: a newer server + may send more. + """ + + IDENTIFICATION_COMPLETED = "identification.completed" + IDENTIFICATION_REFUSED = "identification.refused" + VISITOR_SUSPECT = "visitor.suspect" + BILLING_STATUS_CHANGED = "billing.status_changed" + USAGE_DAILY_SETTLED = "usage.daily_settled" + WEBHOOK_TEST = "webhook.test" diff --git a/src/fingerly/_models.py b/src/fingerly/_models.py index 99cb8ea..3bbb80c 100644 --- a/src/fingerly/_models.py +++ b/src/fingerly/_models.py @@ -11,8 +11,9 @@ from collections.abc import Mapping, Sequence from dataclasses import dataclass, field, replace from datetime import datetime, timezone -from typing import Any, Literal, Optional +from typing import Any, Optional +from ._enums import Signal, VerifyReason from ._errors import FingerlyError _INSTANT = re.compile( @@ -21,81 +22,9 @@ r"(?:[Zz]|(?P[+-])(?P\d{2}):?(?P\d{2}))\Z" ) -#: Canonical v3 risk signal and signal-group names reported in event triggers -#: and archived risk assessments. -SIGNAL_NAMES: tuple[str, ...] = ( - "tor", - "datacenter_proxy", - "proxy", - "datacenter_ip", - "residential_proxy", - "residential_proxy_low_confidence", - "residential_proxy_medium_confidence", - "residential_proxy_high_confidence", - "vpn", - "vpn_public", - "vpn_timezone", - "vpn_relay", - "vpn_mobile", - "vpn_os_mismatch", - "vpn_low_confidence", - "vpn_medium_confidence", - "vpn_high_confidence", - "ip_blocklist", - "ip_blocklist_email_spam", - "ip_blocklist_attack_source", - "ip_reputation", - "ip_abuser", - "network_anomaly", - "bogon_ip", - "anycast_ip", - "location_spoofing", - "geo_mismatch", - "ios_simulator", - "simulator", - "android_emulator", - "emulator", - "virtual_machine", - "jailbroken_device", - "jailbreak", - "rooted_device", - "root_apps", - "play_device_integrity_failed", - "cloned_app", - "app_cloner", - "play_app_unrecognized", - "device_farm", - "app_attest_key_churn", - "mitm_attack", - "frida_detected", - "frida", - "browser_tampering", - "tampering", - "antidetect_browser", - "fingerprint_suppressed", - "developer_tools", - "remote_control", - "bot", - "automation", - "bad_bot", - "fetch_metadata_missing", - "web_ticket_missing", - "web_ticket_invalid", - "high_activity", - "incognito_mode", - "incognito", - "privacy_settings", - "embedded_web_view", - "active_call", - "attestation_missing", - "attestation_failed", - "attestation_downgrade", - "device_inconsistent", - "report_incomplete", - "probe_errors", - "custom_root_ca", - "secondary_user_profile", -) +#: Every :class:`Signal` value, in declaration order. Kept for callers that +#: want plain strings; prefer the :class:`Signal` members. +SIGNAL_NAMES: tuple[str, ...] = tuple(signal.value for signal in Signal) @dataclass(frozen=True) @@ -104,9 +33,10 @@ class EventTrigger: Attributes: signal: The signal group, such as ``vpn``, ``bot`` or - ``attestation_failed``. + ``attestation_failed``; compare with :class:`Signal` members. weight: The group's combined weight in this score. - confidence: ``low``, ``medium`` or ``high``. + confidence: ``low``, ``medium`` or ``high``, a :class:`Confidence` + value. """ signal: str @@ -119,12 +49,14 @@ class Attestation: """Platform-neutral hardware attestation verdict from an archived document. Attributes: - state: ``attested``, ``not_attested`` or ``failed``. + state: ``attested``, ``not_attested`` or ``failed``, an + :class:`AttestationState` value. status: ``verified``, ``indeterminate``, ``invalid``, ``absent`` or - ``unconfigured``. + ``unconfigured``, an :class:`AttestationStatus` value. attest_skipped: Native only: the app's own reason for sending no - attestation, such as ``not_offered``, ``unsupported`` or - ``timeout``. Diagnostic only; it never lowers the score. + attestation, an :class:`AttestSkippedReason` value such as + ``not_offered``, ``unsupported`` or ``timeout``. Diagnostic only; + it never lowers the score. downgrade: Native only: an unproven or rejected report named an install an attested device owns, so it was answered unidentifiable. @@ -187,6 +119,11 @@ class Event: network, IP classification and city-level location, risk, attestation and velocity), with no raw signals, user agent or address. + Closed string sets stay typed ``str`` and hold the value as sent, so a + value a newer server adds still parses. Compare them with the enum + members: ``state`` with :class:`EventState`, ``environment`` with + :class:`Environment`, ``suspect_level`` with :class:`SuspectLevel`. + Attributes: project_id: The Fingerly project the event belongs to, as a UUID string. ``None`` when an older server did not send it. @@ -319,18 +256,6 @@ class ConsumeResult: first: bool -#: Why :meth:`Events.verify` refused an event, or ``""`` when it passed. -VerifyReason = Literal[ - "", - "not_found", - "too_old", - "tag_mismatch", - "unidentifiable", - "unscored", - "already_consumed", -] - - @dataclass(frozen=True) class VerifyResult: """The outcome of :meth:`Events.verify`. @@ -338,9 +263,10 @@ class VerifyResult: Attributes: ok: True when every check passed, and the event was consumed unless ``consume=False``. - reason: ``""`` when ``ok``; otherwise the first check that failed: - ``not_found``, ``too_old``, ``tag_mismatch``, ``unidentifiable``, - ``unscored`` or ``already_consumed``. + reason: A :class:`VerifyReason` member: ``VerifyReason.OK`` (``""``) + when ``ok``; otherwise the first check that failed: ``not_found``, + ``too_old``, ``tag_mismatch``, ``unidentifiable``, ``unscored`` or + ``already_consumed``. It compares equal to those strings. event: The event read, or None only for ``not_found``. When its ``occurred_at`` was missing or unreadable (reason ``too_old``), ``event.occurred_at`` is the earliest UTC ``datetime`` and @@ -406,14 +332,14 @@ def failed_check( level and triggers are never looked at. """ if occurred is None or (now - occurred).total_seconds() > max_age_seconds: - return "too_old" + return VerifyReason.TOO_OLD if tag is not None and (event.tag or "") != tag: - return "tag_mismatch" + return VerifyReason.TAG_MISMATCH if not event.visitor_id: - return "unidentifiable" + return VerifyReason.UNIDENTIFIABLE if event.suspect_score is None: - return "unscored" - return "" + return VerifyReason.UNSCORED + return VerifyReason.OK def parse_device_check_bits(payload: Mapping[str, Any]) -> DeviceCheckBits: diff --git a/src/fingerly/_version.py b/src/fingerly/_version.py index d60e763..6e7a45a 100644 --- a/src/fingerly/_version.py +++ b/src/fingerly/_version.py @@ -4,4 +4,4 @@ send and the version the proxy reports upstream all come from here. """ -__version__ = "0.3.0" +__version__ = "0.4.0" diff --git a/tests/test_enums.py b/tests/test_enums.py new file mode 100644 index 0000000..3536393 --- /dev/null +++ b/tests/test_enums.py @@ -0,0 +1,351 @@ +"""The exported enums match the server's closed string sets and stay strings. + +The pinned lists below mirror the server sources named beside each one. When +the server checkout sits next to this SDK (the integration workspace) or +``FINGERLY_SERVER_DIR`` names it, the server tests read those sources too, so a +signal added or retired there fails here until the SDK follows. +""" + +from __future__ import annotations + +import json +import os +import re +from enum import Enum +from pathlib import Path +from typing import Optional + +import pytest +from conftest import Recorder, event_body, json_response + +import fingerly +from fingerly import ( + SIGNAL_NAMES, + AttestationState, + AttestationStatus, + AttestSkippedReason, + Confidence, + Environment, + EventState, + Fingerly, + Signal, + SuspectLevel, + VerifyReason, + WebhookEventType, +) +from fingerly._models import parse_document, parse_event + +# server/domain/risk/signals.go (Signal) and groups.go (Group). +SERVER_SIGNALS = { + "active_call", + "android_emulator", + "antidetect_browser", + "anycast_ip", + "app_cloner", + "attestation_downgrade", + "attestation_failed", + "attestation_missing", + "automation", + "bad_bot", + "bogon_ip", + "bot", + "browser_tampering", + "cloned_app", + "custom_root_ca", + "datacenter_ip", + "datacenter_proxy", + "developer_tools", + "device_activity_high", + "device_activity_very_high", + "device_farm", + "device_inconsistent", + "embedded_web_view", + "emulator", + "fetch_metadata_missing", + "fingerprint_suppressed", + "frida", + "frida_detected", + "geo_mismatch", + "high_activity", + "incognito", + "incognito_mode", + "ios_simulator", + "ip_abuser", + "ip_blocklist", + "ip_blocklist_attack_source", + "ip_blocklist_email_spam", + "ip_reputation", + "jailbreak", + "jailbroken_device", + "location_spoofing", + "mitm_attack", + "network_anomaly", + "play_app_unrecognized", + "play_device_integrity_failed", + "privacy_settings", + "probe_errors", + "proxy", + "remote_control", + "repeated_reinstall", + "report_incomplete", + "residential_proxy", + "residential_proxy_high_confidence", + "residential_proxy_low_confidence", + "residential_proxy_medium_confidence", + "root_apps", + "rooted_device", + "secondary_user_profile", + "simulator", + "tampering", + "tor", + "virtual_machine", + "vpn", + "vpn_high_confidence", + "vpn_low_confidence", + "vpn_medium_confidence", + "vpn_mobile", + "vpn_os_mismatch", + "vpn_public", + "vpn_relay", + "vpn_timezone", + "web_ticket_invalid", + "web_ticket_missing", +} + +PINNED: dict[type[Enum], set[str]] = { + Signal: SERVER_SIGNALS, + # server/models/enums.go (SuspectLevel). + SuspectLevel: {"low", "medium", "high"}, + # server/domain/risk/signals.go (Confidence). + Confidence: {"low", "medium", "high"}, + # server/models/event.go (EventState). + EventState: {"pending", "enriched", "unavailable"}, + # server/models/enums.go (Environment). + Environment: {"production", "staging", "development"}, + # server/services/android_trust.go (AttestationAttested and siblings). + AttestationState: {"attested", "not_attested", "failed"}, + # server/services/android_trust.go (AttestationReport.Status). + AttestationStatus: { + "verified", + "indeterminate", + "invalid", + "absent", + "unconfigured", + }, + # server/services/android_trust.go (AttestSkippedReasons). + AttestSkippedReason: { + "not_offered", + "unsupported", + "challenge_unavailable", + "key_error", + "timeout", + "backoff", + "install_unavailable", + }, + # server/models/webhook.go (WebhookEventType). + WebhookEventType: { + "identification.completed", + "identification.refused", + "visitor.suspect", + "billing.status_changed", + "usage.daily_settled", + "webhook.test", + }, + # Produced by this SDK's own verify checks. + VerifyReason: { + "", + "not_found", + "too_old", + "tag_mismatch", + "unidentifiable", + "unscored", + "already_consumed", + }, +} + +ENUMS = list(PINNED) + + +def _server_dir() -> Optional[Path]: + """The server checkout: ``FINGERLY_SERVER_DIR``, or the workspace sibling.""" + configured = os.environ.get("FINGERLY_SERVER_DIR") + parents = Path(__file__).resolve().parents + if configured: + path = Path(configured) + elif len(parents) > 4: + path = parents[4] / "server" + else: + return None + return path if (path / "domain" / "risk" / "signals.go").is_file() else None + + +SERVER = _server_dir() +needs_server = pytest.mark.skipif( + SERVER is None, reason="server checkout not found; set FINGERLY_SERVER_DIR" +) + + +def _go_constants(relative: str, go_type: str) -> set[str]: + """Every ``Name go_type = "value"`` constant in one server source file.""" + assert SERVER is not None + source = (SERVER / relative).read_text(encoding="utf-8") + return set(re.findall(rf'\b{go_type}\s*=\s*"([^"]*)"', source)) + + +def _go_block(relative: str, pattern: str) -> str: + assert SERVER is not None + source = (SERVER / relative).read_text(encoding="utf-8") + match = re.search(pattern, source, re.DOTALL) + assert match is not None, f"{pattern!r} not found in {relative}" + return match.group(1) + + +class TestPinnedValues: + @pytest.mark.parametrize("enum", ENUMS, ids=lambda enum: enum.__name__) + def test_values_match_the_server(self, enum: type[Enum]) -> None: + values = [member.value for member in enum] + assert len(values) == len(set(values)) + assert set(values) == PINNED[enum] + + @pytest.mark.parametrize("enum", ENUMS, ids=lambda enum: enum.__name__) + def test_names_are_the_upper_snake_value(self, enum: type[Enum]) -> None: + for member in enum: + if member.value == "": + assert member.name == "OK" + continue + assert member.name == re.sub(r"[^A-Za-z0-9]", "_", member.value).upper() + + def test_signal_names_is_every_signal_in_order(self) -> None: + assert [member.value for member in Signal] == list(SIGNAL_NAMES) + + def test_every_enum_is_exported(self) -> None: + for enum in ENUMS: + assert enum.__name__ in fingerly.__all__ + assert getattr(fingerly, enum.__name__) is enum + + +@needs_server +class TestServerSources: + def test_signals(self) -> None: + server = _go_constants("domain/risk/signals.go", "Signal") | _go_constants( + "domain/risk/groups.go", "Group" + ) + assert server == {member.value for member in Signal} + + def test_suspect_levels_and_environments(self) -> None: + assert _go_constants("models/enums.go", "SuspectLevel") == { + member.value for member in SuspectLevel + } + assert _go_constants("models/enums.go", "Environment") == { + member.value for member in Environment + } + + def test_confidence(self) -> None: + assert _go_constants("domain/risk/signals.go", "Confidence") == { + member.value for member in Confidence + } + + def test_event_states(self) -> None: + assert _go_constants("models/event.go", "EventState") == { + member.value for member in EventState + } + + def test_webhook_event_types(self) -> None: + assert _go_constants("models/webhook.go", "WebhookEventType") == { + member.value for member in WebhookEventType + } + + def test_attestation(self) -> None: + trust = "services/android_trust.go" + states = _go_block(trust, r"(\n\tAttestationAttested\s.*?)\n\)") + assert set(re.findall(r'"([a-z_]+)"', states)) == { + member.value for member in AttestationState + } + status = _go_block( + trust, r"// Status is the detail behind State:(.*?)\n\s*Status " + ) + assert set(re.findall(r"[a-z_]+", status)) - {"or"} == { + member.value for member in AttestationStatus + } + skipped = _go_block(trust, r"AttestSkippedReasons = \[\]string\{(.*?)\}") + assert set(re.findall(r'"([a-z_]+)"', skipped)) == { + member.value for member in AttestSkippedReason + } + + +class TestStringBehaviour: + def test_members_are_their_raw_strings(self) -> None: + raw: str = "high" + assert raw == SuspectLevel.HIGH + assert isinstance(SuspectLevel.HIGH, str) + assert str(Signal.FINGERPRINT_SUPPRESSED) == "fingerprint_suppressed" + assert f"{WebhookEventType.VISITOR_SUSPECT}" == "visitor.suspect" + assert f"{SuspectLevel.LOW:>5}" == " low" + assert json.dumps({"level": SuspectLevel.MEDIUM}) == '{"level": "medium"}' + + def test_members_hash_like_their_strings(self) -> None: + assert Signal.TOR in {"tor", "vpn"} + assert {"high": 1}[SuspectLevel.HIGH] == 1 + by_signal: dict[str, int] = {Signal.BOT: 1} + assert by_signal["bot"] == 1 + + def test_ok_is_falsy_and_every_refusal_truthy(self) -> None: + assert not VerifyReason.OK + assert all(member for member in VerifyReason if member is not VerifyReason.OK) + + def test_parsed_fields_compare_with_members(self) -> None: + event = parse_event( + event_body( + suspect_level="high", + triggers=[ + {"signal": "fingerprint_suppressed", "weight": 9}, + {"signal": "vpn", "weight": 5, "confidence": "medium"}, + ], + ) + ) + signals = [trigger.signal for trigger in event.triggers] + assert event.suspect_level == SuspectLevel.HIGH + assert event.state == EventState.ENRICHED + assert event.environment == Environment.DEVELOPMENT + assert Signal.FINGERPRINT_SUPPRESSED in signals + assert event.triggers[1].confidence == Confidence.MEDIUM + + def test_unknown_values_still_parse(self) -> None: + event = parse_event( + event_body( + state="some_future_state", + suspect_level="extreme", + triggers=[{"signal": "a_future_signal", "weight": 1}], + ) + ) + assert event.suspect_level == "extreme" + assert event.suspect_level not in set(SuspectLevel) + assert event.triggers[0].signal == "a_future_signal" + assert type(event.triggers[0].signal) is str + + def test_attestation_compares_with_members(self) -> None: + document = parse_document( + { + "schema": 3, + "request_id": "request-1", + "occurred_at": "2026-11-01T00:00:00Z", + "sdk": {"platform": "android", "version": "0.3.0"}, + "attestation": { + "state": "not_attested", + "status": "absent", + "attest_skipped": "timeout", + }, + } + ) + assert document.attestation is not None + assert document.attestation.state == AttestationState.NOT_ATTESTED + assert document.attestation.status == AttestationStatus.ABSENT + assert document.attestation.attest_skipped == AttestSkippedReason.TIMEOUT + + def test_a_level_member_is_sent_as_its_value(self) -> None: + recorder = Recorder(json_response({"rows": [], "page": 1, "page_size": 10})) + with Fingerly( + secret_key="fly_sk_development_enums", transport=recorder.transport() + ) as client: + client.events.list(level=SuspectLevel.HIGH) + assert dict(recorder.requests[0].url.params)["level"] == "high" diff --git a/tests/test_events_verify.py b/tests/test_events_verify.py index b15cc96..0a1ad1d 100644 --- a/tests/test_events_verify.py +++ b/tests/test_events_verify.py @@ -24,6 +24,7 @@ FingerlyAPIError, FingerlyEventAlreadyConsumedError, FingerlyEventPendingError, + VerifyReason, VerifyResult, ) @@ -204,7 +205,9 @@ def test_ok_consumes_once_after_the_read(self) -> None: def test_not_found_on_the_read(self) -> None: get = error_response("event_not_found", 404) for result, recorder in verify_both(get): - assert result == VerifyResult(ok=False, reason="not_found", event=None) + assert result == VerifyResult( + ok=False, reason=VerifyReason.NOT_FOUND, event=None + ) assert posts(recorder) == 0 def test_too_old(self) -> None: @@ -311,7 +314,9 @@ def test_not_found_on_consume(self) -> None: get = json_response(fresh_event()) post = error_response("event_not_found", 404) for result, recorder in verify_both(get, post): - assert result == VerifyResult(ok=False, reason="not_found", event=None) + assert result == VerifyResult( + ok=False, reason=VerifyReason.NOT_FOUND, event=None + ) assert posts(recorder) == 1 def test_other_consume_errors_are_raised(self) -> None: diff --git a/tests/test_frameworks.py b/tests/test_frameworks.py index 7e8581c..de58600 100644 --- a/tests/test_frameworks.py +++ b/tests/test_frameworks.py @@ -108,7 +108,7 @@ def test_forwards_from_a_route_at_the_issued_path(self) -> None: assert str(forwarded.url) == INGEST assert forwarded.headers["x-fingerly-client-ip"] == "203.0.113.5" assert forwarded.headers["x-fingerly-proxy-key"] == PROXY_KEY - assert forwarded.headers["x-fingerly-proxy-version"] == "python/0.3.0" + assert forwarded.headers["x-fingerly-proxy-version"] == "python/0.4.0" assert "cookie" not in forwarded.headers (missing_origin,) = self.post( @@ -224,7 +224,7 @@ def test_forwards_beside_the_host_app(self) -> None: forwarded = upstream.requests[0] assert forwarded.content == raw_v3 assert forwarded.headers["x-fingerly-client-ip"] == "203.0.113.5" - assert forwarded.headers["x-fingerly-proxy-version"] == "python/0.3.0" + assert forwarded.headers["x-fingerly-proxy-version"] == "python/0.4.0" assert "cookie" not in forwarded.headers native_forwarded = upstream.requests[1] assert native_forwarded.content == raw_v3 diff --git a/tests/test_proxy.py b/tests/test_proxy.py index c3509f3..439321d 100644 --- a/tests/test_proxy.py +++ b/tests/test_proxy.py @@ -243,7 +243,7 @@ def test_sends_only_vetted_visitor_metadata(self) -> None: assert upstream.headers["x-fingerly-origin"] == "https://shop.test" assert upstream.headers["x-fingerly-user-agent"] == "Firefox" assert upstream.headers["idempotency-key"] == "idem-1" - assert upstream.headers["x-fingerly-proxy-version"] == "python/0.3.0" + assert upstream.headers["x-fingerly-proxy-version"] == "python/0.4.0" assert "cookie" not in upstream.headers assert "authorization" not in upstream.headers