new appraoch

This commit is contained in:
Tim Bendt
2025-11-26 13:22:58 -05:00
parent de3d100844
commit c520b7df89
6760 changed files with 1009780 additions and 0 deletions

View File

@@ -0,0 +1,96 @@
<?php
namespace Aws\Endpoint;
use Aws\Exception\UnresolvedEndpointException;
/**
* Endpoint providers.
*
* An endpoint provider is a function that accepts a hash of endpoint options,
* including but not limited to "service" and "region" key value pairs. The
* endpoint provider function returns a hash of endpoint data, which MUST
* include an "endpoint" key value pair that represents the resolved endpoint
* or NULL if an endpoint cannot be determined.
*
* You can wrap your calls to an endpoint provider with the
* {@see EndpointProvider::resolve} function to ensure that an endpoint hash is
* created. If an endpoint hash is not created, then the resolve() function
* will throw an {@see Aws\Exception\UnresolvedEndpointException}.
*
* use Aws\Endpoint\EndpointProvider;
* $provider = EndpointProvider::defaultProvider();
* // Returns an array or NULL.
* $endpoint = $provider(['service' => 'ec2', 'region' => 'us-west-2']);
* // Returns an endpoint array or throws.
* $endpoint = EndpointProvider::resolve($provider, [
* 'service' => 'ec2',
* 'region' => 'us-west-2'
* ]);
*
* You can compose multiple providers into a single provider using
* {@see Aws\or_chain}. This function accepts providers as arguments and
* returns a new function that will invoke each provider until a non-null value
* is returned.
*
* $a = function (array $args) {
* if ($args['region'] === 'my-test-region') {
* return ['endpoint' => 'http://localhost:123/api'];
* }
* };
* $b = EndpointProvider::defaultProvider();
* $c = \Aws\or_chain($a, $b);
* $config = ['service' => 'ec2', 'region' => 'my-test-region'];
* $res = $c($config); // $a handles this.
* $config['region'] = 'us-west-2';
* $res = $c($config); // $b handles this.
*/
class EndpointProvider
{
/**
* Resolves and endpoint provider and ensures a non-null return value.
*
* @param callable $provider Provider function to invoke.
* @param array $args Endpoint arguments to pass to the provider.
*
* @return array
* @throws UnresolvedEndpointException
*/
public static function resolve(callable $provider, array $args = [])
{
$result = $provider($args);
if (is_array($result)) {
return $result;
}
throw new UnresolvedEndpointException(
'Unable to resolve an endpoint using the provider arguments: '
. json_encode($args) . '. Note: you can provide an "endpoint" '
. 'option to a client constructor to bypass invoking an endpoint '
. 'provider.');
}
/**
* Creates and returns the default SDK endpoint provider.
*
* @deprecated Use an instance of \Aws\Endpoint\Partition instead.
*
* @return callable
*/
public static function defaultProvider()
{
return PartitionEndpointProvider::defaultProvider();
}
/**
* Creates and returns an endpoint provider that uses patterns from an
* array.
*
* @param array $patterns Endpoint patterns
*
* @return callable
*/
public static function patterns(array $patterns)
{
return new PatternEndpointProvider($patterns);
}
}

View File

