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
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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,
Expand Down
50 changes: 32 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.**
Expand Down Expand Up @@ -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__)

Expand All @@ -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
```

Expand Down Expand Up @@ -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.
Expand All @@ -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()
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -609,7 +623,7 @@ The vendored synthetic contract snapshot makes tests independent of sibling repo
<details>
<summary>Source structure</summary>

`_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.

</details>

Expand Down
22 changes: 21 additions & 1 deletion src/fingerly/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,18 @@
Events,
Fingerly,
)
from ._enums import (
AttestationState,
AttestationStatus,
AttestSkippedReason,
Confidence,
Environment,
EventState,
Signal,
SuspectLevel,
VerifyReason,
WebhookEventType,
)
from ._errors import (
FingerlyAPIError,
FingerlyConnectionError,
Expand All @@ -39,7 +51,6 @@
EventDocument,
EventPage,
EventTrigger,
VerifyReason,
VerifyResult,
)
from ._proxy import FingerlyProxy, ProxyRequest
Expand All @@ -51,14 +62,20 @@
"AsyncDeviceCheck",
"AsyncEvents",
"AsyncFingerly",
"AttestSkippedReason",
"Attestation",
"AttestationState",
"AttestationStatus",
"Confidence",
"ConsumeResult",
"DeviceCheck",
"DeviceCheckBits",
"DeviceCheckWriteResult",
"Environment",
"Event",
"EventDocument",
"EventPage",
"EventState",
"EventTrigger",
"Events",
"Fingerly",
Expand All @@ -71,8 +88,11 @@
"FingerlyProxy",
"FingerlyTimeoutError",
"ProxyRequest",
"Signal",
"SuspectLevel",
"VerifyReason",
"VerifyResult",
"WebhookEventType",
"__version__",
"verify_webhook",
]
24 changes: 15 additions & 9 deletions src/fingerly/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
parse_key,
positive_seconds,
)
from ._enums import VerifyReason
from ._errors import (
FingerlyAPIError,
FingerlyConnectionError,
Expand Down Expand Up @@ -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)
Expand All @@ -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,
Expand All @@ -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.
Expand Down Expand Up @@ -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)
Expand All @@ -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,
Expand Down
Loading
Loading