diff --git a/CHANGELOG.md b/CHANGELOG.md index f9aaec0..a535308 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## 0.4.0 + +- Named constants for every closed string set the API sends: `Signal` (every + signal group and detector), `SuspectLevel`, `Confidence`, `EventState`, + `Environment`, `Platform`, `AnonymityNetwork`, `DeviceKind`, `VisitorKind`, + `AttestationState`, `AttestationStatus`, `AttestSkippedReason`, + `VerifyReason`, `WebhookEventType` and `WebhookEnvironment`. They are + `String` constants, so they work in `switch`, and the accessors stay + strings, so a value the server adds later still reads. + `EventTrigger.SIGNAL_` and `VerifyResult.REASON_` are the same strings. +- `Signal` matches the server's signal list, including `repeated_reinstall`, + `device_activity_high` and `device_activity_very_high`. +- `Event.getAnonymityNetwork()` documents `relay`, which the server already + sends. + ## 0.3.0 - Synced the vendored `v: 3` OpenAPI and fixture contract snapshot, added diff --git a/README.md b/README.md index 795bde6..012e4eb 100644 --- a/README.md +++ b/README.md @@ -35,12 +35,12 @@ Java 11 or newer, and Kotlin and Scala through the same artifacts. Releases are io.fingerly fingerly-server - 0.3.0 + 0.4.0 ``` ```kotlin -implementation("io.fingerly:fingerly-server:0.3.0") +implementation("io.fingerly:fingerly-server:0.4.0") ``` For the proxy, add the adapter for your stack as well (see [Artifacts](#artifacts)). @@ -52,6 +52,7 @@ import io.fingerly.server.Event; import io.fingerly.server.EventListParams; import io.fingerly.server.EventPage; import io.fingerly.server.FingerlyClient; +import io.fingerly.server.SuspectLevel; FingerlyClient fingerly = FingerlyClient.builder() .secretKey(System.getenv("FINGERLY_SECRET_KEY")) @@ -59,7 +60,7 @@ FingerlyClient fingerly = FingerlyClient.builder() Event event = fingerly.events().get(requestId); EventPage page = fingerly.events().list( - EventListParams.builder().level("high").limit(50).build()); + EventListParams.builder().level(SuspectLevel.HIGH).limit(50).build()); ``` **4. Verify a webhook.** @@ -96,6 +97,7 @@ Full documentation: [docs.fingerly.io/docs/sdks/java](https://docs.fingerly.io/d - [Errors](#errors) - [Unscored events](#unscored-events) - [Read an event you just identified](#read-an-event-you-just-identified) +- [Named values](#named-values) - [Verify a backend action](#verify-a-backend-action) - [DeviceCheck bits on iOS](#devicecheck-bits-on-ios) - [Verify webhooks](#verify-webhooks) @@ -208,7 +210,27 @@ Retry a pending read a bounded number of times, for example from a scheduled job The archived document arrives moments after the event itself, so check `hasDocument()` rather than assuming it is there, and read `getDocument()` for the allow-listed archived `JsonNode` (`risk`, `attestation`, `ip_network` and `velocity`, with no raw signals, user agent or address). When a submission is unidentifiable (`identifiable == false`, such as insufficient entropy, a genuine embedded WebView, or an unmatched high-risk Web payload), `getVisitorId()` is `""`; there are no `deferred_token`, `deferred_signals` or `supplements` fields in `v: 3`. -`EventTrigger.V3_SIGNALS` groups the `v: 3` anti-spoofing and integrity signal constants on `EventTrigger`: `SIGNAL_ATTESTATION_FAILED` (`"attestation_failed"`), `SIGNAL_ATTESTATION_DOWNGRADE` (`"attestation_downgrade"`), `SIGNAL_DEVICE_INCONSISTENT` (`"device_inconsistent"`), `SIGNAL_REPORT_INCOMPLETE` (`"report_incomplete"`), `SIGNAL_PROBE_ERRORS` (`"probe_errors"`), `SIGNAL_FETCH_METADATA_MISSING` (`"fetch_metadata_missing"`), `SIGNAL_WEB_TICKET_MISSING` (`"web_ticket_missing"`), `SIGNAL_WEB_TICKET_INVALID` (`"web_ticket_invalid"`), `SIGNAL_TAMPERING` (`"tampering"`), `SIGNAL_CUSTOM_ROOT_CA` (`"custom_root_ca"`) and `SIGNAL_SECONDARY_USER_PROFILE` (`"secondary_user_profile"`). +## Named values + +The string fields with a fixed set of values have a class of constants each, holding the exact strings the API sends. The accessors stay plain strings, so a value the server adds after this SDK was released still reads normally: compare with `equals` or `switch`, and keep a default branch. + +| Constants | Values of | +| --- | --- | +| `Signal` | `EventTrigger.getSignal()` (signal groups, such as `Signal.VPN`) and the archived document's `risk.triggers[].signal` (detectors, such as `Signal.VPN_PUBLIC`) | +| `SuspectLevel` | `Event.getSuspectLevel()` and `EventListParams.Builder.level()` | +| `Confidence` | `EventTrigger.getConfidence()` | +| `EventState`, `Environment`, `Platform` | `Event.getState()`, `getEnvironment()`, `getPlatform()` | +| `AnonymityNetwork`, `DeviceKind`, `VisitorKind` | `Event.getAnonymityNetwork()`, `getDeviceKind()`, `getVisitorKind()` | +| `AttestationState`, `AttestationStatus`, `AttestSkippedReason` | the archived document's `attestation.state`, `attestation.status` and `attestation.attest_skipped` | +| `VerifyReason` | `VerifyResult.getReason()` | +| `WebhookEventType`, `WebhookEnvironment` | `WebhookEvent.getType()`, `getEnvironment()` | + +```java +boolean suppressed = event.getTriggers().stream() + .anyMatch(t -> Signal.FINGERPRINT_SUPPRESSED.equals(t.getSignal())); +``` + +`EventTrigger.V3_SIGNALS` groups the `v: 3` anti-spoofing and integrity signals: `Signal.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`. The `EventTrigger.SIGNAL_` constants are the same strings. ## Verify a backend action @@ -221,11 +243,13 @@ Send the request id from the browser or app to your backend and verify it there 5. `unscored`: the event was not scored. 6. `already_consumed`: every check passed, but another call consumed the event first. -It consumes the event last, only when every other check passes, so one event backs one decision: a second verify of the same request id answers `already_consumed`. `VerifyOptions.builder().consume(false)` skips the consume. `getReason()` is one of the `VerifyResult.REASON_` constants, `""` when `isOk()`, and `getEvent()` is the event read (null only for `not_found`). +It consumes the event last, only when every other check passes, so one event backs one decision: a second verify of the same request id answers `already_consumed`. `VerifyOptions.builder().consume(false)` skips the consume. `getReason()` is one of the `VerifyReason` constants (`VerifyReason.OK`, `""`, when `isOk()`), and `getEvent()` is the event read (null only for `not_found`). `verify` never looks at the suspect score, level or triggers: that policy stays with you, applied after `isOk()`. ```java +import io.fingerly.server.Signal; +import io.fingerly.server.SuspectLevel; import io.fingerly.server.VerifyOptions; import io.fingerly.server.VerifyResult; @@ -241,9 +265,9 @@ if (!result.isOk()) { return "refuse"; // result.getReason() says which check failed } Event event = result.getEvent(); -if ("high".equals(event.getSuspectLevel()) +if (SuspectLevel.HIGH.equals(event.getSuspectLevel()) || event.getTriggers().stream() - .anyMatch(t -> EventTrigger.SIGNAL_ATTESTATION_FAILED.equals(t.getSignal()))) { + .anyMatch(t -> Signal.ATTESTATION_FAILED.equals(t.getSignal()))) { return "refuse"; } ``` @@ -296,6 +320,19 @@ Verify the exact raw bytes before parsing them. Signatures cover the timestamp a `WebhookEvent.getData()` stays a `JsonNode`, so a new event type needs no SDK upgrade; `getDataJson()` is the same as text. `identification.completed` and `visitor.suspect` carry the event's project as `data.project_id`; `identification.refused` carries it only when the refused request named a known key. Read it with `getData().path("project_id")`. +```java +switch (event.getType()) { + case WebhookEventType.VISITOR_SUSPECT: + review(event.getData().path("request_id").asText()); + break; + case WebhookEventType.IDENTIFICATION_COMPLETED: + record(event.getData()); + break; + default: + break; // a type added later: acknowledge it and move on +} +``` + ## First-party proxy Content blockers refuse browser requests to third-party APIs, and a refused identification is a visitor never identified. Create a proxy in the dashboard (**Integration > Proxy keys**) and mount it at the path it issued, such as `/k7x2qm4a`, and those requests become first-party. The proxy key is what lets that hop declare the visitor's real address, origin and user agent; a public key alone never can, so nobody can spoof them. @@ -437,7 +474,7 @@ The proxy key (`fly_px_{production|staging|development}_…`) is required: `buil Incoming headers follow the sanitize-and-restore sequence: all incoming `X-Fingerly-*`, `Cookie` and `Authorization` headers are stripped, restoring `X-Fingerly-SDK-Platform` only if 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`). When both `Origin` and a validated `X-Fingerly-SDK-Platform` are absent, the request is rejected locally with `400` (`missing_origin`), and `X-Fingerly-Origin` is never synthesized from `Host`, `Referer` or the request URL. A request carries one channel upstream: with an `Origin`, the proxy sends `X-Fingerly-Origin` and drops the platform header, as the API does on a direct call; without one, it sends the validated `X-Fingerly-SDK-Platform`. -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 never are, and a visitor header that could not be forwarded is dropped. The proxy reports itself upstream as `java/0.3.0`, which the dashboard shows per proxy. +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 never are, and a visitor header that could not be forwarded is dropped. The proxy reports itself upstream as `java/0.4.0`, which the dashboard shows per proxy. Only `Content-Type`, `X-Request-Id`, `RateLimit-Limit`, `RateLimit-Remaining` and `Retry-After` are relayed back, plus `Cache-Control: no-store`, so nothing on the response names Fingerly. The answer is read whole before anything is relayed, so a truncated one is never passed on as a success. diff --git a/fingerly-server/src/main/java/io/fingerly/server/AnonymityNetwork.java b/fingerly-server/src/main/java/io/fingerly/server/AnonymityNetwork.java new file mode 100644 index 0000000..78db285 --- /dev/null +++ b/fingerly-server/src/main/java/io/fingerly/server/AnonymityNetwork.java @@ -0,0 +1,25 @@ +package io.fingerly.server; + +/** + * The {@link Event#getAnonymityNetwork()} values, as the exact strings the API + * sends. The accessor is null on an ordinary connection. + */ +public final class AnonymityNetwork { + + private AnonymityNetwork() {} + + /** A Tor exit node. */ + public static final String TOR = "tor"; + + /** A privacy relay such as Apple's Private Relay. */ + public static final String RELAY = "relay"; + + /** A reported VPN endpoint. */ + public static final String VPN = "vpn"; + + /** A proxy. */ + public static final String PROXY = "proxy"; + + /** A hosting or datacenter network. */ + public static final String HOSTING = "hosting"; +} diff --git a/fingerly-server/src/main/java/io/fingerly/server/AttestSkippedReason.java b/fingerly-server/src/main/java/io/fingerly/server/AttestSkippedReason.java new file mode 100644 index 0000000..5dacedb --- /dev/null +++ b/fingerly-server/src/main/java/io/fingerly/server/AttestSkippedReason.java @@ -0,0 +1,33 @@ +package io.fingerly.server; + +/** + * Why a native SDK sent no attestation, as the exact strings of + * {@code attestation.attest_skipped} in {@link Event#getDocument()}. + * The app reports it about itself; it is diagnostic only and never changes + * the score. + */ +public final class AttestSkippedReason { + + private AttestSkippedReason() {} + + /** Attestation was not offered. */ + public static final String NOT_OFFERED = "not_offered"; + + /** Attestation is not supported on the device. */ + public static final String UNSUPPORTED = "unsupported"; + + /** No attestation challenge was available. */ + public static final String CHALLENGE_UNAVAILABLE = "challenge_unavailable"; + + /** The attestation key failed. */ + public static final String KEY_ERROR = "key_error"; + + /** Attestation timed out. */ + public static final String TIMEOUT = "timeout"; + + /** The SDK was backing off from attestation. */ + public static final String BACKOFF = "backoff"; + + /** The install ID was unavailable. */ + public static final String INSTALL_UNAVAILABLE = "install_unavailable"; +} diff --git a/fingerly-server/src/main/java/io/fingerly/server/AttestationState.java b/fingerly-server/src/main/java/io/fingerly/server/AttestationState.java new file mode 100644 index 0000000..ceb8db2 --- /dev/null +++ b/fingerly-server/src/main/java/io/fingerly/server/AttestationState.java @@ -0,0 +1,26 @@ +package io.fingerly.server; + +/** + * The server's verdict on a native event's hardware evidence, as the exact + * strings of {@code attestation.state} in {@link Event#getDocument()}. + * + *
{@code
+ * String state = event.getDocument().path("attestation").path("state").asText();
+ * if (AttestationState.FAILED.equals(state)) {
+ *     return "refuse";
+ * }
+ * }
+ */ +public final class AttestationState { + + private AttestationState() {} + + /** The hardware evidence verified. */ + public static final String ATTESTED = "attested"; + + /** No evidence that could be proven was offered. */ + public static final String NOT_ATTESTED = "not_attested"; + + /** The evidence failed verification. */ + public static final String FAILED = "failed"; +} diff --git a/fingerly-server/src/main/java/io/fingerly/server/AttestationStatus.java b/fingerly-server/src/main/java/io/fingerly/server/AttestationStatus.java new file mode 100644 index 0000000..a08cc4e --- /dev/null +++ b/fingerly-server/src/main/java/io/fingerly/server/AttestationStatus.java @@ -0,0 +1,25 @@ +package io.fingerly.server; + +/** + * The detail behind {@link AttestationState}, as the exact strings of + * {@code attestation.status} in {@link Event#getDocument()}. + */ +public final class AttestationStatus { + + private AttestationStatus() {} + + /** The evidence verified. */ + public static final String VERIFIED = "verified"; + + /** The evidence could not be checked either way. */ + public static final String INDETERMINATE = "indeterminate"; + + /** The evidence was rejected. */ + public static final String INVALID = "invalid"; + + /** The report carried no evidence. */ + public static final String ABSENT = "absent"; + + /** The key has nothing configured to verify the evidence against. */ + public static final String UNCONFIGURED = "unconfigured"; +} diff --git a/fingerly-server/src/main/java/io/fingerly/server/Confidence.java b/fingerly-server/src/main/java/io/fingerly/server/Confidence.java new file mode 100644 index 0000000..437d2fb --- /dev/null +++ b/fingerly-server/src/main/java/io/fingerly/server/Confidence.java @@ -0,0 +1,16 @@ +package io.fingerly.server; + +/** The {@link EventTrigger#getConfidence()} values, as the exact strings the API sends. */ +public final class Confidence { + + private Confidence() {} + + /** Low confidence. */ + public static final String LOW = "low"; + + /** Medium confidence. */ + public static final String MEDIUM = "medium"; + + /** High confidence. */ + public static final String HIGH = "high"; +} diff --git a/fingerly-server/src/main/java/io/fingerly/server/DeviceKind.java b/fingerly-server/src/main/java/io/fingerly/server/DeviceKind.java new file mode 100644 index 0000000..5c3d786 --- /dev/null +++ b/fingerly-server/src/main/java/io/fingerly/server/DeviceKind.java @@ -0,0 +1,19 @@ +package io.fingerly.server; + +/** The {@link Event#getDeviceKind()} values, as the exact strings the API sends. */ +public final class DeviceKind { + + private DeviceKind() {} + + /** A desktop or laptop. */ + public static final String DESKTOP = "desktop"; + + /** A phone. */ + public static final String MOBILE = "mobile"; + + /** A tablet. */ + public static final String TABLET = "tablet"; + + /** A client with no device at all. */ + public static final String SERVER = "server"; +} diff --git a/fingerly-server/src/main/java/io/fingerly/server/Environment.java b/fingerly-server/src/main/java/io/fingerly/server/Environment.java new file mode 100644 index 0000000..50f3791 --- /dev/null +++ b/fingerly-server/src/main/java/io/fingerly/server/Environment.java @@ -0,0 +1,16 @@ +package io.fingerly.server; + +/** The {@link Event#getEnvironment()} values, as the exact strings the API sends. */ +public final class Environment { + + private Environment() {} + + /** Production. */ + public static final String PRODUCTION = "production"; + + /** Staging. */ + public static final String STAGING = "staging"; + + /** Development. */ + public static final String DEVELOPMENT = "development"; +} diff --git a/fingerly-server/src/main/java/io/fingerly/server/Event.java b/fingerly-server/src/main/java/io/fingerly/server/Event.java index f369c4e..5d8d0ba 100644 --- a/fingerly-server/src/main/java/io/fingerly/server/Event.java +++ b/fingerly-server/src/main/java/io/fingerly/server/Event.java @@ -124,7 +124,7 @@ public Instant getOccurredAt() { return occurredAt; } - /** {@code enriched}, or {@code unavailable} when the lookup could not run. */ + /** {@code enriched}, or {@code unavailable} when the lookup could not run. See {@link EventState}. */ public String getState() { return state; } @@ -134,12 +134,12 @@ public String getReason() { return reason; } - /** {@code production}, {@code staging} or {@code development}. */ + /** {@code production}, {@code staging} or {@code development}. See {@link Environment}. */ public String getEnvironment() { return environment; } - /** The scoring profile applied: {@code web}, {@code android} or {@code ios}. */ + /** The scoring profile applied: {@code web}, {@code android} or {@code ios}. See {@link Platform}. */ public String getPlatform() { return platform; } @@ -212,8 +212,9 @@ public String getAsnName() { } /** - * {@code tor}, {@code vpn}, {@code proxy} or {@code hosting}. Null on an - * ordinary connection, which is most of them. + * {@code tor}, {@code relay}, {@code vpn}, {@code proxy} or {@code hosting} + * (see {@link AnonymityNetwork}). Null on an ordinary connection, which is + * most of them. */ public String getAnonymityNetwork() { return anonymityNetwork; @@ -234,12 +235,12 @@ public String getOs() { return os; } - /** {@code desktop}, {@code mobile}, {@code tablet} or {@code server}. */ + /** {@code desktop}, {@code mobile}, {@code tablet} or {@code server}. See {@link DeviceKind}. */ public String getDeviceKind() { return deviceKind; } - /** {@code human}, {@code ai_bot}, {@code automation} or {@code search_crawler}. */ + /** {@code human}, {@code ai_bot}, {@code automation} or {@code search_crawler}. See {@link VisitorKind}. */ public String getVisitorKind() { return visitorKind; } @@ -259,7 +260,7 @@ public boolean isScored() { return suspectScore != null; } - /** {@code low}, {@code medium} or {@code high}. Null when not scored. */ + /** {@code low}, {@code medium} or {@code high} (see {@link SuspectLevel}). Null when not scored. */ public String getSuspectLevel() { return suspectLevel; } @@ -280,7 +281,8 @@ public boolean hasDocument() { * request id, time, SDK platform and version, IP network, IP * classification (network, city-level location, detections), risk, * attestation and velocity. It carries no raw signals, user agent or - * address. + * address. {@link AttestationState} and {@link AttestationStatus} name the + * values of {@code attestation.state} and {@code attestation.status}. * *

Its contents are deliberately opaque, not a public contract. */ diff --git a/fingerly-server/src/main/java/io/fingerly/server/EventListParams.java b/fingerly-server/src/main/java/io/fingerly/server/EventListParams.java index 2ff7662..8c85f4f 100644 --- a/fingerly-server/src/main/java/io/fingerly/server/EventListParams.java +++ b/fingerly-server/src/main/java/io/fingerly/server/EventListParams.java @@ -14,7 +14,7 @@ * *

{@code
  * EventPage page = fingerly.events().list(
- *     EventListParams.builder().level("high").limit(50).build());
+ *     EventListParams.builder().level(SuspectLevel.HIGH).limit(50).build());
  * }
*/ public final class EventListParams { @@ -130,7 +130,7 @@ public Builder visitor(String visitor) { return this; } - /** Restrict it to {@code low}, {@code medium} or {@code high}. */ + /** Restrict it to {@code low}, {@code medium} or {@code high}; see {@link SuspectLevel}. */ public Builder level(String level) { this.level = level; return this; diff --git a/fingerly-server/src/main/java/io/fingerly/server/EventState.java b/fingerly-server/src/main/java/io/fingerly/server/EventState.java new file mode 100644 index 0000000..b9b0f7c --- /dev/null +++ b/fingerly-server/src/main/java/io/fingerly/server/EventState.java @@ -0,0 +1,22 @@ +package io.fingerly.server; + +/** + * The {@link Event#getState()} values, as the exact strings the API sends. + * + *

A stored event is {@link #ENRICHED} or {@link #UNAVAILABLE}. An event + * still being recorded is not returned as a row: the read throws a + * {@link FingerlyApiException} whose {@code isPending()} is true. + */ +public final class EventState { + + private EventState() {} + + /** Accepted and not yet recorded. */ + public static final String PENDING = "pending"; + + /** The submission was enriched and stored. */ + public static final String ENRICHED = "enriched"; + + /** Enrichment produced nothing; {@link Event#getReason()} says why. */ + public static final String UNAVAILABLE = "unavailable"; +} diff --git a/fingerly-server/src/main/java/io/fingerly/server/EventTrigger.java b/fingerly-server/src/main/java/io/fingerly/server/EventTrigger.java index 18fd89e..fb67065 100644 --- a/fingerly-server/src/main/java/io/fingerly/server/EventTrigger.java +++ b/fingerly-server/src/main/java/io/fingerly/server/EventTrigger.java @@ -6,43 +6,43 @@ public final class EventTrigger { /** Hardware attestation failed cryptographic, chain, replay or ownership verification. */ - public static final String SIGNAL_ATTESTATION_FAILED = "attestation_failed"; + public static final String SIGNAL_ATTESTATION_FAILED = Signal.ATTESTATION_FAILED; /** Native device could have offered hardware attestation proof and did not. */ - public static final String SIGNAL_ATTESTATION_MISSING = "attestation_missing"; + public static final String SIGNAL_ATTESTATION_MISSING = Signal.ATTESTATION_MISSING; /** Unproven or rejected native report naming an install an attested key owns. */ - public static final String SIGNAL_ATTESTATION_DOWNGRADE = "attestation_downgrade"; + public static final String SIGNAL_ATTESTATION_DOWNGRADE = Signal.ATTESTATION_DOWNGRADE; /** Reported hardware, OS or runtime realms contradict each other. */ - public static final String SIGNAL_DEVICE_INCONSISTENT = "device_inconsistent"; + public static final String SIGNAL_DEVICE_INCONSISTENT = Signal.DEVICE_INCONSISTENT; /** Evidence a report always carries is missing: a required native security source or the web worker-realm cross-check. */ - public static final String SIGNAL_REPORT_INCOMPLETE = "report_incomplete"; + public static final String SIGNAL_REPORT_INCOMPLETE = Signal.REPORT_INCOMPLETE; /** Native security source ran but lists probes that threw, were denied or timed out. */ - public static final String SIGNAL_PROBE_ERRORS = "probe_errors"; + public static final String SIGNAL_PROBE_ERRORS = Signal.PROBE_ERRORS; /** Browser report without {@code Sec-Fetch-*} headers from a browser that always sends them. */ - public static final String SIGNAL_FETCH_METADATA_MISSING = "fetch_metadata_missing"; + public static final String SIGNAL_FETCH_METADATA_MISSING = Signal.FETCH_METADATA_MISSING; /** Browser report that carried no single-use freshness ticket. */ - public static final String SIGNAL_WEB_TICKET_MISSING = "web_ticket_missing"; + public static final String SIGNAL_WEB_TICKET_MISSING = Signal.WEB_TICKET_MISSING; /** Browser report whose freshness ticket did not verify: bad signature, another key's or origin's, expired, or already used. */ - public static final String SIGNAL_WEB_TICKET_INVALID = "web_ticket_invalid"; + public static final String SIGNAL_WEB_TICKET_INVALID = Signal.WEB_TICKET_INVALID; /** Runtime code or natives were patched or tampered with. */ - public static final String SIGNAL_TAMPERING = "tampering"; + public static final String SIGNAL_TAMPERING = Signal.TAMPERING; /** Browser tampering signal group key on stored event rows. */ - public static final String SIGNAL_BROWSER_TAMPERING = "browser_tampering"; + public static final String SIGNAL_BROWSER_TAMPERING = Signal.BROWSER_TAMPERING; /** TLS chain anchored at a non-WebPKI or user-installed root authority. */ - public static final String SIGNAL_CUSTOM_ROOT_CA = "custom_root_ca"; + public static final String SIGNAL_CUSTOM_ROOT_CA = Signal.CUSTOM_ROOT_CA; /** Managed Android work profile or secondary OS user profile without cloner indicators. */ - public static final String SIGNAL_SECONDARY_USER_PROFILE = "secondary_user_profile"; + public static final String SIGNAL_SECONDARY_USER_PROFILE = Signal.SECONDARY_USER_PROFILE; /** The v3 anti-spoofing signal identifiers. */ public static final Set V3_SIGNALS = Set.of( @@ -65,7 +65,7 @@ public final class EventTrigger { EventTrigger() {} - /** The signal or signal group, such as {@code vpn}, {@code tampering} or {@code attestation_failed}. */ + /** The signal or signal group, such as {@code vpn}, {@code tampering} or {@code attestation_failed}. See {@link Signal}. */ public String getSignal() { return signal; } @@ -80,7 +80,7 @@ public int getWeight() { return weight; } - /** {@code low}, {@code medium} or {@code high}. */ + /** {@code low}, {@code medium} or {@code high}. See {@link Confidence}. */ public String getConfidence() { return confidence; } diff --git a/fingerly-server/src/main/java/io/fingerly/server/FingerlyClient.java b/fingerly-server/src/main/java/io/fingerly/server/FingerlyClient.java index 6c378ba..337501b 100644 --- a/fingerly-server/src/main/java/io/fingerly/server/FingerlyClient.java +++ b/fingerly-server/src/main/java/io/fingerly/server/FingerlyClient.java @@ -32,7 +32,7 @@ public final class FingerlyClient { /** The SDK version, reported to the API on every request. */ - public static final String VERSION = "0.3.0"; + public static final String VERSION = "0.4.0"; private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(10); private static final String DEFAULT_API_VERSION = "v1"; diff --git a/fingerly-server/src/main/java/io/fingerly/server/Platform.java b/fingerly-server/src/main/java/io/fingerly/server/Platform.java new file mode 100644 index 0000000..1be2e3f --- /dev/null +++ b/fingerly-server/src/main/java/io/fingerly/server/Platform.java @@ -0,0 +1,20 @@ +package io.fingerly.server; + +/** + * The {@link Event#getPlatform()} scoring profiles, as the exact strings the + * API sends. {@link Event#getSdkPlatform()} is what the SDK called itself and + * is not one of these. + */ +public final class Platform { + + private Platform() {} + + /** Browsers. */ + public static final String WEB = "web"; + + /** Android apps. */ + public static final String ANDROID = "android"; + + /** iOS apps. */ + public static final String IOS = "ios"; +} diff --git a/fingerly-server/src/main/java/io/fingerly/server/Signal.java b/fingerly-server/src/main/java/io/fingerly/server/Signal.java new file mode 100644 index 0000000..270186b --- /dev/null +++ b/fingerly-server/src/main/java/io/fingerly/server/Signal.java @@ -0,0 +1,244 @@ +package io.fingerly.server; + +/** + * The signal identifiers Fingerly reports, as the exact strings the API sends. + * + *

Two kinds of identifier share this vocabulary. {@link EventTrigger#getSignal()} + * on a stored event carries a signal group, such as {@link #VPN}, so one VPN is + * one trigger however many detectors saw it. The archived document's + * {@code risk.triggers[].signal} carries the detector itself, such as + * {@link #VPN_PUBLIC}. Many groups have a single detector of the same name, + * such as {@link #TOR} or {@link #FINGERPRINT_SUPPRESSED}. + * + *

The accessors stay plain strings, so a signal the server adds after this + * SDK was released reads normally: compare with {@code equals} or + * {@code switch}, and keep a default branch for values not listed here. + * + *

{@code
+ * boolean suppressed = event.getTriggers().stream()
+ *         .anyMatch(t -> Signal.FINGERPRINT_SUPPRESSED.equals(t.getSignal()));
+ * }
+ */ +public final class Signal { + + private Signal() {} + + /** Group and detector: a published Tor exit node. */ + public static final String TOR = "tor"; + + /** Group: a declared datacenter proxy or an unexplained datacenter address. */ + public static final String DATACENTER_PROXY = "datacenter_proxy"; + + /** Detector: a datacenter proxy, an address that looks like a proxy and lives where servers do. */ + public static final String PROXY = "proxy"; + + /** Detector: an address that lives where servers do, with no proxy or VPN claim attached. */ + public static final String DATACENTER_IP = "datacenter_ip"; + + /** Group and detector: a proxy on a consumer connection. */ + public static final String RESIDENTIAL_PROXY = "residential_proxy"; + + /** Detector: a residential proxy at low confidence, in confidence weighting mode. */ + public static final String RESIDENTIAL_PROXY_LOW_CONFIDENCE = "residential_proxy_low_confidence"; + + /** Detector: a residential proxy at medium confidence, in confidence weighting mode. */ + public static final String RESIDENTIAL_PROXY_MEDIUM_CONFIDENCE = "residential_proxy_medium_confidence"; + + /** Detector: a residential proxy at high confidence, in confidence weighting mode. */ + public static final String RESIDENTIAL_PROXY_HIGH_CONFIDENCE = "residential_proxy_high_confidence"; + + /** Group: the traffic arrived over a VPN. */ + public static final String VPN = "vpn"; + + /** Detector: a commercial VPN endpoint. */ + public static final String VPN_PUBLIC = "vpn_public"; + + /** Detector: an address whose country disagrees with the device's timezone. */ + public static final String VPN_TIMEZONE = "vpn_timezone"; + + /** Detector: Apple's Private Relay and similar relays. */ + public static final String VPN_RELAY = "vpn_relay"; + + /** Detector: a VPN on a mobile carrier network. Native only. */ + public static final String VPN_MOBILE = "vpn_mobile"; + + /** Detector: a claimed operating system the connection's own fingerprint disagrees with. Web only. */ + public static final String VPN_OS_MISMATCH = "vpn_os_mismatch"; + + /** Detector: a VPN at low confidence, in confidence weighting mode. */ + public static final String VPN_LOW_CONFIDENCE = "vpn_low_confidence"; + + /** Detector: a VPN at medium confidence, in confidence weighting mode. */ + public static final String VPN_MEDIUM_CONFIDENCE = "vpn_medium_confidence"; + + /** Detector: a VPN at high confidence, in confidence weighting mode. */ + public static final String VPN_HIGH_CONFIDENCE = "vpn_high_confidence"; + + /** Group: the address is on a public spam or attack-source blocklist. */ + public static final String IP_BLOCKLIST = "ip_blocklist"; + + /** Detector: an address on a mail-abuse blocklist. */ + public static final String IP_BLOCKLIST_EMAIL_SPAM = "ip_blocklist_email_spam"; + + /** Detector: an address on an attack-source blocklist. */ + public static final String IP_BLOCKLIST_ATTACK_SOURCE = "ip_blocklist_attack_source"; + + /** Group: the address has a recent abuse history. */ + public static final String IP_REPUTATION = "ip_reputation"; + + /** Detector: an address with a history of abuse, broader and weaker than either blocklist. */ + public static final String IP_ABUSER = "ip_abuser"; + + /** Group: a bogon or anycast address. Both detectors ship disabled. */ + public static final String NETWORK_ANOMALY = "network_anomaly"; + + /** Detector: an address that cannot appear on the public internet. */ + public static final String BOGON_IP = "bogon_ip"; + + /** Detector: an address announced from many places at once. */ + public static final String ANYCAST_IP = "anycast_ip"; + + /** Group: the device's own idea of where it is disagrees with its address. */ + public static final String LOCATION_SPOOFING = "location_spoofing"; + + /** Detector: the device's timezone or locale disagrees with where its address is. */ + public static final String GEO_MISMATCH = "geo_mismatch"; + + /** Group: the app runs in the iOS simulator. */ + public static final String IOS_SIMULATOR = "ios_simulator"; + + /** Detector: the iOS simulator. */ + public static final String SIMULATOR = "simulator"; + + /** Group: the app runs in an Android emulator. */ + public static final String ANDROID_EMULATOR = "android_emulator"; + + /** Detector: an Android emulator. */ + public static final String EMULATOR = "emulator"; + + /** Group and detector: a browser running inside a virtual machine. */ + public static final String VIRTUAL_MACHINE = "virtual_machine"; + + /** Group: a jailbroken iOS device. */ + public static final String JAILBROKEN_DEVICE = "jailbroken_device"; + + /** Detector: a jailbroken iOS device. */ + public static final String JAILBREAK = "jailbreak"; + + /** Group: a rooted Android device. */ + public static final String ROOTED_DEVICE = "rooted_device"; + + /** Detector: a rooted Android device. */ + public static final String ROOT_APPS = "root_apps"; + + /** Detector: Play Integrity says the device meets no device, strong or virtual integrity. */ + public static final String PLAY_DEVICE_INTEGRITY_FAILED = "play_device_integrity_failed"; + + /** Group: the app runs under a cloning framework or is not recognised by Google Play. */ + public static final String CLONED_APP = "cloned_app"; + + /** Detector: an app running under a cloning framework. */ + public static final String APP_CLONER = "app_cloner"; + + /** Detector: an app Google Play does not recognise, or signed by a certificate the key does not allow. */ + public static final String PLAY_APP_UNRECOGNIZED = "play_app_unrecognized"; + + /** Group and detector: a device that looks mass-provisioned or reset-fresh. */ + public static final String DEVICE_FARM = "device_farm"; + + /** Detector: an iOS device whose App Attest risk metric shows the app reinstalled or the device reset again and again. */ + public static final String REPEATED_REINSTALL = "repeated_reinstall"; + + /** Detector: Play Integrity recent device activity at {@code LEVEL_3}. */ + public static final String DEVICE_ACTIVITY_HIGH = "device_activity_high"; + + /** Detector: Play Integrity recent device activity at {@code LEVEL_4}. */ + public static final String DEVICE_ACTIVITY_VERY_HIGH = "device_activity_very_high"; + + /** Group and detector: a proxy intercepting the app's own TLS. */ + public static final String MITM_ATTACK = "mitm_attack"; + + /** Group: an instrumentation framework is attached to the process. */ + public static final String FRIDA_DETECTED = "frida_detected"; + + /** Detector: an instrumentation framework attached to the process. */ + public static final String FRIDA = "frida"; + + /** Group: the runtime was edited, claims an identity it does not have, or reused a freshness ticket. */ + public static final String BROWSER_TAMPERING = "browser_tampering"; + + /** Detector: runtime code or natives were patched or contradict what was observed. */ + public static final String TAMPERING = "tampering"; + + /** Detector: a build made to defeat fingerprinting, whose observed identity contradicts its claim. */ + public static final String ANTIDETECT_BROWSER = "antidetect_browser"; + + /** Detector: a browser report whose freshness ticket did not verify: bad signature, another key's or origin's, expired, or already used. */ + public static final String WEB_TICKET_INVALID = "web_ticket_invalid"; + + /** Group and detector: a report too thin to identify anyone. */ + public static final String FINGERPRINT_SUPPRESSED = "fingerprint_suppressed"; + + /** Group and detector: an open inspector or an attached debugger. */ + public static final String DEVELOPER_TOOLS = "developer_tools"; + + /** Group and detector: a session driven through remote desktop software. */ + public static final String REMOTE_CONTROL = "remote_control"; + + /** Group: the client is not a person. */ + public static final String BOT = "bot"; + + /** Detector: a browser driven by something other than a person. */ + public static final String AUTOMATION = "automation"; + + /** Detector: a client that says it is not a browser, or a known bad crawler. */ + public static final String BAD_BOT = "bad_bot"; + + /** Detector: a browser report without {@code Sec-Fetch-*} headers from a browser that always sends them. */ + public static final String FETCH_METADATA_MISSING = "fetch_metadata_missing"; + + /** Group and detector: a device seen far more often than an ordinary one. */ + public static final String HIGH_ACTIVITY = "high_activity"; + + /** Group: a private browsing window. */ + public static final String INCOGNITO_MODE = "incognito_mode"; + + /** Detector: a private browsing window. */ + public static final String INCOGNITO = "incognito"; + + /** Group and detector: hardened privacy settings. Ships at weight zero. */ + public static final String PRIVACY_SETTINGS = "privacy_settings"; + + /** Group and detector: a page running inside an app's web view. Ships at weight zero. */ + public static final String EMBEDDED_WEB_VIEW = "embedded_web_view"; + + /** Group and detector: a device on a voice call while the submission was made. */ + public static final String ACTIVE_CALL = "active_call"; + + /** Group and detector: a native device that could have offered hardware attestation proof and did not. */ + public static final String ATTESTATION_MISSING = "attestation_missing"; + + /** Group and detector: hardware attestation failed cryptographic, chain, replay or ownership verification. */ + public static final String ATTESTATION_FAILED = "attestation_failed"; + + /** Detector: an unproven or rejected native report naming an install an attested key owns. */ + public static final String ATTESTATION_DOWNGRADE = "attestation_downgrade"; + + /** Group and detector: reported hardware, OS or runtime realms contradict each other. */ + public static final String DEVICE_INCONSISTENT = "device_inconsistent"; + + /** Group and detector: evidence a report always carries is missing. */ + public static final String REPORT_INCOMPLETE = "report_incomplete"; + + /** Detector: a native security source ran but lists probes that threw, were denied or timed out. */ + public static final String PROBE_ERRORS = "probe_errors"; + + /** Detector: a browser report that carried no single-use freshness ticket. */ + public static final String WEB_TICKET_MISSING = "web_ticket_missing"; + + /** Group and detector: a TLS chain anchored at a non-system or user-installed root authority. */ + public static final String CUSTOM_ROOT_CA = "custom_root_ca"; + + /** Group and detector: a managed Android work profile or secondary user profile without cloner indicators. */ + public static final String SECONDARY_USER_PROFILE = "secondary_user_profile"; +} diff --git a/fingerly-server/src/main/java/io/fingerly/server/SuspectLevel.java b/fingerly-server/src/main/java/io/fingerly/server/SuspectLevel.java new file mode 100644 index 0000000..515a60f --- /dev/null +++ b/fingerly-server/src/main/java/io/fingerly/server/SuspectLevel.java @@ -0,0 +1,26 @@ +package io.fingerly.server; + +/** + * The {@link Event#getSuspectLevel()} bands, as the exact strings the API sends. + * + *

The accessor stays a plain string, null when the event was not scored. + * + *

{@code
+ * if (SuspectLevel.HIGH.equals(event.getSuspectLevel())) {
+ *     return "review";
+ * }
+ * }
+ */ +public final class SuspectLevel { + + private SuspectLevel() {} + + /** The lowest band. */ + public static final String LOW = "low"; + + /** The middle band. */ + public static final String MEDIUM = "medium"; + + /** The highest band. */ + public static final String HIGH = "high"; +} diff --git a/fingerly-server/src/main/java/io/fingerly/server/VerifyReason.java b/fingerly-server/src/main/java/io/fingerly/server/VerifyReason.java new file mode 100644 index 0000000..831b669 --- /dev/null +++ b/fingerly-server/src/main/java/io/fingerly/server/VerifyReason.java @@ -0,0 +1,42 @@ +package io.fingerly.server; + +/** + * The {@link VerifyResult#getReason()} values, as the exact strings every + * Fingerly SDK reports. + * + *
{@code
+ * switch (result.getReason()) {
+ *     case VerifyReason.OK:
+ *         break;
+ *     case VerifyReason.ALREADY_CONSUMED:
+ *         return "replayed";
+ *     default:
+ *         return "refuse";
+ * }
+ * }
+ */ +public final class VerifyReason { + + private VerifyReason() {} + + /** Every check passed. */ + public static final String OK = ""; + + /** No event has this request id: never issued, or past retention. */ + public static final String NOT_FOUND = "not_found"; + + /** The event is older than the age limit, or its time is unreadable. */ + public static final String TOO_OLD = "too_old"; + + /** The event's tag is not the expected one. */ + public static final String TAG_MISMATCH = "tag_mismatch"; + + /** The submission was unidentifiable: its {@code visitor_id} is empty. */ + public static final String UNIDENTIFIABLE = "unidentifiable"; + + /** The event was not scored. */ + public static final String UNSCORED = "unscored"; + + /** Another call consumed the event first. */ + public static final String ALREADY_CONSUMED = "already_consumed"; +} diff --git a/fingerly-server/src/main/java/io/fingerly/server/VerifyResult.java b/fingerly-server/src/main/java/io/fingerly/server/VerifyResult.java index f9465c0..5cb570b 100644 --- a/fingerly-server/src/main/java/io/fingerly/server/VerifyResult.java +++ b/fingerly-server/src/main/java/io/fingerly/server/VerifyResult.java @@ -3,29 +3,30 @@ /** * The outcome of {@link EventsService#verify(String, VerifyOptions)}. * - *

{@link #getReason()} is one of the {@code REASON_} constants, or - * {@code ""} when {@link #isOk()}. It never reflects the suspect score: score + *

{@link #getReason()} is one of the {@link VerifyReason} constants (the + * {@code REASON_} constants here are the same strings), or {@code ""} when + * {@link #isOk()}. It never reflects the suspect score: score * policy stays with the caller. */ public final class VerifyResult { /** No event has this request id: never issued, or past retention. */ - public static final String REASON_NOT_FOUND = "not_found"; + public static final String REASON_NOT_FOUND = VerifyReason.NOT_FOUND; /** The event is older than the age limit, or its time is unreadable. */ - public static final String REASON_TOO_OLD = "too_old"; + public static final String REASON_TOO_OLD = VerifyReason.TOO_OLD; /** The event's tag is not the expected one. */ - public static final String REASON_TAG_MISMATCH = "tag_mismatch"; + public static final String REASON_TAG_MISMATCH = VerifyReason.TAG_MISMATCH; /** The submission was unidentifiable: its {@code visitor_id} is empty. */ - public static final String REASON_UNIDENTIFIABLE = "unidentifiable"; + public static final String REASON_UNIDENTIFIABLE = VerifyReason.UNIDENTIFIABLE; /** The event was not scored. */ - public static final String REASON_UNSCORED = "unscored"; + public static final String REASON_UNSCORED = VerifyReason.UNSCORED; /** Another call consumed the event first. */ - public static final String REASON_ALREADY_CONSUMED = "already_consumed"; + public static final String REASON_ALREADY_CONSUMED = VerifyReason.ALREADY_CONSUMED; private final String reason; private final Event event; diff --git a/fingerly-server/src/main/java/io/fingerly/server/VisitorKind.java b/fingerly-server/src/main/java/io/fingerly/server/VisitorKind.java new file mode 100644 index 0000000..6c2d1c8 --- /dev/null +++ b/fingerly-server/src/main/java/io/fingerly/server/VisitorKind.java @@ -0,0 +1,19 @@ +package io.fingerly.server; + +/** The {@link Event#getVisitorKind()} values, as the exact strings the API sends. */ +public final class VisitorKind { + + private VisitorKind() {} + + /** A browser or an app. */ + public static final String HUMAN = "human"; + + /** A named agent collecting or answering on your content. */ + public static final String AI_BOT = "ai_bot"; + + /** A driver, headless browser or scripted client. */ + public static final String AUTOMATION = "automation"; + + /** A named search engine's crawler. */ + public static final String SEARCH_CRAWLER = "search_crawler"; +} diff --git a/fingerly-server/src/main/java/io/fingerly/server/WebhookEnvironment.java b/fingerly-server/src/main/java/io/fingerly/server/WebhookEnvironment.java new file mode 100644 index 0000000..8866bb1 --- /dev/null +++ b/fingerly-server/src/main/java/io/fingerly/server/WebhookEnvironment.java @@ -0,0 +1,13 @@ +package io.fingerly.server; + +/** The {@link WebhookEvent#getEnvironment()} values, as the exact strings the API sends. */ +public final class WebhookEnvironment { + + private WebhookEnvironment() {} + + /** Sent for production traffic. */ + public static final String LIVE = "live"; + + /** Sent for staging and development traffic. */ + public static final String TEST = "test"; +} diff --git a/fingerly-server/src/main/java/io/fingerly/server/WebhookEvent.java b/fingerly-server/src/main/java/io/fingerly/server/WebhookEvent.java index e4a75fc..9c5b3ec 100644 --- a/fingerly-server/src/main/java/io/fingerly/server/WebhookEvent.java +++ b/fingerly-server/src/main/java/io/fingerly/server/WebhookEvent.java @@ -29,7 +29,7 @@ public String getId() { return id; } - /** The event name, such as {@code identification.completed}. */ + /** The event name, such as {@code identification.completed}. See {@link WebhookEventType}. */ public String getType() { return type; } @@ -44,7 +44,7 @@ public String getOrganizationId() { return organizationId; } - /** The deployment the event came from. */ + /** The deployment the event came from: {@code live} or {@code test}. See {@link WebhookEnvironment}. */ public String getEnvironment() { return environment; } diff --git a/fingerly-server/src/main/java/io/fingerly/server/WebhookEventType.java b/fingerly-server/src/main/java/io/fingerly/server/WebhookEventType.java new file mode 100644 index 0000000..88c7fc1 --- /dev/null +++ b/fingerly-server/src/main/java/io/fingerly/server/WebhookEventType.java @@ -0,0 +1,43 @@ +package io.fingerly.server; + +/** + * The {@link WebhookEvent#getType()} values, as the exact strings the API sends. + * + *

The accessor stays a plain string, so a type the server adds after this + * SDK was released parses normally: keep a default branch for it. + * + *

{@code
+ * switch (event.getType()) {
+ *     case WebhookEventType.VISITOR_SUSPECT:
+ *         review(event.getData());
+ *         break;
+ *     case WebhookEventType.IDENTIFICATION_COMPLETED:
+ *         record(event.getData());
+ *         break;
+ *     default:
+ *         break;
+ * }
+ * }
+ */ +public final class WebhookEventType { + + private WebhookEventType() {} + + /** An identification finished. */ + public static final String IDENTIFICATION_COMPLETED = "identification.completed"; + + /** An identification request was refused. */ + public static final String IDENTIFICATION_REFUSED = "identification.refused"; + + /** A visitor scored as suspect. */ + public static final String VISITOR_SUSPECT = "visitor.suspect"; + + /** The organization's billing status changed. */ + public static final String BILLING_STATUS_CHANGED = "billing.status_changed"; + + /** A day's usage was settled. */ + public static final String USAGE_DAILY_SETTLED = "usage.daily_settled"; + + /** A test delivery sent on request to one endpoint. Nobody subscribes to it. */ + public static final String WEBHOOK_TEST = "webhook.test"; +} diff --git a/fingerly-server/src/test/java/io/fingerly/server/ConstantsTest.java b/fingerly-server/src/test/java/io/fingerly/server/ConstantsTest.java new file mode 100644 index 0000000..1baf434 --- /dev/null +++ b/fingerly-server/src/test/java/io/fingerly/server/ConstantsTest.java @@ -0,0 +1,184 @@ +package io.fingerly.server; + +import static io.fingerly.server.Fixtures.REQUEST_ID; +import static io.fingerly.server.Fixtures.SECRET_KEY; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import org.junit.jupiter.api.Test; + +/** + * Pins every named constant to the exact string the server sends. + * + *

The expected lists are copied from the server's own definitions (the risk + * signal catalogue and its groups, the suspect level bands, the attestation + * report, the webhook event types). A constant added here without a server + * value, or a server value missing here, fails. + */ +class ConstantsTest { + + /** Every detector the server's risk catalogue defines. */ + private static final List SERVER_DETECTORS = Arrays.asList( + "high_activity", "tampering", "device_farm", "developer_tools", "geo_mismatch", + "device_inconsistent", "tor", "proxy", "residential_proxy", + "residential_proxy_low_confidence", "residential_proxy_medium_confidence", + "residential_proxy_high_confidence", "vpn_public", "vpn_timezone", "vpn_relay", + "vpn_mobile", "vpn_os_mismatch", "vpn_low_confidence", "vpn_medium_confidence", + "vpn_high_confidence", "ip_blocklist_email_spam", "ip_blocklist_attack_source", + "ip_abuser", "datacenter_ip", "bogon_ip", "anycast_ip", "incognito", "bad_bot", + "automation", "fetch_metadata_missing", "web_ticket_missing", "web_ticket_invalid", + "antidetect_browser", "virtual_machine", "fingerprint_suppressed", "privacy_settings", + "embedded_web_view", "remote_control", "emulator", "root_apps", "app_cloner", + "jailbreak", "simulator", "frida", "mitm_attack", "active_call", "attestation_missing", + "attestation_downgrade", "repeated_reinstall", "device_activity_high", + "device_activity_very_high", "play_device_integrity_failed", "play_app_unrecognized", + "attestation_failed", "report_incomplete", "probe_errors", "custom_root_ca", + "secondary_user_profile"); + + /** Every group the server reports stored event triggers under. */ + private static final List SERVER_GROUPS = Arrays.asList( + "tor", "datacenter_proxy", "residential_proxy", "vpn", "ip_blocklist", "ip_reputation", + "network_anomaly", "location_spoofing", "ios_simulator", "android_emulator", + "virtual_machine", "jailbroken_device", "rooted_device", "cloned_app", "device_farm", + "mitm_attack", "frida_detected", "browser_tampering", "fingerprint_suppressed", + "developer_tools", "remote_control", "bot", "high_activity", "incognito_mode", + "privacy_settings", "embedded_web_view", "active_call", "attestation_missing", + "attestation_failed", "device_inconsistent", "report_incomplete", "custom_root_ca", + "secondary_user_profile"); + + /** Reads a constants class as name to value, failing on anything that is not a String constant. */ + private static Map constants(Class type) { + Map out = new LinkedHashMap<>(); + for (Field field : type.getDeclaredFields()) { + int modifiers = field.getModifiers(); + if (field.isSynthetic()) { + continue; + } + assertTrue(Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) + && Modifier.isFinal(modifiers) && field.getType() == String.class, + type.getSimpleName() + "." + field.getName() + " is not a public String constant"); + try { + out.put(field.getName(), (String) field.get(null)); + } catch (IllegalAccessException e) { + throw new AssertionError(e); + } + } + return out; + } + + /** Asserts each constant is named after its value and the values are exactly the expected ones. */ + private static void assertConstants(Class type, String... expected) { + Map constants = constants(type); + assertEquals(new HashSet<>(Arrays.asList(expected)), new HashSet<>(constants.values()), + type.getSimpleName()); + assertEquals(expected.length, constants.size(), type.getSimpleName() + " has a duplicate"); + constants.forEach((name, value) -> { + String derived = value.isEmpty() ? "OK" : value.toUpperCase(Locale.ROOT) + .replace('.', '_'); + assertEquals(derived, name, type.getSimpleName() + "." + name); + }); + } + + @Test + void signalCoversEveryServerDetectorAndGroup() { + Set expected = new HashSet<>(SERVER_DETECTORS); + expected.addAll(SERVER_GROUPS); + assertEquals(73, expected.size()); + assertConstants(Signal.class, expected.toArray(new String[0])); + } + + @Test + void closedSetsMatchTheServer() { + assertConstants(SuspectLevel.class, "low", "medium", "high"); + assertConstants(Confidence.class, "low", "medium", "high"); + assertConstants(AttestationState.class, "attested", "not_attested", "failed"); + assertConstants(AttestationStatus.class, + "verified", "indeterminate", "invalid", "absent", "unconfigured"); + assertConstants(AttestSkippedReason.class, "not_offered", "unsupported", + "challenge_unavailable", "key_error", "timeout", "backoff", "install_unavailable"); + assertConstants(VerifyReason.class, "", "not_found", "too_old", "tag_mismatch", + "unidentifiable", "unscored", "already_consumed"); + assertConstants(WebhookEventType.class, "identification.completed", + "identification.refused", "visitor.suspect", "billing.status_changed", + "usage.daily_settled", "webhook.test"); + assertConstants(WebhookEnvironment.class, "live", "test"); + assertConstants(EventState.class, "pending", "enriched", "unavailable"); + assertConstants(Environment.class, "production", "staging", "development"); + assertConstants(Platform.class, "web", "android", "ios"); + assertConstants(AnonymityNetwork.class, "tor", "relay", "vpn", "proxy", "hosting"); + assertConstants(DeviceKind.class, "desktop", "mobile", "tablet", "server"); + assertConstants(VisitorKind.class, "human", "ai_bot", "automation", "search_crawler"); + } + + @Test + void existingConstantsAreTheSameStrings() { + assertEquals(Signal.ATTESTATION_FAILED, EventTrigger.SIGNAL_ATTESTATION_FAILED); + assertEquals(Signal.BROWSER_TAMPERING, EventTrigger.SIGNAL_BROWSER_TAMPERING); + assertEquals(Signal.SECONDARY_USER_PROFILE, EventTrigger.SIGNAL_SECONDARY_USER_PROFILE); + assertEquals(VerifyReason.NOT_FOUND, VerifyResult.REASON_NOT_FOUND); + assertEquals(VerifyReason.ALREADY_CONSUMED, VerifyResult.REASON_ALREADY_CONSUMED); + } + + /** Compile-time constants, so they work as switch labels. */ + private static String route(String level) { + switch (level) { + case SuspectLevel.HIGH: + return "review"; + case SuspectLevel.MEDIUM: + case SuspectLevel.LOW: + return "allow"; + default: + return "unknown"; + } + } + + @Test + void unknownServerValuesStillDecode() throws IOException { + String extra = "\"suspect_level\":\"severe\"," + + "\"suspect_score\":90," + + "\"anonymity_network\":\"mesh\"," + + "\"triggers\":[{\"signal\":\"a_signal_from_the_future\",\"weight\":9}," + + "{\"signal\":\"fingerprint_suppressed\",\"weight\":4,\"confidence\":\"certain\"}],"; + String body = Fixtures.event(extra).replace("\"triggers\":[],", ""); + try (FakeApi api = FakeApi.json(200, body)) { + Event event = FingerlyClient.builder().secretKey(SECRET_KEY).allowInsecureLoopback(true) + .endpoint(api.url()).build().events().get(REQUEST_ID); + + assertEquals("severe", event.getSuspectLevel()); + assertEquals("unknown", route(event.getSuspectLevel())); + assertEquals("mesh", event.getAnonymityNetwork()); + assertEquals(EventState.ENRICHED, event.getState()); + assertEquals("a_signal_from_the_future", event.getTriggers().get(0).getSignal()); + assertEquals("certain", event.getTriggers().get(1).getConfidence()); + assertTrue(event.getTriggers().stream() + .anyMatch(t -> Signal.FINGERPRINT_SUPPRESSED.equals(t.getSignal()))); + assertFalse(SuspectLevel.HIGH.equals(event.getSuspectLevel())); + } + } + + @Test + void unknownWebhookTypeStillParses() { + byte[] body = ("{\"id\":\"evt\",\"type\":\"something.new\",\"version\":1," + + "\"organization_id\":\"org\",\"environment\":\"live\"," + + "\"created_at\":\"2026-09-16T09:41:12Z\",\"data\":{}}") + .getBytes(StandardCharsets.UTF_8); + + WebhookEvent event = Webhooks.parse(body); + + assertEquals("something.new", event.getType()); + assertEquals(WebhookEnvironment.LIVE, event.getEnvironment()); + assertFalse(WebhookEventType.VISITOR_SUSPECT.equals(event.getType())); + } +} diff --git a/gradle.properties b/gradle.properties index 1160177..e0f018c 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,4 +1,4 @@ -version=0.3.0 +version=0.4.0 org.gradle.jvmargs=-Xmx2g org.gradle.caching=true org.gradle.parallel=true