@@ -0,0 +1,322 @@
<?php
namespace Aws\Endpoint;
use ArrayAccess;
use Aws\HasDataTrait;
use Aws\Sts\RegionalEndpoints\ConfigurationProvider;
use Aws\S3\RegionalEndpoint\ConfigurationProvider as S3ConfigurationProvider;
use InvalidArgumentException as Iae;
/**
* Default implementation of an AWS partition.
*/
final class Partition implements ArrayAccess, PartitionInterface
{
use HasDataTrait;
private $stsLegacyGlobalRegions = [
'ap-northeast-1',
'ap-south-1',
'ap-southeast-1',
'ap-southeast-2',
'aws-global',
'ca-central-1',
'eu-central-1',
'eu-north-1',
'eu-west-1',
'eu-west-2',
'eu-west-3',
'sa-east-1',
'us-east-1',
'us-east-2',
'us-west-1',
'us-west-2',
];
/**
* The partition constructor accepts the following options:
*
* - `partition`: (string, required) The partition name as specified in an
* ARN (e.g., `aws`)
* - `partitionName`: (string) The human readable name of the partition
* (e.g., "AWS Standard")
* - `dnsSuffix`: (string, required) The DNS suffix of the partition. This
* value is used to determine how endpoints in the partition are resolved.
* - `regionRegex`: (string) A PCRE regular expression that specifies the
* pattern that region names in the endpoint adhere to.
* - `regions`: (array, required) A map of the regions in the partition.
* Each key is the region as present in a hostname (e.g., `us-east-1`),
* and each value is a structure containing region information.
* - `defaults`: (array) A map of default key value pairs to apply to each
* endpoint of the partition. Any value in an `endpoint` definition will
* supersede any values specified in `defaults`.
* - `services`: (array, required) A map of service endpoint prefix name
* (the value found in a hostname) to information about the service.
*
* @param array $definition
*
* @throws Iae if any required options are missing
*/
public function __construct(array $definition)
{
foreach (['partition', 'regions', 'services', 'dnsSuffix'] as $key) {
if (!isset($definition[$key])) {
throw new Iae("Partition missing required $key field");
}
}
$this->data = $definition;
}
public function getName()
{
return $this->data['partition'];
}
/**
* @internal
* @return mixed
*/
public function getDnsSuffix()
{
return $this->data['dnsSuffix'];
}
public function isRegionMatch($region, $service)
{
if (isset($this->data['regions'][$region])
|| isset($this->data['services'][$service]['endpoints'][$region])
) {
return true;
}
if (isset($this->data['regionRegex'])) {
return (bool) preg_match(
"@{$this->data['regionRegex']}@",
$region
);
}
return false;
}
public function getAvailableEndpoints(
$service,
$allowNonRegionalEndpoints = false
) {
if ($this->isServicePartitionGlobal($service)) {
return [$this->getPartitionEndpoint($service)];
}
if (isset($this->data['services'][$service]['endpoints'])) {
$serviceRegions = array_keys(
$this->data['services'][$service]['endpoints']
);
return $allowNonRegionalEndpoints
? $serviceRegions
: array_intersect($serviceRegions, array_keys(
$this->data['regions']
));
}
return [];
}
public function __invoke(array $args = [])
{
$service = isset($args['service']) ? $args['service'] : '';
$region = isset($args['region']) ? $args['region'] : '';
$scheme = isset($args['scheme']) ? $args['scheme'] : 'https';
$options = isset($args['options']) ? $args['options'] : [];
$data = $this->getEndpointData($service, $region, $options);
$variant = $this->getVariant($options, $data);
if (isset($variant['hostname'])) {
$template = $variant['hostname'];
} else {
$template = isset($data['hostname']) ? $data['hostname'] : '';
}
$dnsSuffix = isset($variant['dnsSuffix'])
? $variant['dnsSuffix']
: $this->data['dnsSuffix'];
return [
'endpoint' => "{$scheme}://" . $this->formatEndpoint(
$template,
$service,
$region,
$dnsSuffix
),
'signatureVersion' => $this->getSignatureVersion($data),
'signingRegion' => isset($data['credentialScope']['region'])
? $data['credentialScope']['region']
: $region,
'signingName' => isset($data['credentialScope']['service'])
? $data['credentialScope']['service']
: $service,
];
}
private function getEndpointData($service, $region, $options)
{
$defaultRegion = $this->resolveRegion($service, $region, $options);
$data = isset($this->data['services'][$service]['endpoints'][$defaultRegion])
? $this->data['services'][$service]['endpoints'][$defaultRegion]
: [];
$data += isset($this->data['services'][$service]['defaults'])
? $this->data['services'][$service]['defaults']
: [];
$data += isset($this->data['defaults'])
? $this->data['defaults']
: [];
return $data;
}
private function getSignatureVersion(array $data)
{
static $supportedBySdk = [
's3v4',
'v4',
'anonymous',
];
$possibilities = array_intersect(
$supportedBySdk,
isset($data['signatureVersions'])
? $data['signatureVersions']
: ['v4']
);
return array_shift($possibilities);
}
private function resolveRegion($service, $region, $options)
{
if (isset($this->data['services'][$service]['endpoints'][$region])
&& $this->isFipsEndpointUsed($region)
) {
return $region;
}
if ($this->isServicePartitionGlobal($service)
|| $this->isStsLegacyEndpointUsed($service, $region, $options)
|| $this->isS3LegacyEndpointUsed($service, $region, $options)
) {
return $this->getPartitionEndpoint($service);
}
return $region;
}
private function isServicePartitionGlobal($service)
{
return isset($this->data['services'][$service]['isRegionalized'])
&& false === $this->data['services'][$service]['isRegionalized']
&& isset($this->data['services'][$service]['partitionEndpoint']);
}
/**
* STS legacy endpoints used for valid regions unless option is explicitly
* set to 'regional'
*
* @param string $service
* @param string $region
* @param array $options
* @return bool
*/
private function isStsLegacyEndpointUsed($service, $region, $options)
{
return $service === 'sts'
&& in_array($region, $this->stsLegacyGlobalRegions)
&& (empty($options['sts_regional_endpoints'])
|| ConfigurationProvider::unwrap(
$options['sts_regional_endpoints']
)->getEndpointsType() !== 'regional'
);
}
/**
* S3 legacy us-east-1 endpoint used for valid regions unless option is explicitly
* set to 'regional'
*
* @param string $service
* @param string $region
* @param array $options
* @return bool
*/
private function isS3LegacyEndpointUsed($service, $region, $options)
{
return $service === 's3'
&& $region === 'us-east-1'
&& (empty($options['s3_us_east_1_regional_endpoint'])
|| S3ConfigurationProvider::unwrap(
$options['s3_us_east_1_regional_endpoint']
)->getEndpointsType() !== 'regional'
);
}
private function getPartitionEndpoint($service)
{
return $this->data['services'][$service]['partitionEndpoint'];
}
private function formatEndpoint($template, $service, $region, $dnsSuffix)
{
return strtr($template, [
'{service}' => $service,
'{region}' => $region,
'{dnsSuffix}' => $dnsSuffix,
]);
}
/**
* @param $region
* @return bool
*/
private function isFipsEndpointUsed($region)
{
return strpos($region, "fips") !== false;
}
/**
* @param array $options
* @param array $data
* @return array
*/
private function getVariant(array $options, array $data)
{
$variantTags = [];
if (isset($options['use_fips_endpoint'])) {
$useFips = $options['use_fips_endpoint'];
if (is_bool($useFips)) {
$useFips && $variantTags[] = 'fips';
} elseif ($useFips->isUseFipsEndpoint()) {
$variantTags[] = 'fips';
}
}
if (isset($options['use_dual_stack_endpoint'])) {
$useDualStack = $options['use_dual_stack_endpoint'];
if (is_bool($useDualStack)) {
$useDualStack && $variantTags[] = 'dualstack';
} elseif ($useDualStack->isUseDualStackEndpoint()) {
$variantTags[] = 'dualstack';
}
}
if (!empty($variantTags)) {
if (isset($data['variants'])) {
foreach ($data['variants'] as $variant) {
if (array_count_values($variant['tags']) == array_count_values($variantTags)) {
return $variant;
}
}
}
if (isset($this->data['defaults']['variants'])) {
foreach ($this->data['defaults']['variants'] as $variant) {
if (array_count_values($variant['tags']) == array_count_values($variantTags)) {
return $variant;
}
}
}
}
}
}

