updated-packages

This commit is contained in:
RafficMohammed
2023-01-08 00:13:22 +05:30
parent 3ff7df7487
commit da241bacb6
12659 changed files with 563377 additions and 510538 deletions

View File

@@ -0,0 +1,361 @@
<?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;
/** @var boolean */
private $isUseEndpointV2;
/**
* Create a middleware wrapper function.
*
* @param Service $service
* @param $region
* @param array $config
* @return callable
*/
public static function wrap(
Service $service,
$region,
array $config,
$isUseEndpointV2
)
{
return function (callable $handler) use ($service, $region, $config, $isUseEndpointV2) {
return new self($handler, $service, $region, $config, $isUseEndpointV2);
};
}
public function __construct(
callable $nextHandler,
Service $service,
$region,
array $config = [],
$isUseEndpointV2 = false
)
{
$this->partitionProvider = PartitionEndpointProvider::defaultProvider();
$this->region = $region;
$this->service = $service;
$this->config = $config;
$this->nextHandler = $nextHandler;
$this->isUseEndpointV2 = $isUseEndpointV2;
}
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]);
!$this->isUseEndpointV2 && $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]);
!$this->isUseEndpointV2 && $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) {
if (!$this->isUseEndpointV2) {
// 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
if (isset($body)) {
$req = $req->withBody($body);
}
if ($this->isUseEndpointV2) {
$req = $req->withUri($req->getUri()->withPath($path));
goto next;
}
$req = $req
->withUri($req->getUri()->withHost($host)->withPath($path))
->withHeader('x-amz-account-id', $arn->getAccountId());
// 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();
}
}
}
}
if ($this->isUseEndpointV2) {
goto next;
}
// 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';
}
next:
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;
}
$fipsString = $this->config['use_fips_endpoint']->isUseFipsEndpoint()
? "-fips"
: "";
$suffix = $this->getPartitionSuffix($arn, $this->partitionProvider);
return "s3-outposts{$fipsString}.{$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(
\Aws\strip_fips_pseudo_regions($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;
}
}

View File

