-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathApiClient.php
More file actions
382 lines (331 loc) · 9.82 KB
/
ApiClient.php
File metadata and controls
382 lines (331 loc) · 9.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
<?php
/**
* ApiClient class file.
*/
declare( strict_types=1 );
namespace Automattic\WooCommerce\FraudProtection;
use Automattic\Jetpack\Connection\Client as Jetpack_Connection_Client;
defined( 'ABSPATH' ) || exit;
/**
* Handles communication with the Blackbox fraud protection API.
*
* Uses Jetpack Connection for authenticated requests to the Blackbox API
* to verify sessions and report fraud events. The API returns fraud protection
* decisions (allow, block, or challenge).
*
* This class implements a fail-open pattern: if the endpoint is unreachable,
* times out, or returns an error, it returns an "allow" decision to ensure
* legitimate transactions are never blocked due to service issues.
*
* @internal This class is part of the internal API and is subject to change without notice.
*/
class ApiClient {
/**
* Default timeout for API requests in seconds.
*
* Using 10 seconds as a reasonable timeout for fraud verification during checkout.
* This balances giving the API enough time to respond while not blocking
* checkout for too long if the service is slow.
*/
private const DEFAULT_TIMEOUT = 10;
/**
* Blackbox API base URL.
*/
private const BLACKBOX_API_BASE_URL = 'https://blackbox-api.wp.com/v1';
/**
* Blackbox API verify endpoint path.
*/
private const VERIFY_ENDPOINT = '/verify';
/**
* Blackbox API report endpoint path.
*/
private const REPORT_ENDPOINT = '/report';
/**
* Decision type: allow session.
*/
public const DECISION_ALLOW = 'allow';
/**
* Decision type: block session.
*/
public const DECISION_BLOCK = 'block';
/**
* Decision type: challenge session.
*/
public const DECISION_CHALLENGE = 'challenge';
/**
* Valid decision values that can be returned by the API.
*
* @var array<string>
*/
public const VALID_DECISIONS = array(
self::DECISION_ALLOW,
self::DECISION_BLOCK,
);
/**
* Report status: good outcome.
*/
public const REPORT_STATUS_GOOD = 'good';
/**
* Report status: bad outcome.
*/
public const REPORT_STATUS_BAD = 'bad';
/**
* Valid report status values.
*
* @var array<string>
*/
public const VALID_REPORT_STATUSES = array(
self::REPORT_STATUS_GOOD,
self::REPORT_STATUS_BAD,
);
/**
* Report source: chargeback event.
*/
public const REPORT_SOURCE_CHARGEBACK = 'chargeback';
/**
* Report source: manual review outcome.
*/
public const REPORT_SOURCE_MANUAL_REVIEW = 'manual_review';
/**
* Report source: API-driven event.
*/
public const REPORT_SOURCE_API = 'api';
/**
* Valid report source values.
*
* @var array<string>
*/
public const VALID_REPORT_SOURCES = array(
self::REPORT_SOURCE_CHARGEBACK,
self::REPORT_SOURCE_MANUAL_REVIEW,
self::REPORT_SOURCE_API,
);
/**
* Verify a session with the Blackbox API and get a fraud decision.
*
* Implements fail-open pattern: if the endpoint is unreachable or times out,
* returns "allow" decision and logs the error.
*
* @param string $session_id Session ID to verify.
* @param array<string, mixed> $payload Event data to send to the endpoint.
* @return string Decision: "allow" or "block".
*/
public function verify( string $session_id, array $payload ): string {
FraudProtectionController::log(
'info',
'Verifying session with Blackbox API',
array(
'session_id' => $session_id,
'payload' => $payload,
)
);
$payload = array(
'context' => $payload,
);
$response = $this->make_request(
'POST',
self::VERIFY_ENDPOINT,
$session_id,
$payload
);
return $this->process_decision_response( $response, $payload );
}
/**
* Report a fraud event to the Blackbox API.
*
* Used for reporting outcomes and feedback to improve fraud detection.
* This is a fire-and-forget operation - errors are logged but do not
* affect the checkout flow.
*
* @param string $session_id Session ID to report.
* @param array<string, mixed> $payload Event data to send to the endpoint.
* @return bool True if report was sent successfully, false otherwise.
*/
public function report( string $session_id, array $payload ): bool {
FraudProtectionController::log(
'info',
'Reporting event to Blackbox API',
array( 'payload' => $payload )
);
$response = $this->make_request( 'POST', self::REPORT_ENDPOINT, $session_id, $payload );
if ( is_wp_error( $response ) ) {
FraudProtectionController::log(
'error',
sprintf(
'Failed to report event to Blackbox API: %s',
$response->get_error_message()
),
array( 'error' => $response->get_error_data() )
);
return false;
}
FraudProtectionController::log(
'info',
'Event reported successfully',
array( 'response' => $response )
);
return true;
}
/**
* Process the API response and extract the decision.
*
* @param array<string, mixed>|\WP_Error $response API response or WP_Error.
* @param array<string, mixed> $event_data Event data for logging.
* @return string Decision: "allow" or "block".
*/
private function process_decision_response( $response, array $event_data ): string {
if ( is_wp_error( $response ) ) {
$error_data = $response->get_error_data() ?? array();
$error_data = is_array( $error_data ) ? $error_data : array( 'error' => $error_data );
FraudProtectionController::log(
'error',
sprintf(
'Blackbox API request failed: %s. Failing open with "allow" decision.',
$response->get_error_message()
),
$error_data
);
return self::DECISION_ALLOW;
}
$decision = $this->extract_decision( $response );
if ( null === $decision ) {
FraudProtectionController::log(
'error',
'Could not extract decision from response. Failing open with "allow" decision.',
array( 'response' => $response )
);
return self::DECISION_ALLOW;
}
if ( ! in_array( $decision, self::VALID_DECISIONS, true ) ) {
FraudProtectionController::log(
'error',
sprintf(
'Invalid decision value "%s". Failing open with "allow" decision.',
$decision
),
array( 'response' => $response )
);
return self::DECISION_ALLOW;
}
$session = is_array( $event_data['session'] ?? null ) ? $event_data['session'] : array();
$session_id = $session['wc_identity_id'] ?? 'unknown';
$source = $event_data['source'] ?? 'unknown';
FraudProtectionController::log(
'info',
sprintf(
'Fraud decision received: %s | Source: %s | Session: %s',
$decision,
$source,
$session_id
),
array( 'response' => $response )
);
return $decision;
}
/**
* Make an HTTP request to the Blackbox API via Jetpack Connection.
*
* Uses Jetpack's signed request mechanism which authenticates with the
* blog token scoped to the blog_id.
*
* @param string $method HTTP method (GET, POST, etc.).
* @param string $path Endpoint path (relative to Blackbox API base URL).
* @param string $session_id Session ID for the request.
* @param array<string, mixed> $payload Request payload.
* @return array<string, mixed>|\WP_Error Parsed JSON response or WP_Error on failure.
*/
private function make_request( string $method, string $path, string $session_id, array $payload ) {
if ( ! class_exists( Jetpack_Connection_Client::class ) ) {
return new \WP_Error(
'jetpack_not_available',
'Jetpack Connection is not available'
);
}
if ( ! $this->get_blog_id() ) {
return new \WP_Error(
'blog_id_not_found',
'Jetpack blog ID not found'
);
}
$body = \wp_json_encode(
array_merge(
$payload,
array(
'session_id' => $session_id,
)
)
);
if ( false === $body ) {
return new \WP_Error(
'json_encode_error',
'Failed to encode payload',
array( 'payload' => $payload )
);
}
$url = self::BLACKBOX_API_BASE_URL . $path . '/' . $session_id;
// Use Jetpack Connection Client to make a signed request.
// This authenticates with the blog token automatically.
$response = Jetpack_Connection_Client::remote_request(
array(
'url' => $url,
'method' => $method,
'timeout' => self::DEFAULT_TIMEOUT,
'headers' => array( 'Content-Type' => 'application/json' ),
'auth_location' => 'header',
),
$body
);
if ( is_wp_error( $response ) ) {
return $response;
}
/**
* Type assertion for PHPStan - Jetpack returns array on success.
*
* @var array $response
*/
$response_code = wp_remote_retrieve_response_code( $response );
$response_body = wp_remote_retrieve_body( $response );
$data = json_decode( $response_body, true );
if ( $response_code >= 300 ) {
return new \WP_Error(
'api_error',
sprintf( 'Blackbox API %s %s returned status code %d', $method, $path, $response_code ),
array( 'response' => JSON_ERROR_NONE === json_last_error() ? $data : $response_body )
);
}
if ( JSON_ERROR_NONE !== json_last_error() || ! is_array( $data ) ) {
return new \WP_Error(
'json_decode_error',
sprintf( 'Failed to decode JSON response: %s', json_last_error_msg() ),
array( 'response' => $response_body )
);
}
return $data;
}
/**
* Extract the decision string from the API response.
*
* Response format: { "data": { "decision": "allow", ... } }
*
* @param array<string, mixed> $response Parsed JSON response.
* @return string|null Lowercased decision string, or null if not extractable.
*/
private function extract_decision( array $response ): ?string {
$data = $response['data'] ?? null;
if ( is_array( $data ) && isset( $data['decision'] ) && is_string( $data['decision'] ) ) {
return \strtolower( $data['decision'] );
}
return null;
}
/**
* Get the Jetpack blog ID.
*
* @return int|false Blog ID or false if not available.
*/
private function get_blog_id() {
if ( ! class_exists( \Jetpack_Options::class ) ) {
return false;
}
return \Jetpack_Options::get_option( 'id' );
}
}