View File

@@ -0,0 +1,130 @@
<?php
namespace Aws\Endpoint;
use JmesPath\Env;
class PartitionEndpointProvider
{
/** @var Partition[] */
private $partitions;
/** @var string */
private $defaultPartition;
/** @var array */
private $options;
/**
* The 'options' parameter accepts the following arguments:
*
* - sts_regional_endpoints: For STS legacy regions, set to 'regional' to
* use regional endpoints, 'legacy' to use the legacy global endpoint.
* Defaults to 'legacy'.
* - s3_us_east_1_regional_endpoint: For S3 us-east-1 region, set to 'regional'
* to use the regional endpoint, 'legacy' to use the legacy global endpoint.
* Defaults to 'legacy'.
*
* @param array $partitions
* @param string $defaultPartition
* @param array $options
*/
public function __construct(
array $partitions,
$defaultPartition = 'aws',
$options = []
) {
$this->partitions = array_map(function (array $definition) {
return new Partition($definition);
}, array_values($partitions));
$this->defaultPartition = $defaultPartition;
$this->options = $options;
}
public function __invoke(array $args = [])
{
$partition = $this->getPartition(
isset($args['region']) ? $args['region'] : '',
isset($args['service']) ? $args['service'] : ''
);
$args['options'] = $this->options;
return $partition($args);
}
/**
* Returns the partition containing the provided region or the default
* partition if no match is found.
*
* @param string $region
* @param string $service
*
* @return Partition
*/
public function getPartition($region, $service)
{
foreach ($this->partitions as $partition) {
if ($partition->isRegionMatch($region, $service)) {
return $partition;
}
}
return $this->getPartitionByName($this->defaultPartition);
}
/**
* Returns the partition with the provided name or null if no partition with
* the provided name can be found.
*
* @param string $name
*
* @return Partition|null
*/
public function getPartitionByName($name)
{
foreach ($this->partitions as $partition) {
if ($name === $partition->getName()) {
return $partition;
}
}
}
/**
* Creates and returns the default SDK partition provider.
*
* @param array $options
* @return PartitionEndpointProvider
*/
public static function defaultProvider($options = [])
{
$data = \Aws\load_compiled_json(__DIR__ . '/../data/endpoints.json');
$prefixData = \Aws\load_compiled_json(__DIR__ . '/../data/endpoints_prefix_history.json');
$mergedData = self::mergePrefixData($data, $prefixData);
return new self($mergedData['partitions'], 'aws', $options);
}
/**
* Copy endpoint data for other prefixes used by a given service
*
* @param $data
* @param $prefixData
* @return array
*/
public static function mergePrefixData($data, $prefixData)
{
$prefixGroups = $prefixData['prefix-groups'];
foreach ($data["partitions"] as $index => $partition) {
foreach ($prefixGroups as $current => $old) {
$serviceData = Env::search("services.\"{$current}\"", $partition);
if (!empty($serviceData)) {
foreach ($old as $prefix) {
if (empty(Env::search("services.\"{$prefix}\"", $partition))) {
$data["partitions"][$index]["services"][$prefix] = $serviceData;
}
}
}
}
}
return $data;
}
}

