Debian Codegraph @

lib/3rdParty/composer/aws/aws-sdk-php/src/EndpointV2/Ruleset/RulesetStandardLibrary.php

raw symbols SCIP
1 <?php
2
3 namespace Aws\EndpointV2\Ruleset;
4
5 use Aws\Exception\UnresolvedEndpointException;
6
7 /**
8 * Provides functions and actions to be performed for endpoint evaluation.
9 * This is an internal only class and is not subject to backwards-compatibility guarantees.
10 *
11 * @internal
12 */
13 class RulesetStandardLibrary
14 {
15 const IPV4_RE = '/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/';
16 const IPV6_RE = '/([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|
17 . ([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]
18 . {1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:)
19 . {1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|
20 . [0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:
21 . (:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|
22 . 1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]
23 . {1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]
24 . |1{0,1}[0-9]){0,1}[0-9])/';
25 const TEMPLATE_SEARCH_RE = '/\{\{.*?\}\}|\{[a-zA-Z0-9_#]+\}/';
26 const TEMPLATE_PARSE_RE = '/\{\{\s*([^{}]*?)\s*\}\}|\{([a-zA-Z0-9_]+(?:#[a-zA-Z0-9_]+)*)\}/';
27 const HOST_LABEL_RE = '/^(?!-)[a-zA-Z\d-]{1,63}(?<!-)$/';
28 private $partitions;
29
30 public function __construct($partitions)
31 {
32 $this->partitions = $partitions;
33 }
34
35 /**
36 * Determines if a value is set.
37 *
38 * @return boolean
39 */
40 public function is_set($value)
41 {
42 return isset($value);
43 }
44
45 /**
46 * Function implementation of logical operator `not`
47 *
48 * @return boolean
49 */
50 public function not($value)
51 {
52 return !$value;
53 }
54
55 /**
56 * Find an attribute within a value given a path string.
57 *
58 * @return mixed
59 */
60 public function getAttr($from, $path)
61 {
62 // Handles the case where "[<int|string]" is provided as the top-level path
63 if (preg_match('/^\[(\w+)\]$/', $path, $matches)) {
64 $index = is_numeric($matches[1]) ? (int) $matches[1] : $matches[1];
65
66 return $from[$index] ?? null;
67 }
68
69 $parts = explode('.', $path);
70 foreach ($parts as $part) {
71 $sliceIdx = strpos($part, '[');
72 if ($sliceIdx !== false) {
73 if (substr($part, -1) !== ']') {
74 return null;
75 }
76 $slice = (int) substr($part, $sliceIdx + 1, strlen($part) - 1);
77 $fromIndex = substr($part, 0, $sliceIdx);
78 $from = $from[$fromIndex][$slice] ?? null;
79 } else {
80 $from = $from[$part];
81 }
82 }
83 return $from;
84 }
85
86 /**
87 * Computes a substring given the start index and end index. If `reverse` is
88 * true, slice the string from the end instead.
89 *
90 * @return mixed
91 */
92 public function substring($input, $start, $stop, $reverse)
93 {
94 if (!is_string($input)) {
95 throw new UnresolvedEndpointException(
96 'Input passed to `substring` must be `string`.'
97 );
98 }
99
100 if (preg_match('/[^\x00-\x7F]/', $input)) {
101 return null;
102 }
103 if ($start >= $stop or strlen($input) < $stop) {
104 return null;
105 }
106 if (!$reverse) {
107 return substr($input, $start, $stop - $start);
108 } else {
109 $offset = strlen($input) - $stop;
110 $length = $stop - $start;
111 return substr($input, $offset, $length);
112 }
113 }
114
115 /**
116 * Evaluates two strings for equality.
117 *
118 * @return boolean
119 */
120 public function stringEquals($string1, $string2)
121 {
122 if (!is_string($string1) || !is_string($string2)) {
123 throw new UnresolvedEndpointException(
124 'Values passed to StringEquals must be `string`.'
125 );
126 }
127 return $string1 === $string2;
128 }
129
130 /**
131 * Evaluates two booleans for equality.
132 *
133 * @return boolean
134 */
135 public function booleanEquals($boolean1, $boolean2)
136 {
137 return
138 filter_var($boolean1, FILTER_VALIDATE_BOOLEAN)
139 === filter_var($boolean2, FILTER_VALIDATE_BOOLEAN);
140 }
141
142 /**
143 * Percent-encodes an input string.
144 *
145 * @return mixed
146 */
147 public function uriEncode($input)
148 {
149 if (is_null($input)) {
150 return null;
151 }
152 return str_replace('%7E', '~', rawurlencode($input));
153 }
154
155 /**
156 * Parses URL string into components.
157 *
158 * @return mixed
159 */
160 public function parseUrl($url)
161 {
162 if (is_null($url)) {
163 return null;
164 }
165
166 $parsed = parse_url($url);
167
168 if ($parsed === false || !empty($parsed['query'])) {
169 return null;
170 } elseif (!isset($parsed['scheme'])) {
171 return null;
172 }
173
174 if ($parsed['scheme'] !== 'http'
175 && $parsed['scheme'] !== 'https'
176 ) {
177 return null;
178 }
179
180 $urlInfo = [];
181 $urlInfo['scheme'] = $parsed['scheme'];
182 $urlInfo['authority'] = $parsed['host'] ?? '';
183 if (isset($parsed['port'])) {
184 $urlInfo['authority'] = $urlInfo['authority'] . ":" . $parsed['port'];
185 }
186 $urlInfo['path'] = $parsed['path'] ?? '';
187 $urlInfo['normalizedPath'] = !empty($parsed['path'])
188 ? rtrim($urlInfo['path'] ?: '', '/' . "/") . '/'
189 : '/';
190 $urlInfo['isIp'] = !isset($parsed['host']) ?
191 'false' : $this->isValidIp($parsed['host']);
192
193 return $urlInfo;
194 }
195
196 /**
197 * Evaluates whether a value is a valid host label per
198 * RFC 1123. If allow_subdomains is true, split on `.` and validate
199 * each subdomain separately.
200 *
201 * @return boolean
202 */
203 public function isValidHostLabel($hostLabel, $allowSubDomains)
204 {
205 if (!isset($hostLabel)
206 || (!$allowSubDomains && strpos($hostLabel, '.') != false)
207 ) {
208 return false;
209 }
210
211 if ($allowSubDomains) {
212 foreach (explode('.', $hostLabel) as $subdomain) {
213 if (!$this->validateHostLabel($subdomain)) {
214 return false;
215 }
216 }
217 return true;
218 } else {
219 return $this->validateHostLabel($hostLabel);
220 }
221 }
222
223 /**
224 * Parse and validate string for ARN components.
225 *
226 * @return array|null
227 */
228 public function parseArn($arnString)
229 {
230 if (!is_string($arnString)
231 || strncmp($arnString, 'arn', 3) !== 0
232 ) {
233 return null;
234 }
235
236 $parts = explode(':', $arnString, 6);
237 if (count($parts) < 6) {
238 return null;
239 }
240
241 $partition = $parts[1];
242 $service = $parts[2];
243 $region = $parts[3];
244 $accountId = $parts[4];
245 $resource = $parts[5];
246
247 if ($partition === ''
248 || $service === ''
249 || $resource === ''
250 ) {
251 return null;
252 }
253
254 return [
255 'partition' => $partition,
256 'service' => $service,
257 'region' => $region,
258 'accountId' => $accountId,
259 'resourceId' => preg_split("/[:\/]/", $resource),
260 ];
261 }
262
263 /**
264 * Matches a region string to an AWS partition.
265 *
266 * @return mixed
267 */
268 public function partition($region)
269 {
270 if (!is_string($region)) {
271 throw new UnresolvedEndpointException(
272 'Value passed to `partition` must be `string`.'
273 );
274 }
275
276 $partitions = $this->partitions;
277 foreach ($partitions['partitions'] as $partition) {
278 if (array_key_exists($region, $partition['regions'])
279 || preg_match("/{$partition['regionRegex']}/", $region)
280 ) {
281 return $partition['outputs'];
282 }
283 }
284 //return `aws` partition if no match is found.
285 return $partitions['partitions'][0]['outputs'];
286 }
287
288 /**
289 * Returns the first non-null argument, or null if every argument is null.
290 * Mirrors the standard library `coalesce` function and accepts any number
291 * of already-resolved values.
292 *
293 * @return mixed
294 */
295 public function coalesce(...$values)
296 {
297 foreach ($values as $value) {
298 if (!is_null($value)) {
299 return $value;
300 }
301 }
302 return null;
303 }
304
305 /**
306 * Splits a string on a delimiter up to an optional limit, returning an
307 * array of string parts. Mirrors the smithy `split` function: a `null` or
308 * `0` limit means "no limit", a positive limit caps the number of parts,
309 * and any other input (non-string, empty delimiter, negative limit)
310 * returns null so downstream conditions treat it as "no value".
311 *
312 * @return array|null
313 */
314 public function split($input, $delimiter, $limit = null)
315 {
316 if (!is_string($input) || !is_string($delimiter) || $delimiter === '') {
317 return null;
318 }
319
320 if (is_null($limit) || $limit === 0) {
321 return explode($delimiter, $input);
322 }
323
324 if (!is_int($limit) || $limit < 0) {
325 return null;
326 }
327
328 return explode($delimiter, $input, $limit);
329 }
330
331 /**
332 * Functional if-then-else. Returns `$then` when `$condition` is truthy,
333 * otherwise `$else`. Arguments are resolved eagerly by the caller, which
334 * matches the rules engine semantics for function arguments.
335 *
336 * @return mixed
337 */
338 public function ite($condition, $then, $else)
339 {
340 return filter_var($condition, FILTER_VALIDATE_BOOLEAN) ? $then : $else;
341 }
342
343 /**
344 * Evaluates whether a value is a valid bucket name for virtual host
345 * style bucket URLs.
346 *
347 * @return boolean
348 */
349 public function isVirtualHostableS3Bucket($bucketName, $allowSubdomains)
350 {
351 if ((is_null($bucketName)
352 || (strlen($bucketName) < 3 || strlen($bucketName) > 63))
353 || preg_match(self::IPV4_RE, $bucketName)
354 || strtolower($bucketName) !== $bucketName
355 ) {
356 return false;
357 }
358
359 if ($allowSubdomains) {
360 $labels = explode('.', $bucketName);
361 $results = [];
362 forEach($labels as $label) {
363 $results[] = $this->isVirtualHostableS3Bucket($label, false);
364 }
365 return !in_array(false, $results);
366 }
367 return $this->isValidHostLabel($bucketName, false);
368 }
369
370 public function callFunction($funcCondition, &$inputParameters)
371 {
372 $argv = $funcCondition['argv'];
373 $assign = $funcCondition['assign'] ?? null;
374 $fn = $funcCondition['fn'];
375 switch ($fn) {
376 case 'aws.parseArn':
377 $result = $this->parseArn(
378 $this->resolveValue($argv[0], $inputParameters)
379 );
380 break;
381
382 case 'getAttr':
383 $result = $this->getAttr(
384 $this->resolveValue($argv[0], $inputParameters),
385 $argv[1]
386 );
387 break;
388
389 case 'stringEquals':
390 $result = $this->stringEquals(
391 $this->resolveValue($argv[0], $inputParameters),
392 $this->resolveValue($argv[1], $inputParameters)
393 );
394 break;
395
396 case 'booleanEquals':
397 $result = $this->booleanEquals(
398 $this->resolveValue($argv[0], $inputParameters),
399 $this->resolveValue($argv[1], $inputParameters)
400 );
401 break;
402
403 case 'isSet':
404 $arg = $argv[0];
405 $result = isset($arg['ref'])
406 ? isset($inputParameters[$arg['ref']])
407 : $this->is_set($this->resolveValue($arg, $inputParameters));
408 break;
409
410 case 'not':
411 $result = $this->not(
412 $this->resolveValue($argv[0], $inputParameters)
413 );
414 break;
415
416 case 'substring':
417 $result = $this->substring(
418 $this->resolveValue($argv[0], $inputParameters),
419 $this->resolveValue($argv[1], $inputParameters),
420 $this->resolveValue($argv[2], $inputParameters),
421 isset($argv[3])
422 ? $this->resolveValue($argv[3], $inputParameters)
423 : false
424 );
425 break;
426
427 default:
428 $funcArgs = [];
429 foreach ($argv as $arg) {
430 $funcArgs[] = $this->resolveValue($arg, $inputParameters);
431 }
432
433 $funcName = str_replace('aws.', '', $fn);
434 if ($funcName === 'isSet') {
435 $funcName = 'is_set';
436 }
437
438 if (!method_exists($this, $funcName)) {
439 throw new UnresolvedEndpointException(
440 "Unknown endpoint function `{$fn}`."
441 );
442 }
443
444 $result = call_user_func_array(
445 [$this, $funcName],
446 $funcArgs
447 );
448 }
449
450 if ($assign !== null) {
451 if (isset($inputParameters[$assign])) {
452 throw new UnresolvedEndpointException(
453 "Assignment `{$assign}` already exists in input parameters" .
454 " or has already been assigned by an endpoint rule and cannot be overwritten."
455 );
456 }
457 $inputParameters[$assign] = $result;
458 }
459 return $result;
460 }
461
462 public function resolveValue($value, $inputParameters)
463 {
464 //Given a value, check if it's a function, reference or template.
465 //returns resolved value
466 if (is_array($value)) {
467 if (isset($value['fn'])) {
468 return $this->callFunction($value, $inputParameters);
469 }
470 if (isset($value['ref'])) {
471 return $inputParameters[$value['ref']] ?? null;
472 }
473 } elseif (is_string($value)
474 && str_contains($value, '{')
475 && $this->isTemplate($value)
476 ) {
477 return $this->resolveTemplateString($value, $inputParameters);
478 }
479
480 return $value;
481 }
482
483 public function isFunc($arg)
484 {
485 return is_array($arg) && isset($arg['fn']);
486 }
487
488 public function isRef($arg)
489 {
490 return is_array($arg) && isset($arg['ref']);
491 }
492
493 public function isTemplate($arg)
494 {
495 return is_string($arg)
496 && str_contains($arg, '{')
497 && preg_match(self::TEMPLATE_SEARCH_RE, $arg) === 1;
498 }
499
500 public function resolveTemplateString($value, $inputParameters)
501 {
502 return preg_replace_callback(
503 self::TEMPLATE_PARSE_RE,
504 function ($match) use ($inputParameters) {
505 if (str_starts_with($match[0], '{{')) {
506 return '{' . $match[1] . '}';
507 }
508
509 $notFoundMessage = 'Resolved value was null. Please check rules and ' .
510 'input parameters and try again.';
511
512 $parts = explode("#", $match[2]);
513 if (count($parts) > 1) {
514 $resolvedValue = $inputParameters;
515 foreach($parts as $part) {
516 if (!isset($resolvedValue[$part])) {
517 throw new UnresolvedEndpointException($notFoundMessage);
518 }
519 $resolvedValue = $resolvedValue[$part];
520 }
521 return $resolvedValue;
522 } else {
523 if (!isset($inputParameters[$parts[0]])) {
524 throw new UnresolvedEndpointException($notFoundMessage);
525 }
526 return $inputParameters[$parts[0]];
527 }
528 },
529 $value
530 );
531 }
532
533 private function validateHostLabel ($hostLabel)
534 {
535 if (empty($hostLabel) || strlen($hostLabel) > 63) {
536 return false;
537 }
538 if (preg_match(self::HOST_LABEL_RE, $hostLabel)) {
539 return true;
540 }
541 return false;
542 }
543
544 private function isValidIp($hostName)
545 {
546 $isWrapped = strpos($hostName, '[') === 0
547 && strrpos($hostName, ']') === strlen($hostName) - 1;
548
549 return preg_match(
550 self::IPV4_RE,
551 $hostName
552 )
553 //IPV6 enclosed in brackets
554 || ($isWrapped && preg_match(
555 self::IPV6_RE,
556 $hostName
557 ))
558 ? 'true' : 'false';
559 }
560 }