@@ -2,15 +2,137 @@
namespace Aws\S3Control;
use Aws\AwsClient;
use Aws\CacheInterface;
use Aws\HandlerList;
use Aws\S3\UseArnRegion\Configuration;
use Aws\S3\UseArnRegion\ConfigurationInterface;
use Aws\S3\UseArnRegion\ConfigurationProvider as UseArnRegionConfigurationProvider;
use GuzzleHttp\Promise\PromiseInterface;
/**
* This client is used to interact with the **AWS S3 Control** service.
* @method \Aws\Result createAccessPoint(array $args = [])
* @method \GuzzleHttp\Promise\Promise createAccessPointAsync(array $args = [])
* @method \Aws\Result createAccessPointForObjectLambda(array $args = [])
* @method \GuzzleHttp\Promise\Promise createAccessPointForObjectLambdaAsync(array $args = [])
* @method \Aws\Result createBucket(array $args = [])
* @method \GuzzleHttp\Promise\Promise createBucketAsync(array $args = [])
* @method \Aws\Result createJob(array $args = [])
* @method \GuzzleHttp\Promise\Promise createJobAsync(array $args = [])
* @method \Aws\Result createMultiRegionAccessPoint(array $args = [])
* @method \GuzzleHttp\Promise\Promise createMultiRegionAccessPointAsync(array $args = [])
* @method \Aws\Result deleteAccessPoint(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteAccessPointAsync(array $args = [])
* @method \Aws\Result deleteAccessPointForObjectLambda(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteAccessPointForObjectLambdaAsync(array $args = [])
* @method \Aws\Result deleteAccessPointPolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteAccessPointPolicyAsync(array $args = [])
* @method \Aws\Result deleteAccessPointPolicyForObjectLambda(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteAccessPointPolicyForObjectLambdaAsync(array $args = [])
* @method \Aws\Result deleteBucket(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteBucketAsync(array $args = [])
* @method \Aws\Result deleteBucketLifecycleConfiguration(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteBucketLifecycleConfigurationAsync(array $args = [])
* @method \Aws\Result deleteBucketPolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteBucketPolicyAsync(array $args = [])
* @method \Aws\Result deleteBucketTagging(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteBucketTaggingAsync(array $args = [])
* @method \Aws\Result deleteJobTagging(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteJobTaggingAsync(array $args = [])
* @method \Aws\Result deleteMultiRegionAccessPoint(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteMultiRegionAccessPointAsync(array $args = [])
* @method \Aws\Result deletePublicAccessBlock(array $args = [])
* @method \GuzzleHttp\Promise\Promise deletePublicAccessBlockAsync(array $args = [])
* @method \Aws\Result deleteStorageLensConfiguration(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteStorageLensConfigurationAsync(array $args = [])
* @method \Aws\Result deleteStorageLensConfigurationTagging(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteStorageLensConfigurationTaggingAsync(array $args = [])
* @method \Aws\Result describeJob(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeJobAsync(array $args = [])
* @method \Aws\Result describeMultiRegionAccessPointOperation(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeMultiRegionAccessPointOperationAsync(array $args = [])
* @method \Aws\Result getAccessPoint(array $args = [])
* @method \GuzzleHttp\Promise\Promise getAccessPointAsync(array $args = [])
* @method \Aws\Result getAccessPointConfigurationForObjectLambda(array $args = [])
* @method \GuzzleHttp\Promise\Promise getAccessPointConfigurationForObjectLambdaAsync(array $args = [])
* @method \Aws\Result getAccessPointForObjectLambda(array $args = [])
* @method \GuzzleHttp\Promise\Promise getAccessPointForObjectLambdaAsync(array $args = [])
* @method \Aws\Result getAccessPointPolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise getAccessPointPolicyAsync(array $args = [])
* @method \Aws\Result getAccessPointPolicyForObjectLambda(array $args = [])
* @method \GuzzleHttp\Promise\Promise getAccessPointPolicyForObjectLambdaAsync(array $args = [])
* @method \Aws\Result getAccessPointPolicyStatus(array $args = [])
* @method \GuzzleHttp\Promise\Promise getAccessPointPolicyStatusAsync(array $args = [])
* @method \Aws\Result getAccessPointPolicyStatusForObjectLambda(array $args = [])
* @method \GuzzleHttp\Promise\Promise getAccessPointPolicyStatusForObjectLambdaAsync(array $args = [])
* @method \Aws\Result getBucket(array $args = [])
* @method \GuzzleHttp\Promise\Promise getBucketAsync(array $args = [])
* @method \Aws\Result getBucketLifecycleConfiguration(array $args = [])
* @method \GuzzleHttp\Promise\Promise getBucketLifecycleConfigurationAsync(array $args = [])
* @method \Aws\Result getBucketPolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise getBucketPolicyAsync(array $args = [])
* @method \Aws\Result getBucketTagging(array $args = [])
* @method \GuzzleHttp\Promise\Promise getBucketTaggingAsync(array $args = [])
* @method \Aws\Result getBucketVersioning(array $args = [])
* @method \GuzzleHttp\Promise\Promise getBucketVersioningAsync(array $args = [])
* @method \Aws\Result getJobTagging(array $args = [])
* @method \GuzzleHttp\Promise\Promise getJobTaggingAsync(array $args = [])
* @method \Aws\Result getMultiRegionAccessPoint(array $args = [])
* @method \GuzzleHttp\Promise\Promise getMultiRegionAccessPointAsync(array $args = [])
* @method \Aws\Result getMultiRegionAccessPointPolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise getMultiRegionAccessPointPolicyAsync(array $args = [])
* @method \Aws\Result getMultiRegionAccessPointPolicyStatus(array $args = [])
* @method \GuzzleHttp\Promise\Promise getMultiRegionAccessPointPolicyStatusAsync(array $args = [])
* @method \Aws\Result getMultiRegionAccessPointRoutes(array $args = [])
* @method \GuzzleHttp\Promise\Promise getMultiRegionAccessPointRoutesAsync(array $args = [])
* @method \Aws\Result getPublicAccessBlock(array $args = [])
* @method \GuzzleHttp\Promise\Promise getPublicAccessBlockAsync(array $args = [])
* @method \Aws\Result getStorageLensConfiguration(array $args = [])
* @method \GuzzleHttp\Promise\Promise getStorageLensConfigurationAsync(array $args = [])
* @method \Aws\Result getStorageLensConfigurationTagging(array $args = [])
* @method \GuzzleHttp\Promise\Promise getStorageLensConfigurationTaggingAsync(array $args = [])
* @method \Aws\Result listAccessPoints(array $args = [])
* @method \GuzzleHttp\Promise\Promise listAccessPointsAsync(array $args = [])
* @method \Aws\Result listAccessPointsForObjectLambda(array $args = [])
* @method \GuzzleHttp\Promise\Promise listAccessPointsForObjectLambdaAsync(array $args = [])
* @method \Aws\Result listJobs(array $args = [])
* @method \GuzzleHttp\Promise\Promise listJobsAsync(array $args = [])
* @method \Aws\Result listMultiRegionAccessPoints(array $args = [])
* @method \GuzzleHttp\Promise\Promise listMultiRegionAccessPointsAsync(array $args = [])
* @method \Aws\Result listRegionalBuckets(array $args = [])
* @method \GuzzleHttp\Promise\Promise listRegionalBucketsAsync(array $args = [])
* @method \Aws\Result listStorageLensConfigurations(array $args = [])
* @method \GuzzleHttp\Promise\Promise listStorageLensConfigurationsAsync(array $args = [])
* @method \Aws\Result putAccessPointConfigurationForObjectLambda(array $args = [])
* @method \GuzzleHttp\Promise\Promise putAccessPointConfigurationForObjectLambdaAsync(array $args = [])
* @method \Aws\Result putAccessPointPolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise putAccessPointPolicyAsync(array $args = [])
* @method \Aws\Result putAccessPointPolicyForObjectLambda(array $args = [])
* @method \GuzzleHttp\Promise\Promise putAccessPointPolicyForObjectLambdaAsync(array $args = [])
* @method \Aws\Result putBucketLifecycleConfiguration(array $args = [])
* @method \GuzzleHttp\Promise\Promise putBucketLifecycleConfigurationAsync(array $args = [])
* @method \Aws\Result putBucketPolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise putBucketPolicyAsync(array $args = [])
* @method \Aws\Result putBucketTagging(array $args = [])
* @method \GuzzleHttp\Promise\Promise putBucketTaggingAsync(array $args = [])
* @method \Aws\Result putBucketVersioning(array $args = [])
* @method \GuzzleHttp\Promise\Promise putBucketVersioningAsync(array $args = [])
* @method \Aws\Result putJobTagging(array $args = [])
* @method \GuzzleHttp\Promise\Promise putJobTaggingAsync(array $args = [])
* @method \Aws\Result putMultiRegionAccessPointPolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise putMultiRegionAccessPointPolicyAsync(array $args = [])
* @method \Aws\Result putPublicAccessBlock(array $args = [])
* @method \GuzzleHttp\Promise\Promise putPublicAccessBlockAsync(array $args = [])
* @method \Aws\Result putStorageLensConfiguration(array $args = [])
* @method \GuzzleHttp\Promise\Promise putStorageLensConfigurationAsync(array $args = [])
* @method \Aws\Result putStorageLensConfigurationTagging(array $args = [])
* @method \GuzzleHttp\Promise\Promise putStorageLensConfigurationTaggingAsync(array $args = [])
* @method \Aws\Result submitMultiRegionAccessPointRoutes(array $args = [])
* @method \GuzzleHttp\Promise\Promise submitMultiRegionAccessPointRoutesAsync(array $args = [])
* @method \Aws\Result updateJobPriority(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateJobPriorityAsync(array $args = [])
* @method \Aws\Result updateJobStatus(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateJobStatusAsync(array $args = [])
*/
class S3ControlClient extends AwsClient
{
@@ -27,9 +149,41 @@ class S3ControlClient extends AwsClient
. ' \'@use_dual_stack_endpoint\' to true or false.',
'default' => false,
],
'use_arn_region' => [
'type' => 'config',
'valid' => [
'bool',
Configuration::class,
CacheInterface::class,
'callable'
],
'doc' => 'Set to true to allow passed in ARNs to override'
. ' client region. Accepts...',
'fn' => [__CLASS__, '_apply_use_arn_region'],
'default' => [UseArnRegionConfigurationProvider::class, 'defaultProvider'],
],
];
}
public static function _apply_use_arn_region($value, array &$args, HandlerList $list)
{
if ($value instanceof CacheInterface) {
$value = UseArnRegionConfigurationProvider::defaultProvider($args);
}
if (is_callable($value)) {
$value = $value();
}
if ($value instanceof PromiseInterface) {
$value = $value->wait();
}
if ($value instanceof ConfigurationInterface) {
$args['use_arn_region'] = $value;
} else {
// The Configuration class itself will validate other inputs
$args['use_arn_region'] = new Configuration($value);
}
}
/**
* {@inheritdoc}
*
@@ -48,15 +202,72 @@ class S3ControlClient extends AwsClient
public function __construct(array $args)
{
parent::__construct($args);
if ($this->isUseEndpointV2()) {
$this->processEndpointV2Model();
}
$stack = $this->getHandlerList();
$stack->appendBuild(
S3ControlEndpointMiddleware::wrap(
EndpointArnMiddleware::wrap(
$this->getApi(),
$this->getRegion(),
[
'dual_stack' => $this->getConfig('use_dual_stack_endpoint'),
]
'use_arn_region' => $this->getConfig('use_arn_region'),
'dual_stack' =>
$this->getConfig('use_dual_stack_endpoint')->isUseDualStackEndpoint(),
'endpoint' => isset($args['endpoint'])
? $args['endpoint']
: null,
'use_fips_endpoint' => $this->getConfig('use_fips_endpoint'),
],
$this->isUseEndpointV2()
),
's3control.endpoint_middleware'
's3control.endpoint_arn_middleware'
);
}
/**
* Modifies API definition to remove `AccountId`
* host prefix. This is now handled by the endpoint ruleset.
*
* @return void
*
* @internal
*/
private function processEndpointV2Model()
{
$definition = $this->getApi()->getDefinition();
$this->removeHostPrefix($definition);
$this->removeRequiredMember($definition);
$this->getApi()->setDefinition($definition);
}
private function removeHostPrefix(&$definition)
{
foreach($definition['operations'] as &$operation) {
if (isset($operation['endpoint']['hostPrefix'])
&& $operation['endpoint']['hostPrefix'] === '{AccountId}.'
) {
$operation['endpoint']['hostPrefix'] = str_replace(
'{AccountId}.',
'',
$operation['endpoint']['hostPrefix']
);
}
}
}
private function removeRequiredMember(&$definition)
{
foreach($definition['shapes'] as &$shape) {
if (isset($shape['required'])
) {
$found = array_search('AccountId', $shape['required']);
if ($found !== false) {
unset($shape['required'][$found]);
}
}
}
}
}