View File

@@ -0,0 +1,56 @@
<?php
namespace Aws\Endpoint;
/**
* Represents a section of the AWS cloud.
*/
interface PartitionInterface
{
/**
* Returns the partition's short name, e.g., 'aws,' 'aws-cn,' or
* 'aws-us-gov.'
*
* @return string
*/
public function getName();
/**
* Determine if this partition contains the provided region. Include the
* name of the service to inspect non-regional endpoints
*
* @param string $region
* @param string $service
*
* @return bool
*/
public function isRegionMatch($region, $service);
/**
* Return the endpoints supported by a given service.
*
* @param string $service Identifier of the service
* whose endpoints should be
* listed (e.g., 's3' or 'ses')
* @param bool $allowNonRegionalEndpoints Set to `true` to include
* endpoints that are not AWS
* regions (e.g., 'local' for
* DynamoDB or
* 'fips-us-gov-west-1' for S3)
*
* @return string[]
*/
public function getAvailableEndpoints(
$service,
$allowNonRegionalEndpoints = false
);
/**
* A partition must be invokable as an endpoint provider.
*
* @see EndpointProvider
*
* @param array $args
* @return array
*/
public function __invoke(array $args = []);
}

View File

@@ -0,0 +1,51 @@
<?php
namespace Aws\Endpoint;
/**
* Provides endpoints based on an endpoint pattern configuration array.
*/
class PatternEndpointProvider
{
/** @var array */
private $patterns;
/**
* @param array $patterns Hash of endpoint patterns mapping to endpoint
* configurations.
*/
public function __construct(array $patterns)
{
$this->patterns = $patterns;
}
public function __invoke(array $args = [])
{
$service = isset($args['service']) ? $args['service'] : '';
$region = isset($args['region']) ? $args['region'] : '';
$keys = ["{$region}/{$service}", "{$region}/*", "*/{$service}", "*/*"];
foreach ($keys as $key) {
if (isset($this->patterns[$key])) {
return $this->expand(
$this->patterns[$key],
isset($args['scheme']) ? $args['scheme'] : 'https',
$service,
$region
);
}
}
return null;
}
private function expand(array $config, $scheme, $service, $region)
{
$config['endpoint'] = $scheme . '://'
. strtr($config['endpoint'], [
'{service}' => $service,
'{region}' => $region
]);
return $config;
}
}

