-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclass-wp-codebox-wordpress-runtime-primitives.php
More file actions
314 lines (278 loc) · 14.5 KB
/
Copy pathclass-wp-codebox-wordpress-runtime-primitives.php
File metadata and controls
314 lines (278 loc) · 14.5 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
<?php
/**
* Shared WordPress runtime primitives for workload execution.
*
* @package WPCodebox
*/
defined( 'ABSPATH' ) || exit;
/**
* Reusable safety and result-collection primitives for in-process WordPress workloads.
*/
final class WP_Codebox_WordPress_Runtime_Primitives {
/** @param array<string,mixed> $args Args. @return array<string,mixed> */
public static function external_http_guardrail( array $args ): array {
$state = is_array( $GLOBALS['wp_codebox_external_http_guardrail_state'] ?? null ) ? $GLOBALS['wp_codebox_external_http_guardrail_state'] : array();
$action = (string) ( $args['action'] ?? 'collect' );
if ( 'install' === $action ) {
$state = array(
'allowlist' => self::normalize_allowlist( $args['allowlistDomains'] ?? $args['allowlist'] ?? array() ),
'block' => filter_var( $args['blockNetwork'] ?? $args['block_network'] ?? true, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE ) ?? true,
'requests' => array(),
);
$GLOBALS['wp_codebox_external_http_guardrail_state'] = $state;
if ( empty( $GLOBALS['wp_codebox_external_http_guardrail_filter_installed'] ) && function_exists( 'add_filter' ) ) {
add_filter( 'pre_http_request', 'wp_codebox_external_http_guardrail_pre_http_request', 10, 3 );
$GLOBALS['wp_codebox_external_http_guardrail_filter_installed'] = true;
}
}
$state = is_array( $GLOBALS['wp_codebox_external_http_guardrail_state'] ?? null ) ? $GLOBALS['wp_codebox_external_http_guardrail_state'] : $state;
$requests = is_array( $state['requests'] ?? null ) ? $state['requests'] : array();
$blocked = count( array_filter( $requests, static fn( array $request ): bool => 'blocked' === ( $request['classification'] ?? '' ) ) );
$allowed = count( array_filter( $requests, static fn( array $request ): bool => in_array( (string) ( $request['classification'] ?? '' ), array( 'allowlisted', 'internal' ), true ) ) );
return array(
'schema' => 'wp-codebox/external-http-guardrail/v1',
'status' => 'passed',
'summary' => array( 'total' => count( $requests ), 'blocked' => $blocked, 'allowlisted' => $allowed ),
'requests' => $requests,
'metadata' => array(
'runner' => 'wp-codebox/wordpress-runtime-primitives/v1',
'allowlist' => array_values( array_map( 'strval', $state['allowlist'] ?? array() ) ),
'block' => (bool) ( $state['block'] ?? true ),
),
);
}
/** @param false|array|WP_Error $preempt Preempt. @param array<string,mixed> $parsed_args Parsed args. */
public static function external_http_guardrail_pre_http_request( mixed $preempt, array $parsed_args, string $url ): mixed {
$state = is_array( $GLOBALS['wp_codebox_external_http_guardrail_state'] ?? null ) ? $GLOBALS['wp_codebox_external_http_guardrail_state'] : array();
$host = strtolower( (string) wp_parse_url( $url, PHP_URL_HOST ) );
if ( '' === $host ) {
return $preempt;
}
$allowlist = array_map( 'strtolower', array_map( 'strval', is_array( $state['allowlist'] ?? null ) ? $state['allowlist'] : array() ) );
$is_internal = self::is_internal_host( $host );
$is_allowlisted = ! $is_internal && self::host_matches_allowlist( $host, $allowlist );
$classification = $is_internal ? 'internal' : ( $is_allowlisted ? 'allowlisted' : 'blocked' );
$state['requests'][] = array_filter(
array(
'url' => self::redact_url( $url ),
'host' => $host,
'method' => strtoupper( (string) ( $parsed_args['method'] ?? 'GET' ) ),
'classification' => $classification,
'headers' => self::redact_headers( is_array( $parsed_args['headers'] ?? null ) ? $parsed_args['headers'] : array() ),
),
static fn( mixed $value ): bool => ! ( is_array( $value ) && empty( $value ) ) && '' !== $value
);
$GLOBALS['wp_codebox_external_http_guardrail_state'] = $state;
if ( 'blocked' === $classification && ( $state['block'] ?? true ) ) {
return new WP_Error( 'wp_codebox_external_http_guardrail_blocked', 'External HTTP request blocked by WP Codebox fuzz guardrail.', array( 'host' => $host, 'classification' => $classification ) );
}
return $preempt;
}
/** @param array<string,mixed> $args Args. @param array<int,array<string,mixed>> $prior_steps Steps. @param array<int,array<string,mixed>> $artifact_refs Artifact refs. @return array<string,mixed> */
public static function collect_workload_result( array $args, array $prior_steps, array $artifact_refs = array() ): array {
$name = (string) ( $args['artifact'] ?? $args['name'] ?? '' );
$command = (string) ( $args['command'] ?? '' );
$status = (string) ( $args['status'] ?? '' );
$matched_steps = array_values(
array_filter(
$prior_steps,
static function ( mixed $step ) use ( $name, $command, $status ): bool {
if ( ! is_array( $step ) ) {
return false;
}
if ( '' !== $command && (string) ( $step['command'] ?? '' ) !== $command ) {
return false;
}
if ( '' !== $status && (string) ( $step['status'] ?? '' ) !== $status ) {
return false;
}
if ( '' === $name ) {
return true;
}
foreach ( is_array( $step['artifactRefs'] ?? null ) ? $step['artifactRefs'] : array() as $ref ) {
if ( is_array( $ref ) && self::artifact_matches_name( $ref, $name ) ) {
return true;
}
}
if ( self::step_has_artifact_payload( $step, $name ) ) {
return true;
}
$observation = is_array( $step['observation'] ?? null ) ? $step['observation'] : array();
return self::artifact_name_matches( (string) ( $observation['artifact'] ?? $observation['name'] ?? '' ), $name );
}
)
);
$matched_refs = array();
$matched_payloads = array();
foreach ( $matched_steps as $step ) {
foreach ( is_array( $step['artifactRefs'] ?? null ) ? $step['artifactRefs'] : array() as $ref ) {
if ( is_array( $ref ) && ( '' === $name || self::artifact_matches_name( $ref, $name ) ) ) {
$matched_refs[] = $ref;
}
}
$matched_payloads = array_merge( $matched_payloads, self::step_artifact_payloads( $step, $name ) );
}
$matched_payloads = self::dedupe_artifact_payloads( $matched_payloads );
$matched_refs = array_merge( $matched_refs, array_values( array_filter( $artifact_refs, static fn( mixed $ref ): bool => is_array( $ref ) && ( '' === $name || self::artifact_matches_name( $ref, $name ) ) ) ) );
$matched_refs = self::dedupe_artifact_refs( $matched_refs );
if ( '' === $name || empty( $matched_payloads ) ) {
$diagnostic = array(
'severity' => 'error',
'code' => 'wp_codebox_workload_result_artifact_missing',
'message' => 'Requested workload result artifact was not found or had no typed payload.',
'metadata' => array_filter( array( 'artifact' => $name, 'command' => $command, 'status' => $status ), static fn( mixed $value ): bool => '' !== $value ),
);
return array( 'status' => 'failed', 'payload' => array(), 'artifactRefs' => array(), 'diagnostics' => array( $diagnostic ) );
}
if ( count( $matched_payloads ) > 1 ) {
$diagnostic = array(
'severity' => 'error',
'code' => 'wp_codebox_workload_result_artifact_ambiguous',
'message' => 'Requested workload result artifact resolved multiple typed payloads; refine the collection query.',
'metadata' => array_filter( array( 'artifact' => $name, 'command' => $command, 'status' => $status, 'payloads' => count( $matched_payloads ) ), static fn( mixed $value ): bool => '' !== $value ),
);
return array( 'status' => 'failed', 'payload' => array(), 'artifactRefs' => array(), 'diagnostics' => array( $diagnostic ) );
}
$payload = is_array( $matched_payloads[0]['payload'] ?? null ) ? $matched_payloads[0]['payload'] : $matched_payloads[0];
$collection_name = '' === $name ? 'workload-result' : $name;
$collection_ref = array(
'name' => $collection_name,
'kind' => $collection_name,
'path' => 'files/workload-results/' . self::safe_key( $collection_name ) . '.json',
'contentType' => 'application/json',
'payload' => $payload,
);
return array( 'status' => 'passed', 'payload' => $payload, 'artifactRefs' => array_values( array_merge( $matched_refs, array( $collection_ref ) ) ), 'diagnostics' => array() );
}
/** @param mixed $value Value. @return string[] */
private static function normalize_allowlist( mixed $value ): array {
$items = is_array( $value ) ? $value : explode( ',', (string) $value );
return array_values( array_unique( array_filter( array_map( static fn( mixed $item ): string => strtolower( trim( (string) $item ) ), $items ), static fn( string $item ): bool => '' !== $item ) ) );
}
/** @param string[] $allowlist Allowlist. */
private static function host_matches_allowlist( string $host, array $allowlist ): bool {
foreach ( $allowlist as $allowed ) {
if ( $host === $allowed || str_ends_with( $host, '.' . ltrim( $allowed, '.' ) ) ) {
return true;
}
}
return false;
}
private static function is_internal_host( string $host ): bool {
$internal = array( 'localhost', '127.0.0.1', '::1' );
if ( function_exists( 'home_url' ) ) {
$home_host = strtolower( (string) wp_parse_url( home_url( '/' ), PHP_URL_HOST ) );
if ( '' !== $home_host ) {
$internal[] = $home_host;
}
}
return in_array( $host, array_unique( $internal ), true );
}
private static function redact_url( string $url ): string {
return preg_replace( '/([?&][^=]*(?:token|secret|nonce|_wpnonce|authorization|password|passwd|pwd|key|signature|sig)[^=]*=)[^&#]+/i', '$1[redacted]', $url ) ?? $url;
}
private static function safe_key( string $value ): string {
if ( function_exists( 'sanitize_key' ) ) {
$key = sanitize_key( $value );
return '' === $key ? 'result' : $key;
}
$key = strtolower( preg_replace( '/[^a-zA-Z0-9_-]+/', '-', $value ) ?? '' );
$key = trim( $key, '-' );
return '' === $key ? 'result' : $key;
}
/** @param array<string,mixed> $headers Headers. @return array<string,string> */
private static function redact_headers( array $headers ): array {
$out = array();
foreach ( $headers as $name => $value ) {
$header = (string) $name;
$out[ $header ] = preg_match( '/authorization|cookie|token|secret|nonce|api[-_]?key|x-wp-nonce/i', $header ) ? '[redacted]' : (string) ( is_array( $value ) ? implode( ', ', array_map( 'strval', $value ) ) : $value );
}
return $out;
}
/** @param array<string,mixed> $artifact Artifact ref. */
private static function artifact_matches_name( array $artifact, string $name ): bool {
return self::artifact_name_matches( (string) ( $artifact['name'] ?? $artifact['artifact'] ?? $artifact['id'] ?? '' ), $name );
}
private static function artifact_name_matches( string $candidate, string $name ): bool {
$normalize = static fn( string $value ): string => str_replace( array( '_', '-' ), '', strtolower( $value ) );
return $name === $candidate || str_replace( '_', '-', $name ) === str_replace( '_', '-', $candidate ) || $normalize( $name ) === $normalize( $candidate );
}
/** @param array<string,mixed> $step Step. */
private static function step_has_artifact_payload( array $step, string $name ): bool {
return ! empty( self::step_artifact_payloads( $step, $name ) );
}
/** @param array<string,mixed> $step Step. @return array<int,array<string,mixed>> */
private static function step_artifact_payloads( array $step, string $name ): array {
$payloads = array();
$containers = array( $step, is_array( $step['observation'] ?? null ) ? $step['observation'] : array() );
foreach ( $containers as $container ) {
$payload = is_array( $container['payload'] ?? null ) ? $container['payload'] : array();
foreach ( self::artifact_payloads_from_container( $container, $name ) as $artifact_payload ) {
$payloads[] = $artifact_payload;
}
foreach ( is_array( $payload['steps'] ?? null ) ? $payload['steps'] : array() as $payload_step ) {
if ( is_array( $payload_step ) ) {
foreach ( self::artifact_payloads_from_container( $payload_step, $name ) as $artifact_payload ) {
$payloads[] = $artifact_payload;
}
}
}
}
return $payloads;
}
/** @param array<string,mixed> $container Container. @return array<int,array<string,mixed>> */
private static function artifact_payloads_from_container( array $container, string $name ): array {
$payloads = array();
foreach ( is_array( $container['artifacts'] ?? null ) ? $container['artifacts'] : array() as $artifact_name => $payload ) {
if ( is_array( $payload ) && ( '' === $name || self::artifact_name_matches( (string) $artifact_name, $name ) ) ) {
$payloads[] = array( 'name' => (string) $artifact_name, 'payload' => $payload );
}
}
foreach ( is_array( $container['artifactRefs'] ?? null ) ? $container['artifactRefs'] : array() as $ref ) {
if ( is_array( $ref ) && is_array( $ref['payload'] ?? null ) && ( '' === $name || self::artifact_matches_name( $ref, $name ) ) ) {
$payloads[] = array( 'name' => (string) ( $ref['name'] ?? $ref['artifact'] ?? $ref['id'] ?? '' ), 'payload' => $ref['payload'] );
}
}
return $payloads;
}
/** @param array<int,array<string,mixed>> $payloads Payloads. @return array<int,array<string,mixed>> */
private static function dedupe_artifact_payloads( array $payloads ): array {
$seen = array();
$out = array();
foreach ( $payloads as $payload ) {
$key = (string) ( $payload['name'] ?? '' ) . '|' . wp_json_encode( $payload['payload'] ?? $payload );
if ( isset( $seen[ $key ] ) ) {
continue;
}
$seen[ $key ] = true;
$out[] = $payload;
}
return $out;
}
/** @param array<int,array<string,mixed>> $refs Refs. @return array<int,array<string,mixed>> */
private static function dedupe_artifact_refs( array $refs ): array {
$seen = array();
$out = array();
foreach ( $refs as $ref ) {
$key = (string) ( $ref['name'] ?? $ref['artifact'] ?? '' ) . '|' . (string) ( $ref['path'] ?? '' );
if ( isset( $seen[ $key ] ) ) {
continue;
}
$seen[ $key ] = true;
$out[] = $ref;
}
return $out;
}
}
if ( ! function_exists( 'wp_codebox_bench_run_external_http_guardrail_step' ) ) {
/** @param array<string,mixed> $args Args. @return array<string,mixed> */
function wp_codebox_bench_run_external_http_guardrail_step( array $args ): array {
return WP_Codebox_WordPress_Runtime_Primitives::external_http_guardrail( $args );
}
}
if ( ! function_exists( 'wp_codebox_external_http_guardrail_pre_http_request' ) ) {
/** @param false|array|WP_Error $preempt Preempt. @param array<string,mixed> $parsed_args Parsed args. */
function wp_codebox_external_http_guardrail_pre_http_request( mixed $preempt, array $parsed_args, string $url ): mixed {
return WP_Codebox_WordPress_Runtime_Primitives::external_http_guardrail_pre_http_request( $preempt, $parsed_args, $url );
}
}