Welcome to mirror list, hosted at ThFree Co, Russian Federation.

BucketEndpointArnMiddleware.php « S3 « src « aws-sdk-php « aws - github.com/nextcloud/3rdparty.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 37f76135b999b08504991d818974af24a477d68c (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
<?php
namespace Aws\S3;

use Aws\Api\Service;
use Aws\Arn\AccessPointArnInterface;
use Aws\Arn\ArnParser;
use Aws\Arn\ObjectLambdaAccessPointArn;
use Aws\Arn\Exception\InvalidArnException;
use Aws\Arn\AccessPointArn as BaseAccessPointArn;
use Aws\Arn\S3\OutpostsAccessPointArn;
use Aws\Arn\S3\MultiRegionAccessPointArn;
use Aws\Arn\S3\OutpostsArnInterface;
use Aws\CommandInterface;
use Aws\Endpoint\PartitionEndpointProvider;
use Aws\Exception\InvalidRegionException;
use Aws\Exception\UnresolvedEndpointException;
use Aws\S3\Exception\S3Exception;
use InvalidArgumentException;
use Psr\Http\Message\RequestInterface;

/**
 * Checks for access point ARN in members targeting BucketName, modifying
 * endpoint as appropriate
 *
 * @internal
 */
class BucketEndpointArnMiddleware
{
    use EndpointRegionHelperTrait;

    /** @var callable */
    private $nextHandler;

    /** @var array */
    private $nonArnableCommands = ['CreateBucket'];

    /**
     * Create a middleware wrapper function.
     *
     * @param Service $service
     * @param $region
     * @param array $config
     * @return callable
     */
    public static function wrap(
        Service $service,
        $region,
        array $config

    ) {
        return function (callable $handler) use ($service, $region, $config) {
            return new self($handler, $service, $region, $config);
        };
    }

    public function __construct(
        callable $nextHandler,
        Service $service,
        $region,
        array $config = []
    ) {
        $this->partitionProvider = PartitionEndpointProvider::defaultProvider();
        $this->region = $region;
        $this->service = $service;
        $this->config = $config;
        $this->nextHandler = $nextHandler;
    }

    public function __invoke(CommandInterface $cmd, RequestInterface $req)
    {
        $nextHandler = $this->nextHandler;

        $op = $this->service->getOperation($cmd->getName())->toArray();
        if (!empty($op['input']['shape'])) {
            $service = $this->service->toArray();
            if (!empty($input = $service['shapes'][$op['input']['shape']])) {
                foreach ($input['members'] as $key => $member) {
                    if ($member['shape'] === 'BucketName') {
                        $arnableKey = $key;
                        break;
                    }
                }

                if (!empty($arnableKey) && ArnParser::isArn($cmd[$arnableKey])) {

                    try {
                        // Throw for commands that do not support ARN inputs
                        if (in_array($cmd->getName(), $this->nonArnableCommands)) {
                            throw new S3Exception(
                                'ARN values cannot be used in the bucket field for'
                                    . ' the ' . $cmd->getName() . ' operation.',
                                $cmd
                            );
                        }

                        $arn = ArnParser::parse($cmd[$arnableKey]);
                        $partition = $this->validateArn($arn);

                        $host = $this->generateAccessPointHost($arn, $req);

                        // Remove encoded bucket string from path
                        $path = $req->getUri()->getPath();
                        $encoded = rawurlencode($cmd[$arnableKey]);
                        $len = strlen($encoded) + 1;
                        if (trim(substr($path, 0, $len), '/') === "{$encoded}") {
                            $path = substr($path, $len);
                            if (substr($path, 0, 1) !== "/") {
                                $path = '/' . $path;
                            }
                        }
                        if (empty($path)) {
                            $path = '';
                        }

                        // Set modified request
                        $req = $req->withUri(
                            $req->getUri()->withPath($path)->withHost($host)
                        );

                        // Update signing region based on ARN data if configured to do so
                        if ($this->config['use_arn_region']->isUseArnRegion()
                            && !$this->config['use_fips_endpoint']->isUseFipsEndpoint()
                        ) {
                            $region = $arn->getRegion();
                        } else {
                            $region = $this->region;
                        }
                        $endpointData = $partition([
                            'region' => $region,
                            'service' => $arn->getService()
                        ]);
                        $cmd['@context']['signing_region'] = $endpointData['signingRegion'];

                        // Update signing service for Outposts and Lambda ARNs
                        if ($arn instanceof OutpostsArnInterface
                            || $arn instanceof ObjectLambdaAccessPointArn
                        ) {
                            $cmd['@context']['signing_service'] = $arn->getService();
                        }
                    } catch (InvalidArnException $e) {
                        // Add context to ARN exception
                        throw new S3Exception(
                            'Bucket parameter parsed as ARN and failed with: '
                                . $e->getMessage(),
                            $cmd,
                            [],
                            $e
                        );
                    }
                }
            }
        }

        return $nextHandler($cmd, $req);
    }

    private function generateAccessPointHost(
        BaseAccessPointArn $arn,
        RequestInterface $req
    ) {
        if ($arn instanceof OutpostsAccessPointArn) {
            $accesspointName = $arn->getAccesspointName();
        } else {
            $accesspointName = $arn->getResourceId();
        }

        if ($arn instanceof MultiRegionAccessPointArn) {
            $partition = $this->partitionProvider->getPartitionByName(
                $arn->getPartition(),
                's3'
            );
            $dnsSuffix = $partition->getDnsSuffix();
            return "{$accesspointName}.accesspoint.s3-global.{$dnsSuffix}";
        }

        $host = "{$accesspointName}-" . $arn->getAccountId();
        
        $useFips = $this->config['use_fips_endpoint']->isUseFipsEndpoint();
        $fipsString = $useFips ? "-fips" : "";

        if ($arn instanceof OutpostsAccessPointArn) {
            $host .= '.' . $arn->getOutpostId() . '.s3-outposts';
        } else if ($arn instanceof ObjectLambdaAccessPointArn) {
            if (!empty($this->config['endpoint'])) {
               return $host . '.' . $this->config['endpoint'];
            } else {
                $host .= ".s3-object-lambda{$fipsString}";
            }
        } else {
            $host .= ".s3-accesspoint{$fipsString}";
            if (!empty($this->config['dual_stack'])) {
                $host .= '.dualstack';
            }
        }

        if (!empty($this->config['use_arn_region']->isUseArnRegion())) {
            $region = $arn->getRegion();
        } else {
            $region = $this->region;
        }
        $region = \Aws\strip_fips_pseudo_regions($region);
        $host .= '.' . $region . '.' . $this->getPartitionSuffix($arn, $this->partitionProvider);
        return $host;
    }

    /**
     * Validates an ARN, returning a partition object corresponding to the ARN
     * if successful
     *
     * @param $arn
     * @return \Aws\Endpoint\Partition
     */
    private function validateArn($arn)
    {
        if ($arn instanceof AccessPointArnInterface) {

            // Dualstack is not supported with Outposts access points
            if ($arn instanceof OutpostsAccessPointArn
                && !empty($this->config['dual_stack'])
            ) {
                throw new UnresolvedEndpointException(
                    'Dualstack is currently not supported with S3 Outposts access'
                    . ' points. Please disable dualstack or do not supply an'
                    . ' access point ARN.');
            }
            if ($arn instanceof MultiRegionAccessPointArn) {
                if (!empty($this->config['disable_multiregion_access_points'])) {
                    throw new UnresolvedEndpointException(
                        'Multi-Region Access Point ARNs are disabled, but one was provided.  Please'
                        . ' enable them or provide a different ARN.'
                    );
                }
                if (!empty($this->config['dual_stack'])) {
                    throw new UnresolvedEndpointException(
                        'Multi-Region Access Point ARNs do not currently support dual stack. Please'
                        . ' disable dual stack or provide a different ARN.'
                    );
                }
            }
            // Accelerate is not supported with access points
            if (!empty($this->config['accelerate'])) {
                throw new UnresolvedEndpointException(
                    'Accelerate is currently not supported with access points.'
                    . ' Please disable accelerate or do not supply an access'
                    . ' point ARN.');
            }

            // Path-style is not supported with access points
            if (!empty($this->config['path_style'])) {
                throw new UnresolvedEndpointException(
                    'Path-style addressing is currently not supported with'
                    . ' access points. Please disable path-style or do not'
                    . ' supply an access point ARN.');
            }

            // Custom endpoint is not supported with access points
            if (!is_null($this->config['endpoint'])
                && !$arn instanceof  ObjectLambdaAccessPointArn
            ) {
                throw new UnresolvedEndpointException(
                    'A custom endpoint has been supplied along with an access'
                    . ' point ARN, and these are not compatible with each other.'
                    . ' Please only use one or the other.');
            }

            // Dualstack is not supported with object lambda access points
            if ($arn instanceof ObjectLambdaAccessPointArn
                && !empty($this->config['dual_stack'])
            ) {
                throw new UnresolvedEndpointException(
                    'Dualstack is currently not supported with Object Lambda access'
                    . ' points. Please disable dualstack or do not supply an'
                    . ' access point ARN.');
            }
            // Global endpoints do not support cross-region requests
            if ($this->isGlobal($this->region)
                && $this->config['use_arn_region']->isUseArnRegion() == false
                && $arn->getRegion() != $this->region
                && !$arn instanceof MultiRegionAccessPointArn
            ) {
                throw new UnresolvedEndpointException(
                    'Global endpoints do not support cross region requests.'
                    . ' Please enable use_arn_region or do not supply a global region'
                    . ' with a different region in the ARN.');
            }

            // Get partitions for ARN and client region
            $arnPart = $this->partitionProvider->getPartition(
                $arn->getRegion(),
                's3'
            );
            $clientPart = $this->partitionProvider->getPartition(
                $this->region,
                's3'
            );

            // If client partition not found, try removing pseudo-region qualifiers
            if (!($clientPart->isRegionMatch($this->region, 's3'))) {
                $clientPart = $this->partitionProvider->getPartition(
                    \Aws\strip_fips_pseudo_regions($this->region),
                    's3'
                );
            }
            if (!$arn instanceof MultiRegionAccessPointArn) {
                // Verify that the partition matches for supplied partition and region
                if ($arn->getPartition() !== $clientPart->getName()) {
                    throw new InvalidRegionException('The supplied ARN partition'
                        . " does not match the client's partition.");
                }
                if ($clientPart->getName() !== $arnPart->getName()) {
                    throw new InvalidRegionException('The corresponding partition'
                        . ' for the supplied ARN region does not match the'
                        . " client's partition.");
                }

                // Ensure ARN region matches client region unless
                // configured for using ARN region over client region
                $this->validateMatchingRegion($arn);

                // Ensure it is not resolved to fips pseudo-region for S3 Outposts
                $this->validateFipsConfigurations($arn);
            }

            return $arnPart;
        }

        throw new InvalidArnException('Provided ARN was not a valid S3 access'
            . ' point ARN or S3 Outposts access point ARN.');
    }

    /**
     * Checks if a region is global
     *
     * @param $region
     * @return bool
     */
    private function isGlobal($region)
    {
        return $region == 's3-external-1' || $region == 'aws-global';
    }
}