summaryrefslogtreecommitdiff
path: root/vendor/aws/aws-sdk-php/src/EndpointV2/Ruleset/RulesetStandardLibrary.php
blob: 18ec270943d0c400e17ab0f4d0c870822a09d1fd (plain)
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
<?php

namespace Aws\EndpointV2\Ruleset;

use Aws\Exception\UnresolvedEndpointException;

/**
 * Provides functions and actions to be performed for endpoint evaluation.
 * This is an internal only class and is not subject to backwards-compatibility guarantees.
 *
 * @internal
 */
class RulesetStandardLibrary
{
    const IPV4_RE = '/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/';
    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}:|
                    . ([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]
                    . {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}:)
                    . {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}|
                    . [0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:
                    . (:[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]|
                    . 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]
                    . {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]
                    . |1{0,1}[0-9]){0,1}[0-9])/';
    const TEMPLATE_ESCAPE_RE = '/{\{\s*(.*?)\s*\}\}/';
    const TEMPLATE_SEARCH_RE = '/\{[a-zA-Z#]+\}/';
    const TEMPLATE_PARSE_RE = '#\{((?>[^\{\}]+)|(?R))*\}#x';
    const HOST_LABEL_RE = '/^(?!-)[a-zA-Z\d-]{1,63}(?<!-)$/';

    private $partitions;

    public function __construct($partitions)
    {
        $this->partitions = $partitions;
    }

    /**
     * Determines if a value is set.
     *
     * @return boolean
     */
    public function is_set($value)
    {
        return isset($value);
    }

    /**
     * Function implementation of logical operator `not`
     *
     * @return boolean
     */
    public function not($value)
    {
        return !$value;
    }

    /**
     * Find an attribute within a value given a path string.
     *
     * @return mixed
     */
    public function getAttr($from, $path)
    {
        $parts = explode('.', $path);
        foreach ($parts as $part) {
            $sliceIdx = strpos($part, '[');
            if ($sliceIdx !== false) {
                if (substr($part, -1) !== ']') {
                    return null;
                }
                $slice = intval(substr($part, $sliceIdx + 1, strlen($part) - 1));
                $from = isset($from[substr($part,0, $sliceIdx)][$slice])
                    ? $from[substr($part,0, $sliceIdx)][$slice]
                    : null;
            } else {
                $from = $from[$part];
            }
        }
        return $from;
    }

    /**
     * Computes a substring given the start index and end index. If `reverse` is
     * true, slice the string from the end instead.
     *
     * @return mixed
     */
    public function substring($input, $start, $stop, $reverse)
    {
        if (!is_string($input)) {
            throw new UnresolvedEndpointException(
                'Input passed to `substring` must be `string`.'
            );
        }

        if (preg_match('/[^\x00-\x7F]/', $input)) {
            return null;
        }
        if ($start >= $stop or strlen($input) < $stop) {
            return null;
        }
        if (!$reverse) {
            return substr($input, $start, $stop - $start);
        } else {
            $offset = strlen($input) - $stop;
            $length = $stop - $start;
            return substr($input, $offset, $length);
        }
    }

    /**
     * Evaluates two strings for equality.
     *
     * @return boolean
     */
    public function stringEquals($string1, $string2)
    {
        if (!is_string($string1) || !is_string($string2)) {
            throw new UnresolvedEndpointException(
                'Values passed to StringEquals must be `string`.'
            );
        }
        return $string1 === $string2;
    }

    /**
     * Evaluates two booleans for equality.
     *
     * @return boolean
     */
    public function booleanEquals($boolean1, $boolean2)
    {
        return
            filter_var($boolean1, FILTER_VALIDATE_BOOLEAN)
            === filter_var($boolean2, FILTER_VALIDATE_BOOLEAN);
    }

    /**
     * Percent-encodes an input string.
     *
     * @return mixed
     */
    public function uriEncode($input)
    {
        if (is_null($input)) {
            return null;
        }
        return str_replace('%7E', '~', rawurlencode($input));
    }

    /**
     * Parses URL string into components.
     *
     * @return mixed
     */
    public function parseUrl($url)
    {
        $parsed = parse_url($url);

        if ($parsed === false || !empty($parsed['query'])) {
            return null;
        } elseif (!isset($parsed['scheme'])) {
            return null;
        }

        if ($parsed['scheme'] !== 'http'
            && $parsed['scheme'] !== 'https'
        ) {
            return null;
        }

        $urlInfo = [];
        $urlInfo['scheme'] = $parsed['scheme'];
        $urlInfo['authority'] = isset($parsed['host']) ? $parsed['host'] : '';
        if (isset($parsed['port'])) {
            $urlInfo['authority'] = $urlInfo['authority'] . ":" . $parsed['port'];
        }
        $urlInfo['path'] = isset($parsed['path']) ? $parsed['path'] : '';
        $urlInfo['normalizedPath'] = !empty($parsed['path'])
            ? rtrim($urlInfo['path'] ?: '', '/' .  "/") . '/'
            : '/';
        $urlInfo['isIp'] = !isset($parsed['host']) ?
            'false' : $this->isValidIp($parsed['host']);

        return $urlInfo;
    }

    /**
     * Evaluates whether a value is a valid host label per
     * RFC 1123. If allow_subdomains is true, split on `.` and validate
     * each subdomain separately.
     *
     * @return boolean
     */
    public function isValidHostLabel($hostLabel, $allowSubDomains)
    {
        if (!isset($hostLabel)
            || (!$allowSubDomains && strpos($hostLabel, '.') != false)
        ) {
            return false;
        }

        if ($allowSubDomains) {
            foreach (explode('.', $hostLabel) as $subdomain) {
                if (!$this->validateHostLabel($subdomain)) {
                    return false;
                }
            }
            return true;
        } else {
            return $this->validateHostLabel($hostLabel);
        }
    }

    /**
     * Parse and validate string for ARN components.
     *
     * @return array|null
     */
    public function parseArn($arnString)
    {
        if (is_null($arnString)
            || substr( $arnString, 0, 3 ) !== "arn"
        ) {
            return null;
        }

        $arn = [];
        $parts = explode(':', $arnString, 6);
        if (sizeof($parts) > 6) {
            return null;
        }

        $arn['partition'] = isset($parts[1]) ? $parts[1] : null;
        $arn['service'] = isset($parts[2]) ? $parts[2] : null;
        $arn['region'] = isset($parts[3]) ? $parts[3] : null;
        $arn['accountId'] = isset($parts[4]) ? $parts[4] : null;
        $arn['resourceId'] = isset($parts[5]) ? $parts[5] : null;

        if (empty($arn['partition'])
            || empty($arn['service'])
            || empty($arn['resourceId'])
        ) {
            return null;
        }
        $resource = $arn['resourceId'];
        $delimiter = strpos($resource, ':') !== false ? ':' : '/';
        $arn['resourceId'] = explode($delimiter, $resource);

        return $arn;
    }

    /**
     * Matches a region string to an AWS partition.
     *
     * @return mixed
     */
    public function partition($region)
    {
        if (!is_string($region)) {
            throw new UnresolvedEndpointException(
                'Value passed to `partition` must be `string`.'
            );
        }

        $partitions = $this->partitions;
        foreach ($partitions['partitions'] as $partition) {
            if (array_key_exists($region, $partition['regions'])
                || preg_match("/{$partition['regionRegex']}/", $region)
            ) {
                return $partition['outputs'];
            }
        }
        //return `aws` partition if no match is found.
        return $partitions['partitions'][0]['outputs'];
    }

    /**
     * Evaluates whether a value is a valid bucket name for virtual host
     * style bucket URLs.
     *
     * @return boolean
     */
    public function isVirtualHostableS3Bucket($bucketName, $allowSubdomains)
    {
        if ((is_null($bucketName)
            || (strlen($bucketName) < 3 || strlen($bucketName) > 63))
            || preg_match(self::IPV4_RE, $bucketName)
            || strtolower($bucketName) !== $bucketName
        ) {
            return false;
        }

        if ($allowSubdomains) {
            $labels = explode('.', $bucketName);
            $results = [];
            forEach($labels as $label) {
                $results[] = $this->isVirtualHostableS3Bucket($label, false);
            }
            return !in_array(false, $results);
        }
        return $this->isValidHostLabel($bucketName, false);
    }

    public function callFunction($funcCondition, &$inputParameters)
    {
        $funcArgs = [];

        forEach($funcCondition['argv'] as $arg) {
            $funcArgs[] = $this->resolveValue($arg, $inputParameters);
        }

        $funcName = str_replace('aws.', '', $funcCondition['fn']);
        if ($funcName === 'isSet') {
            $funcName = 'is_set';
        }

        $result = call_user_func_array(
            ['Aws\EndpointV2\Ruleset\RulesetStandardLibrary', $funcName],
            $funcArgs
        );

        if (isset($funcCondition['assign'])) {
            $assign = $funcCondition['assign'];
            if (isset($inputParameters[$assign])){
                throw new UnresolvedEndpointException(
                    "Assignment `{$assign}` already exists in input parameters" .
                    " or has already been assigned by an endpoint rule and cannot be overwritten."
                );
            }
            $inputParameters[$assign] = $result;
        }
        return $result;
    }

    public function resolveValue($value, $inputParameters)
    {
        //Given a value, check if it's a function, reference or template.
        //returns resolved value
        if ($this->isFunc($value)) {
            return $this->callFunction($value, $inputParameters);
        } elseif ($this->isRef($value)) {
            return isset($inputParameters[$value['ref']]) ? $inputParameters[$value['ref']] : null;
        } elseif ($this->isTemplate($value)) {
            return $this->resolveTemplateString($value, $inputParameters);
        }
        return $value;
    }

    public function isFunc($arg)
    {
        return is_array($arg) && isset($arg['fn']);
    }

    public function isRef($arg)
    {
        return is_array($arg) && isset($arg['ref']);
    }

    public function isTemplate($arg)
    {
        return is_string($arg) && !empty(preg_match(self::TEMPLATE_SEARCH_RE, $arg));
    }

    public function resolveTemplateString($value, $inputParameters)
    {
        return preg_replace_callback(
            self::TEMPLATE_PARSE_RE,
            function ($match) use ($inputParameters) {
                if (preg_match(self::TEMPLATE_ESCAPE_RE, $match[0])) {
                    return $match[1];
                }

                $notFoundMessage = 'Resolved value was null.  Please check rules and ' .
                    'input parameters and try again.';

                $parts = explode("#", $match[1]);
                if (count($parts) > 1) {
                    $resolvedValue = $inputParameters;
                    foreach($parts as $part) {
                        if (!isset($resolvedValue[$part])) {
                            throw new UnresolvedEndpointException($notFoundMessage);
                        }
                        $resolvedValue = $resolvedValue[$part];
                    }
                    return $resolvedValue;
                } else {
                    if (!isset($inputParameters[$parts[0]])) {
                        throw new UnresolvedEndpointException($notFoundMessage);
                    }
                    return $inputParameters[$parts[0]];
                }
            },
            $value
        );
    }

    private function validateHostLabel ($hostLabel)
    {
        if (empty($hostLabel) || strlen($hostLabel) > 63) {
            return false;
        }
        if (preg_match(self::HOST_LABEL_RE, $hostLabel)) {
            return true;
        }
        return false;
    }

    private function isValidIp($hostName)
    {
        $isWrapped = strpos($hostName, '[') === 0
            && strrpos($hostName, ']') === strlen($hostName) - 1;

        return preg_match(
                self::IPV4_RE,
            $hostName
        )
        //IPV6 enclosed in brackets
        || ($isWrapped && preg_match(
            self::IPV6_RE,
            $hostName
        ))
            ? 'true' : 'false';
    }
}