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

EndpointArnMiddleware.php « S3Control « src « aws-sdk-php « aws - github.com/nextcloud/3rdparty.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: c1e137ee046d66f66cdb2755967aef9939adec46 (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\S3Control;

use Aws\Api\Service;
use Aws\Arn\AccessPointArnInterface;
use Aws\Arn\ArnInterface;
use Aws\Arn\ArnParser;
use Aws\Arn\Exception\InvalidArnException;
use Aws\Arn\S3\BucketArnInterface;
use Aws\Arn\S3\OutpostsArnInterface;
use Aws\CommandInterface;
use Aws\Endpoint\PartitionEndpointProvider;
use Aws\Exception\InvalidRegionException;
use Aws\Exception\UnresolvedEndpointException;
use Aws\S3\EndpointRegionHelperTrait;
use GuzzleHttp\Psr7;
use Psr\Http\Message\RequestInterface;

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

    /**
     * Commands which do not do ARN expansion for a specific given shape name
     * @var array
     */
    private static $selectiveNonArnableCmds = [
        'AccessPointName' => [
            'CreateAccessPoint',
        ],
        'BucketName' => [],
    ];

    /**
     * Commands which do not do ARN expansion at all for relevant members
     * @var array
     */
    private static $nonArnableCmds = [
        'CreateBucket',
        'ListRegionalBuckets',
    ];

    /**
     * Commands which trigger endpoint and signer redirection based on presence
     * of OutpostId
     * @var array
     */
    private static $outpostIdRedirectCmds = [
        'CreateBucket',
        'ListRegionalBuckets',
    ];

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

    /**
     * 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'])
            && !in_array($cmd->getName(), self::$nonArnableCmds)
        ) {
            $service = $this->service->toArray();
            if (!empty($input = $service['shapes'][$op['input']['shape']])) {

                // Stores member name that targets 'BucketName' shape
                $bucketNameMember = null;

                // Stores member name that targets 'AccessPointName' shape
                $accesspointNameMember = null;

                foreach ($input['members'] as $key => $member) {
                    if ($member['shape'] === 'BucketName') {
                        $bucketNameMember = $key;
                    }
                    if ($member['shape'] === 'AccessPointName') {
                        $accesspointNameMember = $key;
                    }
                }

                // Determine if appropriate member contains ARN value and is
                // eligible for ARN expansion
                if (!is_null($bucketNameMember)
                    && !empty($cmd[$bucketNameMember])
                    && !in_array($cmd->getName(), self::$selectiveNonArnableCmds['BucketName'])
                    && ArnParser::isArn($cmd[$bucketNameMember])
                ) {
                    $arn = ArnParser::parse($cmd[$bucketNameMember]);
                    $partition = $this->validateBucketArn($arn);
                } elseif (!is_null($accesspointNameMember)
                    && !empty($cmd[$accesspointNameMember])
                    && !in_array($cmd->getName(), self::$selectiveNonArnableCmds['AccessPointName'])
                    && ArnParser::isArn($cmd[$accesspointNameMember])
                ) {
                    $arn = ArnParser::parse($cmd[$accesspointNameMember]);
                    $partition = $this->validateAccessPointArn($arn);
                }

                // Process only if an appropriate member contains an ARN value
                // and is an Outposts ARN
                if (!empty($arn) && $arn instanceof OutpostsArnInterface) {
                    // Generate host based on ARN
                    $host = $this->generateOutpostsArnHost($arn, $req);
                    $req = $req->withHeader('x-amz-outpost-id', $arn->getOutpostId());

                    // ARN replacement
                    $path = $req->getUri()->getPath();
                    if ($arn instanceof AccessPointArnInterface) {

                        // Replace ARN with access point name
                        $path = str_replace(
                            urlencode($cmd[$accesspointNameMember]),
                            $arn->getAccesspointName(),
                            $path
                        );

                        // Replace ARN in the payload
                        $req->getBody()->seek(0);
                        $body = Psr7\Utils::streamFor(str_replace(
                            $cmd[$accesspointNameMember],
                            $arn->getAccesspointName(),
                            $req->getBody()->getContents()
                        ));

                        // Replace ARN in the command
                        $cmd[$accesspointNameMember] = $arn->getAccesspointName();
                    } elseif ($arn instanceof BucketArnInterface) {

                        // Replace ARN in the path
                        $path = str_replace(
                            urlencode($cmd[$bucketNameMember]),
                            $arn->getBucketName(),
                            $path
                        );

                        // Replace ARN in the payload
                        $req->getBody()->seek(0);
                        $newBody = str_replace(
                            $cmd[$bucketNameMember],
                            $arn->getBucketName(),
                            $req->getBody()->getContents()
                        );
                        $body = Psr7\Utils::streamFor($newBody);

                        // Replace ARN in the command
                        $cmd[$bucketNameMember] = $arn->getBucketName();
                    }

                    // Validate or set account ID in command
                    if (isset($cmd['AccountId'])) {
                        if ($cmd['AccountId'] !== $arn->getAccountId()) {
                            throw new \InvalidArgumentException("The account ID"
                                . " supplied in the command ({$cmd['AccountId']})"
                                . " does not match the account ID supplied in the"
                                . " ARN (" . $arn->getAccountId() . ").");
                        }
                    } else {
                        $cmd['AccountId'] = $arn->getAccountId();
                    }

                    // Set modified request
                    $req = $req
                        ->withUri($req->getUri()->withHost($host)->withPath($path))
                        ->withHeader('x-amz-account-id', $arn->getAccountId());
                    if (isset($body)) {
                        $req = $req->withBody($body);
                    }

                    // Update signing region based on ARN data if configured to do so
                    if ($this->config['use_arn_region']->isUseArnRegion()) {
                        $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 ARNs
                    if ($arn instanceof OutpostsArnInterface) {
                        $cmd['@context']['signing_service'] = $arn->getService();
                    }
                }
            }
        }

        // For operations that redirect endpoint & signing service based on
        // presence of OutpostId member. These operations will likely not
        // overlap with operations that perform ARN expansion.
        if (in_array($cmd->getName(), self::$outpostIdRedirectCmds)
            && !empty($cmd['OutpostId'])
        ) {
            $req = $req->withUri(
                $req->getUri()->withHost($this->generateOutpostIdHost())
            );
            $cmd['@context']['signing_service'] = 's3-outposts';
        }

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

    private function generateOutpostsArnHost(
        OutpostsArnInterface $arn,
        RequestInterface $req
    ) {
        if (!empty($this->config['use_arn_region']->isUseArnRegion())) {
            $region = $arn->getRegion();
        } else {
            $region = $this->region;
        }
        $suffix = $this->getPartitionSuffix($arn, $this->partitionProvider);
        return "s3-outposts.{$region}.{$suffix}";
    }

    private function generateOutpostIdHost()
    {
        $partition = $this->partitionProvider->getPartition(
            $this->region,
            $this->service->getEndpointPrefix()
        );
        $suffix = $partition->getDnsSuffix();
        return "s3-outposts.{$this->region}.{$suffix}";
    }

    private function validateBucketArn(ArnInterface $arn)
    {
        if ($arn instanceof BucketArnInterface) {
            return $this->validateArn($arn);
        }

        throw new InvalidArnException('Provided ARN was not a valid S3 bucket'
            . ' ARN.');
    }

    private function validateAccessPointArn(ArnInterface $arn)
    {
        if ($arn instanceof AccessPointArnInterface) {
            return $this->validateArn($arn);
        }

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

    /**
     * Validates an ARN, returning a partition object corresponding to the ARN
     * if successful
     *
     * @param $arn
     * @return \Aws\Endpoint\Partition
     */
    private function validateArn(ArnInterface $arn)
    {
        // Dualstack is not supported with Outposts ARNs
        if ($arn instanceof OutpostsArnInterface
            && !empty($this->config['dual_stack'])
        ) {
            throw new UnresolvedEndpointException(
                'Dualstack is currently not supported with S3 Outposts ARNs.'
                . ' Please disable dualstack or do not supply an Outposts ARN.');
        }

        // Get partitions for ARN and client region
        $arnPart = $this->partitionProvider->getPartitionByName(
            $arn->getPartition()
        );
        $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(
                $this->stripPseudoRegions($this->region),
                's3'
            );
        }

        // 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;
    }
}