View File

@@ -1,121 +0,0 @@
<?php
namespace Aws\S3Control;
use Aws\CommandInterface;
use Psr\Http\Message\RequestInterface;
/**
* Used to update the URL used for S3 Control requests to support S3 Control
* DualStack. It will build to host style paths, including for S3 Control
* DualStack.
*
* IMPORTANT: this middleware must be added after the "build" step.
*
* @internal
*/
class S3ControlEndpointMiddleware
{
const NO_PATTERN = 0;
const DUALSTACK = 1;
/** @var bool */
private $dualStackByDefault;
/** @var string */
private $region;
/** @var callable */
private $nextHandler;
/**
* Create a middleware wrapper function
*
* @param string $region
* @param array $options
*
* @return callable
*/
public static function wrap($region, array $options)
{
return function (callable $handler) use ($region, $options) {
return new self($handler, $region, $options);
};
}
public function __construct(
callable $nextHandler,
$region,
array $options
) {
$this->dualStackByDefault = isset($options['dual_stack'])
? (bool) $options['dual_stack'] : false;
$this->region = (string) $region;
$this->nextHandler = $nextHandler;
}
public function __invoke(CommandInterface $command, RequestInterface $request)
{
if ($this->isDualStackRequest($command, $request)) {
$request = $this->applyDualStackEndpoint($command, $request);
}
$request = $this->applyHostStyleEndpoint($command, $request)
->withoutHeader('x-amz-account-id');
unset($command['AccountId']);
$nextHandler = $this->nextHandler;
return $nextHandler($command, $request);
}
private function isDualStackRequest(
CommandInterface $command,
RequestInterface $request
) {
return isset($command['@use_dual_stack_endpoint'])
? $command['@use_dual_stack_endpoint'] : $this->dualStackByDefault;
}
private function getDualStackHost($host)
{
$parts = explode(".{$this->region}.", $host);
return $parts[0] . ".dualstack.{$this->region}." . $parts[1];
}
private function applyDualStackEndpoint(
CommandInterface $command,
RequestInterface $request
) {
$uri = $request->getUri();
return $request->withUri(
$uri->withHost($this->getDualStackHost(
$uri->getHost()
))
);
}
private function getAccountIdStyleHost(CommandInterface $command, $host)
{
return "{$command['AccountId']}.{$host}";
}
private function getAccountIdlessPath($path, CommandInterface $command)
{
$pattern = '/^\\/' . preg_quote($command['AccountId'], '/') . '/';
return preg_replace($pattern, '', $path) ?: '/';
}
private function applyHostStyleEndpoint(
CommandInterface $command,
RequestInterface $request
) {
$uri = $request->getUri();
$request = $request->withUri(
$uri->withHost($this->getAccountIdStyleHost(
$command,
$uri->getHost()
))
->withPath($this->getAccountIdlessPath(
$uri->getPath(),
$command
))
);
return $request;
}
}