View File

@@ -0,0 +1,41 @@
<?php
namespace Aws\Endpoint\UseDualstackEndpoint;
use Aws;
use Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException;
class Configuration implements ConfigurationInterface
{
private $useDualstackEndpoint;
public function __construct($useDualstackEndpoint, $region)
{
$this->useDualstackEndpoint = Aws\boolean_value($useDualstackEndpoint);
if (is_null($this->useDualstackEndpoint)) {
throw new ConfigurationException("'use_dual_stack_endpoint' config option"
. " must be a boolean value.");
}
if ($this->useDualstackEndpoint == true
&& (strpos($region, "iso-") !== false || strpos($region, "-iso") !== false)
) {
throw new ConfigurationException("Dual-stack is not supported in ISO regions"); }
}
/**
* {@inheritdoc}
*/
public function isUseDualstackEndpoint()
{
return $this->useDualstackEndpoint;
}
/**
* {@inheritdoc}
*/
public function toArray()
{
return [
'use_dual_stack_endpoint' => $this->isUseDualstackEndpoint(),
];
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace Aws\Endpoint\UseDualstackEndpoint;
interface ConfigurationInterface
{
/**
* Returns whether or not to use a DUALSTACK endpoint
*
* @return bool
*/
public function isUseDualstackEndpoint();
/**
* Returns the configuration as an associative array
*
* @return array
*/
public function toArray();
}

View File

@@ -0,0 +1,173 @@
<?php
namespace Aws\Endpoint\UseDualstackEndpoint;
use Aws\AbstractConfigurationProvider;
use Aws\CacheInterface;
use Aws\ConfigurationProviderInterface;
use Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException;
use GuzzleHttp\Promise;
/**
* A configuration provider is a function that returns a promise that is
* fulfilled with a {@see \Aws\Endpoint\UseDualstackEndpoint\onfigurationInterface}
* or rejected with an {@see \Aws\Endpoint\UseDualstackEndpoint\ConfigurationException}.
*
* <code>
* use Aws\Endpoint\UseDualstackEndpoint\ConfigurationProvider;
* $provider = ConfigurationProvider::defaultProvider();
* // Returns a ConfigurationInterface or throws.
* $config = $provider()->wait();
* </code>
*
* Configuration providers can be composed to create configuration using
* conditional logic that can create different configurations in different
* environments. You can compose multiple providers into a single provider using
* {@see Aws\Endpoint\UseDualstackEndpoint\ConfigurationProvider::chain}. This function
* accepts providers as variadic arguments and returns a new function that will
* invoke each provider until a successful configuration is returned.
*
* <code>
* // First try an INI file at this location.
* $a = ConfigurationProvider::ini(null, '/path/to/file.ini');
* // Then try an INI file at this location.
* $b = ConfigurationProvider::ini(null, '/path/to/other-file.ini');
* // Then try loading from environment variables.
* $c = ConfigurationProvider::env();
* // Combine the three providers together.
* $composed = ConfigurationProvider::chain($a, $b, $c);
* // Returns a promise that is fulfilled with a configuration or throws.
* $promise = $composed();
* // Wait on the configuration to resolve.
* $config = $promise->wait();
* </code>
*/
class ConfigurationProvider extends AbstractConfigurationProvider
implements ConfigurationProviderInterface
{
const ENV_USE_DUAL_STACK_ENDPOINT = 'AWS_USE_DUALSTACK_ENDPOINT';
const INI_USE_DUAL_STACK_ENDPOINT = 'use_dualstack_endpoint';
public static $cacheKey = 'aws_cached_use_dualstack_endpoint_config';
protected static $interfaceClass = ConfigurationInterface::class;
protected static $exceptionClass = ConfigurationException::class;
/**
* Create a default config provider that first checks for environment
* variables, then checks for a specified profile in the environment-defined
* config file location (env variable is 'AWS_CONFIG_FILE', file location
* defaults to ~/.aws/config), then checks for the "default" profile in the
* environment-defined config file location, and failing those uses a default
* fallback set of configuration options.
*
* This provider is automatically wrapped in a memoize function that caches
* previously provided config options.
*
* @param array $config
*
* @return callable
*/
public static function defaultProvider(array $config = [])
{
$region = $config['region'];
$configProviders = [self::env($region)];
if (
!isset($config['use_aws_shared_config_files'])
|| $config['use_aws_shared_config_files'] != false
) {
$configProviders[] = self::ini($region);
}
$configProviders[] = self::fallback($region);
$memo = self::memoize(
call_user_func_array([ConfigurationProvider::class, 'chain'], $configProviders)
);
if (isset($config['use_dual_stack_endpoint'])
&& $config['use_dual_stack_endpoint'] instanceof CacheInterface
) {
return self::cache($memo, $config['use_dual_stack_endpoint'], self::$cacheKey);
}
return $memo;
}
/**
* Provider that creates config from environment variables.
*
* @return callable
*/
public static function env($region)
{
return function () use ($region) {
// Use config from environment variables, if available
$useDualstackEndpoint = getenv(self::ENV_USE_DUAL_STACK_ENDPOINT);
if (!empty($useDualstackEndpoint)) {
return Promise\Create::promiseFor(
new Configuration($useDualstackEndpoint, $region)
);
}
return self::reject('Could not find environment variable config'
. ' in ' . self::ENV_USE_DUAL_STACK_ENDPOINT);
};
}
/**
* Config provider that creates config using a config file whose location
* is specified by an environment variable 'AWS_CONFIG_FILE', defaulting to
* ~/.aws/config if not specified
*
* @param string|null $profile Profile to use. If not specified will use
* the "default" profile.
* @param string|null $filename If provided, uses a custom filename rather
* than looking in the default directory.
*
* @return callable
*/
public static function ini($region, $profile = null, $filename = null)
{
$filename = $filename ?: (self::getDefaultConfigFilename());
$profile = $profile ?: (getenv(self::ENV_PROFILE) ?: 'default');
return function () use ($region, $profile, $filename) {
if (!@is_readable($filename)) {
return self::reject("Cannot read configuration from $filename");
}
// Use INI_SCANNER_NORMAL instead of INI_SCANNER_TYPED for PHP 5.5 compatibility
$data = \Aws\parse_ini_file($filename, true, INI_SCANNER_NORMAL);
if ($data === false) {
return self::reject("Invalid config file: $filename");
}
if (!isset($data[$profile])) {
return self::reject("'$profile' not found in config file");
}
if (!isset($data[$profile][self::INI_USE_DUAL_STACK_ENDPOINT])) {
return self::reject("Required use dualstack endpoint config values
not present in INI profile '{$profile}' ({$filename})");
}
// INI_SCANNER_NORMAL parses false-y values as an empty string
if ($data[$profile][self::INI_USE_DUAL_STACK_ENDPOINT] === "") {
$data[$profile][self::INI_USE_DUAL_STACK_ENDPOINT] = false;
}
return Promise\Create::promiseFor(
new Configuration($data[$profile][self::INI_USE_DUAL_STACK_ENDPOINT], $region)
);
};
}
/**
* Fallback config options when other sources are not set.
*
* @return callable
*/
public static function fallback($region)
{
return function () use ($region) {
return Promise\Create::promiseFor(new Configuration(false, $region));
};
}
}

View File

@@ -0,0 +1,14 @@
<?php
namespace Aws\Endpoint\UseDualstackEndpoint\Exception;
use Aws\HasMonitoringEventsTrait;
use Aws\MonitoringEventsInterface;
/**
* Represents an error interacting with configuration for useDualstackRegion
*/
class ConfigurationException extends \RuntimeException implements
MonitoringEventsInterface
{
use HasMonitoringEventsTrait;
}

View File

@@ -0,0 +1,37 @@
<?php
namespace Aws\Endpoint\UseFipsEndpoint;
use Aws;
use Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException;
class Configuration implements ConfigurationInterface
{
private $useFipsEndpoint;
public function __construct($useFipsEndpoint)
{
$this->useFipsEndpoint = Aws\boolean_value($useFipsEndpoint);
if (is_null($this->useFipsEndpoint)) {
throw new ConfigurationException("'use_fips_endpoint' config option"
. " must be a boolean value.");
}
}
/**
* {@inheritdoc}
*/
public function isUseFipsEndpoint()
{
return $this->useFipsEndpoint;
}
/**
* {@inheritdoc}
*/
public function toArray()
{
return [
'use_fips_endpoint' => $this->isUseFipsEndpoint(),
];
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace Aws\Endpoint\UseFipsEndpoint;
interface ConfigurationInterface
{
/**
* Returns whether or not to use a FIPS endpoint
*
* @return bool
*/
public function isUseFipsEndpoint();
/**
* Returns the configuration as an associative array
*
* @return array
*/
public function toArray();
}

View File

@@ -0,0 +1,179 @@
<?php
namespace Aws\Endpoint\UseFipsEndpoint;
use Aws\AbstractConfigurationProvider;
use Aws\CacheInterface;
use Aws\ConfigurationProviderInterface;
use Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException;
use GuzzleHttp\Promise;
/**
* A configuration provider is a function that returns a promise that is
* fulfilled with a {@see \Aws\Endpoint\UseFipsEndpoint\onfigurationInterface}
* or rejected with an {@see \Aws\Endpoint\UseFipsEndpoint\ConfigurationException}.
*
* <code>
* use Aws\Endpoint\UseFipsEndpoint\ConfigurationProvider;
* $provider = ConfigurationProvider::defaultProvider();
* // Returns a ConfigurationInterface or throws.
* $config = $provider()->wait();
* </code>
*
* Configuration providers can be composed to create configuration using
* conditional logic that can create different configurations in different
* environments. You can compose multiple providers into a single provider using
* {@see Aws\Endpoint\UseFipsEndpoint\ConfigurationProvider::chain}. This function
* accepts providers as variadic arguments and returns a new function that will
* invoke each provider until a successful configuration is returned.
*
* <code>
* // First try an INI file at this location.
* $a = ConfigurationProvider::ini(null, '/path/to/file.ini');
* // Then try an INI file at this location.
* $b = ConfigurationProvider::ini(null, '/path/to/other-file.ini');
* // Then try loading from environment variables.
* $c = ConfigurationProvider::env();
* // Combine the three providers together.
* $composed = ConfigurationProvider::chain($a, $b, $c);
* // Returns a promise that is fulfilled with a configuration or throws.
* $promise = $composed();
* // Wait on the configuration to resolve.
* $config = $promise->wait();
* </code>
*/
class ConfigurationProvider extends AbstractConfigurationProvider
implements ConfigurationProviderInterface
{
const ENV_USE_FIPS_ENDPOINT = 'AWS_USE_FIPS_ENDPOINT';
const INI_USE_FIPS_ENDPOINT = 'use_fips_endpoint';
public static $cacheKey = 'aws_cached_use_fips_endpoint_config';
protected static $interfaceClass = ConfigurationInterface::class;
protected static $exceptionClass = ConfigurationException::class;
/**
* Create a default config provider that first checks for environment
* variables, then checks for a specified profile in the environment-defined
* config file location (env variable is 'AWS_CONFIG_FILE', file location
* defaults to ~/.aws/config), then checks for the "default" profile in the
* environment-defined config file location, and failing those uses a default
* fallback set of configuration options.
*
* This provider is automatically wrapped in a memoize function that caches
* previously provided config options.
*
* @param array $config
*
* @return callable
*/
public static function defaultProvider(array $config = [])
{
$configProviders = [self::env()];
if (
!isset($config['use_aws_shared_config_files'])
|| $config['use_aws_shared_config_files'] != false
) {
$configProviders[] = self::ini();
}
$configProviders[] = self::fallback($config['region']);
$memo = self::memoize(
call_user_func_array([ConfigurationProvider::class, 'chain'], $configProviders)
);
if (isset($config['use_fips_endpoint'])
&& $config['use_fips_endpoint'] instanceof CacheInterface
) {
return self::cache($memo, $config['use_fips_endpoint'], self::$cacheKey);
}
return $memo;
}
/**
* Provider that creates config from environment variables.
*
* @return callable
*/
public static function env()
{
return function () {
// Use config from environment variables, if available
$useFipsEndpoint = getenv(self::ENV_USE_FIPS_ENDPOINT);
if (!empty($useFipsEndpoint)) {
return Promise\Create::promiseFor(
new Configuration($useFipsEndpoint)
);
}
return self::reject('Could not find environment variable config'
. ' in ' . self::ENV_USE_FIPS_ENDPOINT);
};
}
/**
* Config provider that creates config using a config file whose location
* is specified by an environment variable 'AWS_CONFIG_FILE', defaulting to
* ~/.aws/config if not specified
*
* @param string|null $profile Profile to use. If not specified will use
* the "default" profile.
* @param string|null $filename If provided, uses a custom filename rather
* than looking in the default directory.
*
* @return callable
*/
public static function ini($profile = null, $filename = null)
{
$filename = $filename ?: (self::getDefaultConfigFilename());
$profile = $profile ?: (getenv(self::ENV_PROFILE) ?: 'default');
return function () use ($profile, $filename) {
if (!@is_readable($filename)) {
return self::reject("Cannot read configuration from $filename");
}
// Use INI_SCANNER_NORMAL instead of INI_SCANNER_TYPED for PHP 5.5 compatibility
$data = \Aws\parse_ini_file($filename, true, INI_SCANNER_NORMAL);
if ($data === false) {
return self::reject("Invalid config file: $filename");
}
if (!isset($data[$profile])) {
return self::reject("'$profile' not found in config file");
}
if (!isset($data[$profile][self::INI_USE_FIPS_ENDPOINT])) {
return self::reject("Required use fips endpoint config values
not present in INI profile '{$profile}' ({$filename})");
}
// INI_SCANNER_NORMAL parses false-y values as an empty string
if ($data[$profile][self::INI_USE_FIPS_ENDPOINT] === "") {
$data[$profile][self::INI_USE_FIPS_ENDPOINT] = false;
}
return Promise\Create::promiseFor(
new Configuration($data[$profile][self::INI_USE_FIPS_ENDPOINT])
);
};
}
/**
* Fallback config options when other sources are not set.
*
* @return callable
*/
public static function fallback($region)
{
return function () use ($region) {
$isFipsPseudoRegion = strpos($region, 'fips-') !== false
|| strpos($region, '-fips') !== false;
if ($isFipsPseudoRegion){
$configuration = new Configuration(true);
} else {
$configuration = new Configuration(false);
}
return Promise\Create::promiseFor($configuration);
};
}
}

View File

@@ -0,0 +1,14 @@
<?php
namespace Aws\Endpoint\UseFipsEndpoint\Exception;
use Aws\HasMonitoringEventsTrait;
use Aws\MonitoringEventsInterface;
/**
* Represents an error interacting with configuration for useFipsRegion
*/
class ConfigurationException extends \RuntimeException implements
MonitoringEventsInterface
{
use HasMonitoringEventsTrait;
}