0
# Assessment Operations
1
2
Core fraud detection functionality that analyzes user interactions and provides risk scores, token validation, and detailed threat analysis. Assessment operations form the heart of reCAPTCHA Enterprise's fraud prevention capabilities.
3
4
## Capabilities
5
6
### Create Assessment
7
8
Analyzes user interactions to determine the likelihood of fraudulent activity. Returns a comprehensive assessment including risk scores, token validation results, and detailed fraud analysis signals.
9
10
```python { .api }
11
def create_assessment(
12
request: CreateAssessmentRequest = None,
13
*,
14
parent: str = None,
15
assessment: Assessment = None,
16
retry: Union[retries.Retry, gapic_v1.method._MethodDefault] = _MethodDefault._DEFAULT_VALUE,
17
timeout: Union[float, object] = _MethodDefault._DEFAULT_VALUE,
18
metadata: Sequence[Tuple[str, str]] = ()
19
) -> Assessment:
20
"""
21
Creates an Assessment to analyze user interactions.
22
23
Args:
24
request: The request object for creating an assessment
25
parent: Required. The name of the project in format 'projects/{project}'
26
assessment: Required. The assessment details
27
retry: Retry configuration for the request
28
timeout: Timeout for the request in seconds
29
metadata: Additional metadata for the request
30
31
Returns:
32
Assessment: Complete assessment results including risk analysis,
33
token properties, and fraud detection signals
34
35
Raises:
36
google.api_core.exceptions.GoogleAPICallError: If the request fails
37
google.api_core.exceptions.InvalidArgument: If request parameters are invalid
38
google.api_core.exceptions.PermissionDenied: If insufficient permissions
39
"""
40
```
41
42
#### Usage Example
43
44
```python
45
from google.cloud import recaptchaenterprise
46
from google.cloud.recaptchaenterprise_v1.types import Assessment, Event
47
48
client = recaptchaenterprise.RecaptchaEnterpriseServiceClient()
49
50
# Create event details
51
event = Event(
52
token="03AIIukzh7Z...", # reCAPTCHA token from frontend
53
site_key="6LdGwQ0...", # Your site key
54
user_agent="Mozilla/5.0...",
55
user_ip_address="203.0.113.1",
56
expected_action="login",
57
hashed_account_id=b"hashed_user_id"
58
)
59
60
# Create assessment
61
assessment = Assessment(event=event)
62
request = recaptchaenterprise.CreateAssessmentRequest(
63
parent="projects/your-project-id",
64
assessment=assessment
65
)
66
67
# Execute assessment
68
response = client.create_assessment(request=request)
69
70
# Analyze results
71
risk_score = response.risk_analysis.score
72
if risk_score >= 0.5:
73
print(f"Legitimate interaction (score: {risk_score})")
74
else:
75
print(f"Potential fraud detected (score: {risk_score})")
76
print(f"Reasons: {response.risk_analysis.reasons}")
77
```
78
79
### Annotate Assessment
80
81
Provides feedback on assessment accuracy to improve the machine learning model. This helps reCAPTCHA Enterprise learn from real-world outcomes and improve future assessments.
82
83
```python { .api }
84
def annotate_assessment(
85
request: AnnotateAssessmentRequest = None,
86
*,
87
name: str = None,
88
annotation: AnnotateAssessmentRequest.Annotation = None,
89
retry: Union[retries.Retry, gapic_v1.method._MethodDefault] = _MethodDefault._DEFAULT_VALUE,
90
timeout: Union[float, object] = _MethodDefault._DEFAULT_VALUE,
91
metadata: Sequence[Tuple[str, str]] = ()
92
) -> AnnotateAssessmentResponse:
93
"""
94
Annotates a previously created Assessment with feedback.
95
96
Args:
97
request: The request object for annotating an assessment
98
name: Required. The resource name of the Assessment in format
99
'projects/{project}/assessments/{assessment}'
100
annotation: Optional. The annotation providing feedback
101
retry: Retry configuration for the request
102
timeout: Timeout for the request in seconds
103
metadata: Additional metadata for the request
104
105
Returns:
106
AnnotateAssessmentResponse: Response confirming annotation was recorded
107
108
Raises:
109
google.api_core.exceptions.GoogleAPICallError: If the request fails
110
google.api_core.exceptions.NotFound: If the assessment doesn't exist
111
google.api_core.exceptions.InvalidArgument: If annotation is invalid
112
"""
113
```
114
115
#### Usage Example
116
117
```python
118
# After determining the actual outcome of a user interaction
119
assessment_name = response.name # From previous create_assessment call
120
121
# Annotate based on actual fraud outcome
122
annotation_request = recaptchaenterprise.AnnotateAssessmentRequest(
123
name=assessment_name,
124
annotation=recaptchaenterprise.AnnotateAssessmentRequest.Annotation.LEGITIMATE
125
)
126
127
client.annotate_assessment(request=annotation_request)
128
```
129
130
## Request and Response Types
131
132
### CreateAssessmentRequest
133
134
```python { .api }
135
class CreateAssessmentRequest:
136
"""Request message for creating an assessment."""
137
parent: str # Required. Project name in format 'projects/{project}'
138
assessment: Assessment # Required. The assessment details
139
```
140
141
### Assessment
142
143
```python { .api }
144
class Assessment:
145
"""Assessment of user interaction for fraud detection."""
146
name: str # Output only. Resource name
147
event: Event # Required. User event details
148
risk_analysis: RiskAnalysis # Output only. Risk analysis results
149
token_properties: TokenProperties # Output only. Token validation results
150
account_defender_assessment: AccountDefenderAssessment # Account defender results
151
fraud_prevention_assessment: FraudPreventionAssessment # Fraud prevention results
152
phone_fraud_assessment: PhoneFraudAssessment # Phone fraud analysis
153
firewall_policy_assessment: FirewallPolicyAssessment # Firewall policy results
154
account_verification: AccountVerificationInfo # Account verification
155
private_password_leak_verification: PrivatePasswordLeakVerification # Password leak check
156
```
157
158
### Event
159
160
```python { .api }
161
class Event:
162
"""User event details for assessment."""
163
token: str # Optional. reCAPTCHA token
164
site_key: str # Optional. Site key for the event
165
user_agent: str # Optional. User agent string
166
user_ip_address: str # Optional. IP address of the user
167
expected_action: str # Optional. Expected action name
168
hashed_account_id: bytes # Optional. Hashed account identifier
169
express: bool # Optional. Whether this is Express assessment
170
requested_uri: str # Optional. URI being requested
171
waf_token_assessment: bool # Optional. Whether to assess WAF token
172
ja3: str # Optional. JA3 fingerprint
173
headers: List[str] # Optional. HTTP headers
174
firewall_policy_evaluation: bool # Optional. Whether to evaluate firewall policies
175
transaction_data: TransactionData # Optional. Transaction details for fraud prevention
176
user_info: UserInfo # Optional. User information
177
```
178
179
### RiskAnalysis
180
181
```python { .api }
182
class RiskAnalysis:
183
"""Risk analysis results from assessment."""
184
score: float # Risk score between 0.0 (likely fraud) and 1.0 (likely legitimate)
185
reasons: List[str] # List of reasons for the risk score
186
extended_verdict: ExtendedVerdict # Extended verdict with additional context
187
188
class ExtendedVerdict:
189
"""Extended verdict information."""
190
class Verdict(Enum):
191
VERDICT_UNSPECIFIED = 0
192
LEGITIMATE = 1
193
SUSPICIOUS = 2
194
MALICIOUS = 3
195
```
196
197
### TokenProperties
198
199
```python { .api }
200
class TokenProperties:
201
"""Properties of the reCAPTCHA token."""
202
valid: bool # Whether the token is valid
203
invalid_reason: str # Reason for invalidity if token is invalid
204
hostname: str # Hostname for which the token was generated
205
android_package_name: str # Android package name (if applicable)
206
ios_bundle_id: str # iOS bundle ID (if applicable)
207
action: str # Action associated with the token
208
create_time: Timestamp # When the token was created
209
210
class InvalidReason(Enum):
211
"""Reasons why a token might be invalid."""
212
INVALID_REASON_UNSPECIFIED = 0
213
UNKNOWN_INVALID_REASON = 1
214
MALFORMED = 2
215
EXPIRED = 3
216
DUPE = 4
217
MISSING = 5
218
BROWSER_ERROR = 6
219
```
220
221
### Advanced Assessment Types
222
223
```python { .api }
224
class AccountDefenderAssessment:
225
"""Account Defender assessment results."""
226
labels: List[str] # Account defender labels
227
228
class FraudPreventionAssessment:
229
"""Fraud prevention assessment results."""
230
transaction_risk: float # Transaction risk score
231
stolen_instrument_verdict: StolenInstrumentVerdict # Stolen instrument analysis
232
card_testing_verdict: CardTestingVerdict # Card testing analysis
233
behavioral_trust_verdict: BehavioralTrustVerdict # Behavioral trust analysis
234
235
class PhoneFraudAssessment:
236
"""Phone fraud assessment results."""
237
sms_toll_fraud_verdict: SmsTollFraudVerdict # SMS toll fraud analysis
238
239
class SmsTollFraudVerdict:
240
"""SMS toll fraud verdict."""
241
reasons: List[str] # Reasons for the verdict
242
risk: float # Risk score for SMS toll fraud
243
244
class FirewallPolicyAssessment:
245
"""Firewall policy assessment results."""
246
firewall_policy: FirewallPolicy # The firewall policy that matched
247
error: Status # Error information if policy evaluation failed
248
```
249
250
### AnnotateAssessmentRequest
251
252
```python { .api }
253
class AnnotateAssessmentRequest:
254
"""Request to annotate an assessment with feedback."""
255
name: str # Required. Assessment name
256
annotation: Annotation # Optional. The annotation
257
reasons: List[Reason] # Optional. Reasons for the annotation
258
hashed_account_id: bytes # Optional. Account identifier
259
transaction_event: TransactionEvent # Optional. Transaction event details
260
261
class Annotation(Enum):
262
"""Annotation values for assessment feedback."""
263
ANNOTATION_UNSPECIFIED = 0
264
LEGITIMATE = 1
265
FRAUDULENT = 2
266
PASSWORD_CORRECT = 3
267
PASSWORD_INCORRECT = 4
268
269
class Reason(Enum):
270
"""Reasons for annotation."""
271
REASON_UNSPECIFIED = 0
272
CHARGEBACK = 1
273
CHARGEBACK_FRAUD = 8
274
CHARGEBACK_DISPUTE = 9
275
REFUND = 10
276
REFUND_FRAUD = 11
277
TRANSACTION_ACCEPTED = 12
278
TRANSACTION_DECLINED = 13
279
PAYMENT_HEURISTICS = 2
280
INITIATED_TWO_FACTOR = 7
281
PASSED_TWO_FACTOR = 3
282
FAILED_TWO_FACTOR = 4
283
CORRECT_PASSWORD = 5
284
INCORRECT_PASSWORD = 6
285
```
286
287
### AnnotateAssessmentResponse
288
289
```python { .api }
290
class AnnotateAssessmentResponse:
291
"""Response message for annotation request."""
292
# This message is typically empty, indicating successful annotation
293
```
294
295
### Additional Assessment Types
296
297
```python { .api }
298
class AccountVerificationInfo:
299
"""Information about account verification for identity verification."""
300
endpoints: List[EndpointVerificationInfo] # Endpoints for identity verification
301
language_code: str # Language preference for verification
302
latest_verification_result: Result # Result of latest verification challenge
303
username: str # Username being verified (deprecated)
304
305
class EndpointVerificationInfo:
306
"""Information about a verification endpoint for 2FA."""
307
email_address: str # Email endpoint for verification
308
phone_number: str # Phone endpoint for verification
309
310
class PrivatePasswordLeakVerification:
311
"""Private password leak verification information."""
312
lookup_hash_prefix: bytes # 26-bit prefix of SHA-256 hash
313
encrypted_user_credentials_hash: bytes # Encrypted Scrypt hash
314
encrypted_leak_match_prefixes: List[bytes] # Encrypted leak match prefixes
315
reencrypted_user_credentials_hash: bytes # Re-encrypted hash
316
317
class TransactionData:
318
"""Transaction data for payment fraud prevention."""
319
transaction_id: str # Unique transaction identifier
320
payment_method: str # Payment method used
321
card_bin: str # Bank identification number
322
card_last_four: str # Last four digits of card
323
currency_code: str # Transaction currency
324
value: float # Transaction value
325
shipping_value: float # Shipping cost
326
shipping_address: TransactionData.Address # Shipping address
327
billing_address: TransactionData.Address # Billing address
328
user: TransactionData.User # User information
329
merchants: List[TransactionData.User] # Merchant information
330
items: List[TransactionData.Item] # Transaction items
331
gateway_info: TransactionData.GatewayInfo # Payment gateway information
332
333
class TransactionEvent:
334
"""Describes an event in payment transaction lifecycle."""
335
event_type: TransactionEventType # Type of transaction event
336
reason: str # Reason or code for the event
337
value: float # Value associated with event
338
event_time: Timestamp # When event occurred
339
340
class UserInfo:
341
"""User information for assessment."""
342
create_account_time: Timestamp # Account creation time
343
account_id: str # Account identifier
344
user_ids: List[UserId] # Associated user identifiers
345
346
class UserId:
347
"""User identifier for assessment."""
348
email: str # Email address
349
phone_number: str # Phone number
350
username: str # Username
351
account_id: str # Account ID
352
353
class FraudSignals:
354
"""Fraud signals describing users and cards in transaction."""
355
user_signals: FraudSignals.UserSignals # User-related fraud signals
356
card_signals: FraudSignals.CardSignals # Card-related fraud signals
357
358
class AssessmentEnvironment:
359
"""Environment information for assessment creation."""
360
client: str # Client module information
361
version: str # Client version
362
```
363
364
## Error Handling
365
366
Common errors when working with assessments:
367
368
```python
369
from google.api_core import exceptions
370
371
try:
372
response = client.create_assessment(request=request)
373
except exceptions.InvalidArgument as e:
374
# Invalid request parameters (missing required fields, malformed data)
375
print(f"Invalid request: {e}")
376
except exceptions.PermissionDenied as e:
377
# Insufficient IAM permissions for reCAPTCHA Enterprise API
378
print(f"Permission denied: {e}")
379
except exceptions.ResourceExhausted as e:
380
# Rate limits or quota exceeded
381
print(f"Rate limit exceeded: {e}")
382
except exceptions.FailedPrecondition as e:
383
# Site key not configured properly or project setup issues
384
print(f"Precondition failed: {e}")
385
```
386
387
## Best Practices
388
389
### Assessment Creation
390
- Always include `user_ip_address` and `user_agent` for better accuracy
391
- Use meaningful `expected_action` names that match your application's actions
392
- Include `hashed_account_id` for account-level analysis
393
- Set appropriate timeout values for real-time assessments
394
395
### Annotation Feedback
396
- Annotate assessments with actual outcomes to improve model accuracy
397
- Include transaction events for e-commerce fraud prevention
398
- Provide detailed reasons when possible
399
- Annotate both legitimate and fraudulent cases consistently
400
401
### Score Interpretation
402
- Scores closer to 1.0 indicate legitimate user behavior
403
- Scores closer to 0.0 indicate potential fraud or bot activity
404
- Consider score thresholds based on your risk tolerance
405
- Use additional assessment signals beyond just the main score