<?php
namespace Aws\S3\Crypto;

use Aws\Crypto\DecryptionTrait;
use Aws\HashingStream;
use Aws\PhpHash;
use Aws\Crypto\AbstractCryptoClient;
use Aws\Crypto\EncryptionTrait;
use Aws\Crypto\MetadataEnvelope;
use Aws\Crypto\MaterialsProvider;
use Aws\Crypto\Cipher\CipherBuilderTrait;
use Aws\S3\S3Client;
use GuzzleHttp\Promise;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7;

/**
 * Provides a wrapper for an S3Client that supplies functionality to encrypt
 * data on putObject[Async] calls and decrypt data on getObject[Async] calls.
 *
 * Legacy implementation using older encryption workflow.
 *
 * AWS strongly recommends the upgrade to the S3EncryptionClientV2 (over the
 * S3EncryptionClient), as it offers updated data security best practices to our
 * customers who upgrade. S3EncryptionClientV2 contains breaking changes, so this
 * will require planning by engineering teams to migrate. New workflows should
 * just start with S3EncryptionClientV2.
 *
 * @deprecated
 */
class S3EncryptionClient extends AbstractCryptoClient
{
    use CipherBuilderTrait;
    use CryptoParamsTrait;
    use DecryptionTrait;
    use EncryptionTrait;
    use UserAgentTrait;

    const CRYPTO_VERSION = '1n';

    private $client;
    private $instructionFileSuffix;

    /**
     * @param S3Client $client The S3Client to be used for true uploading and
     *                         retrieving objects from S3 when using the
     *                         encryption client.
     * @param string|null $instructionFileSuffix Suffix for a client wide
     *                                           default when using instruction
     *                                           files for metadata storage.
     */
    public function __construct(
        S3Client $client,
        $instructionFileSuffix = null
    ) {
        $this->appendUserAgent($client, 'feat/s3-encrypt/' . self::CRYPTO_VERSION);
        $this->client = $client;
        $this->instructionFileSuffix = $instructionFileSuffix;
    }

    private static function getDefaultStrategy()
    {
        return new HeadersMetadataStrategy();
    }

    /**
     * Encrypts the data in the 'Body' field of $args and promises to upload it
     * to the specified location on S3.
     *
     * @param array $args Arguments for encrypting an object and uploading it
     *                    to S3 via PutObject.
     *
     * The required configuration arguments are as follows:
     *
     * - @MaterialsProvider: (MaterialsProvider) Provides Cek, Iv, and Cek
     *   encrypting/decrypting for encryption metadata.
     * - @CipherOptions: (array) Cipher options for encrypting data. Only the
     *   Cipher option is required. Accepts the following:
     *       - Cipher: (string) cbc|gcm
     *            See also: AbstractCryptoClient::$supportedCiphers. Note that
     *            cbc is deprecated and gcm should be used when possible.
     *       - KeySize: (int) 128|192|256
     *            See also: MaterialsProvider::$supportedKeySizes
     *       - Aad: (string) Additional authentication data. This option is
     *            passed directly to OpenSSL when using gcm. It is ignored when
     *            using cbc. Note if you pass in Aad for gcm encryption, the
     *            PHP SDK will be able to decrypt the resulting object, but other
     *            AWS SDKs may not be able to do so.
     *
     * The optional configuration arguments are as follows:
     *
     * - @MetadataStrategy: (MetadataStrategy|string|null) Strategy for storing
     *   MetadataEnvelope information. Defaults to using a
     *   HeadersMetadataStrategy. Can either be a class implementing
     *   MetadataStrategy, a class name of a predefined strategy, or empty/null
     *   to default.
     * - @InstructionFileSuffix: (string|null) Suffix used when writing to an
     *   instruction file if using an InstructionFileMetadataHandler.
     *
     * @return PromiseInterface
     *
     * @throws \InvalidArgumentException Thrown when arguments above are not
     *                                   passed or are passed incorrectly.
     */
    public function putObjectAsync(array $args)
    {
        $provider = $this->getMaterialsProvider($args);
        unset($args['@MaterialsProvider']);

        $instructionFileSuffix = $this->getInstructionFileSuffix($args);
        unset($args['@InstructionFileSuffix']);

        $strategy = $this->getMetadataStrategy($args, $instructionFileSuffix);
        unset($args['@MetadataStrategy']);

        $envelope = new MetadataEnvelope();

        return Promise\Create::promiseFor($this->encrypt(
            Psr7\Utils::streamFor($args['Body']),
            $args['@CipherOptions'] ?: [],
            $provider,
            $envelope
        ))->then(
            function ($encryptedBodyStream) use ($args) {
                $hash = new PhpHash('sha256');
                $hashingEncryptedBodyStream = new HashingStream(
                    $encryptedBodyStream,
                    $hash,
                    self::getContentShaDecorator($args)
                );
                return [$hashingEncryptedBodyStream, $args];
            }
        )->then(
            function ($putObjectContents) use ($strategy, $envelope) {
                list($bodyStream, $args) = $putObjectContents;
                if ($strategy === null) {
                    $strategy = self::getDefaultStrategy();
                }

                $updatedArgs = $strategy->save($envelope, $args);
                $updatedArgs['Body'] = $bodyStream;
                return $updatedArgs;
            }
        )->then(
            function ($args) {
                unset($args['@CipherOptions']);
                return $this->client->putObjectAsync($args);
            }
        );
    }

    private static function getContentShaDecorator(&$args)
    {
        return function ($hash) use (&$args) {
            $args['ContentSHA256'] = bin2hex($hash);
        };
    }

    /**
     * Encrypts the data in the 'Body' field of $args and uploads it to the
     * specified location on S3.
     *
     * @param array $args Arguments for encrypting an object and uploading it
     *                    to S3 via PutObject.
     *
     * The required configuration arguments are as follows:
     *
     * - @MaterialsProvider: (MaterialsProvider) Provides Cek, Iv, and Cek
     *   encrypting/decrypting for encryption metadata.
     * - @CipherOptions: (array) Cipher options for encrypting data. A Cipher
     *   is required. Accepts the following options:
     *       - Cipher: (string) cbc|gcm
     *            See also: AbstractCryptoClient::$supportedCiphers. Note that
     *            cbc is deprecated and gcm should be used when possible.
     *       - KeySize: (int) 128|192|256
     *            See also: MaterialsProvider::$supportedKeySizes
     *       - Aad: (string) Additional authentication data. This option is
     *            passed directly to OpenSSL when using gcm. It is ignored when
     *            using cbc. Note if you pass in Aad for gcm encryption, the
     *            PHP SDK will be able to decrypt the resulting object, but other
     *            AWS SDKs may not be able to do so.
     *
     * The optional configuration arguments are as follows:
     *
     * - @MetadataStrategy: (MetadataStrategy|string|null) Strategy for storing
     *   MetadataEnvelope information. Defaults to using a
     *   HeadersMetadataStrategy. Can either be a class implementing
     *   MetadataStrategy, a class name of a predefined strategy, or empty/null
     *   to default.
     * - @InstructionFileSuffix: (string|null) Suffix used when writing to an
     *   instruction file if an using an InstructionFileMetadataHandler was
     *   determined.
     *
     * @return \Aws\Result PutObject call result with the details of uploading
     *                     the encrypted file.
     *
     * @throws \InvalidArgumentException Thrown when arguments above are not
     *                                   passed or are passed incorrectly.
     */
    public function putObject(array $args)
    {
        return $this->putObjectAsync($args)->wait();
    }

    /**
     * Promises to retrieve an object from S3 and decrypt the data in the
     * 'Body' field.
     *
     * @param array $args Arguments for retrieving an object from S3 via
     *                    GetObject and decrypting it.
     *
     * The required configuration argument is as follows:
     *
     * - @MaterialsProvider: (MaterialsProvider) Provides Cek, Iv, and Cek
     *   encrypting/decrypting for decryption metadata. May have data loaded
     *   from the MetadataEnvelope upon decryption.
     *
     * The optional configuration arguments are as follows:
     *
     * - SaveAs: (string) The path to a file on disk to save the decrypted
     *   object data. This will be handled by file_put_contents instead of the
     *   Guzzle sink.
     *
     * - @MetadataStrategy: (MetadataStrategy|string|null) Strategy for reading
     *   MetadataEnvelope information. Defaults to determining based on object
     *   response headers. Can either be a class implementing MetadataStrategy,
     *   a class name of a predefined strategy, or empty/null to default.
     * - @InstructionFileSuffix: (string) Suffix used when looking for an
     *   instruction file if an InstructionFileMetadataHandler is being used.
     * - @CipherOptions: (array) Cipher options for decrypting data. A Cipher
     *   is required. Accepts the following options:
     *       - Aad: (string) Additional authentication data. This option is
     *            passed directly to OpenSSL when using gcm. It is ignored when
     *            using cbc.
     *
     * @return PromiseInterface
     *
     * @throws \InvalidArgumentException Thrown when required arguments are not
     *                                   passed or are passed incorrectly.
     */
    public function getObjectAsync(array $args)
    {
        $provider = $this->getMaterialsProvider($args);
        unset($args['@MaterialsProvider']);

        $instructionFileSuffix = $this->getInstructionFileSuffix($args);
        unset($args['@InstructionFileSuffix']);

        $strategy = $this->getMetadataStrategy($args, $instructionFileSuffix);
        unset($args['@MetadataStrategy']);

        $saveAs = null;
        if (!empty($args['SaveAs'])) {
            $saveAs = $args['SaveAs'];
        }

        $promise = $this->client->getObjectAsync($args)
            ->then(
                function ($result) use (
                    $provider,
                    $instructionFileSuffix,
                    $strategy,
                    $args
                ) {
                    if ($strategy === null) {
                        $strategy = $this->determineGetObjectStrategy(
                            $result,
                            $instructionFileSuffix
                        );
                    }

                    $envelope = $strategy->load($args + [
                        'Metadata' => $result['Metadata']
                    ]);

                    $provider = $provider->fromDecryptionEnvelope($envelope);

                    $result['Body'] = $this->decrypt(
                        $result['Body'],
                        $provider,
                        $envelope,
                        isset($args['@CipherOptions'])
                            ? $args['@CipherOptions']
                            : []
                    );
                    return $result;
                }
            )->then(
                function ($result) use ($saveAs) {
                    if (!empty($saveAs)) {
                        file_put_contents(
                            $saveAs,
                            (string)$result['Body'],
                            LOCK_EX
                        );
                    }
                    return $result;
                }
            );

        return $promise;
    }

    /**
     * Retrieves an object from S3 and decrypts the data in the 'Body' field.
     *
     * @param array $args Arguments for retrieving an object from S3 via
     *                    GetObject and decrypting it.
     *
     * The required configuration argument is as follows:
     *
     * - @MaterialsProvider: (MaterialsProvider) Provides Cek, Iv, and Cek
     *   encrypting/decrypting for decryption metadata. May have data loaded
     *   from the MetadataEnvelope upon decryption.
     *
     * The optional configuration arguments are as follows:
     *
     * - SaveAs: (string) The path to a file on disk to save the decrypted
     *   object data. This will be handled by file_put_contents instead of the
     *   Guzzle sink.
     * - @InstructionFileSuffix: (string|null) Suffix used when looking for an
     *   instruction file if an InstructionFileMetadataHandler was detected.
     * - @CipherOptions: (array) Cipher options for encrypting data. A Cipher
     *   is required. Accepts the following options:
     *       - Aad: (string) Additional authentication data. This option is
     *            passed directly to OpenSSL when using gcm. It is ignored when
     *            using cbc.
     *
     * @return \Aws\Result GetObject call result with the 'Body' field
     *                     wrapped in a decryption stream with its metadata
     *                     information.
     *
     * @throws \InvalidArgumentException Thrown when arguments above are not
     *                                   passed or are passed incorrectly.
     */
    public function getObject(array $args)
    {
        return $this->getObjectAsync($args)->wait();
    }
}


<?php
namespace Aws\S3\Crypto;

use Aws\Crypto\DecryptionTraitV2;
use Aws\Exception\CryptoException;
use Aws\HashingStream;
use Aws\PhpHash;
use Aws\Crypto\AbstractCryptoClientV2;
use Aws\Crypto\EncryptionTraitV2;
use Aws\Crypto\MetadataEnvelope;
use Aws\Crypto\MaterialsProvider;
use Aws\Crypto\Cipher\CipherBuilderTrait;
use Aws\S3\S3Client;
use GuzzleHttp\Promise;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7;

/**
 * Provides a wrapper for an S3Client that supplies functionality to encrypt
 * data on putObject[Async] calls and decrypt data on getObject[Async] calls.
 *
 * AWS strongly recommends the upgrade to the S3EncryptionClientV2 (over the
 * S3EncryptionClient), as it offers updated data security best practices to our
 * customers who upgrade. S3EncryptionClientV2 contains breaking changes, so this
 * will require planning by engineering teams to migrate. New workflows should
 * just start with S3EncryptionClientV2.
 *
 * Note that for PHP versions of < 7.1, this class uses an AES-GCM polyfill
 * for encryption since there is no native PHP support. The performance for large
 * inputs will be a lot slower than for PHP 7.1+, so upgrading older PHP version
 * environments may be necessary to use this effectively.
 *
 * Example write path:
 *
 *
 * use Aws\Crypto\KmsMaterialsProviderV2;
 * use Aws\S3\Crypto\S3EncryptionClientV2;
 * use Aws\S3\S3Client;
 *
 * $encryptionClient = new S3EncryptionClientV2(
 *     new S3Client([
 *         'region' => 'us-west-2',
 *         'version' => 'latest'
 *     ])
 * );
 * $materialsProvider = new KmsMaterialsProviderV2(
 *     new KmsClient([
 *         'profile' => 'default',
 *         'region' => 'us-east-1',
 *         'version' => 'latest',
 *     ],
 *    'your-kms-key-id'
 * );
 *
 * $encryptionClient->putObject([
 *     '@MaterialsProvider' => $materialsProvider,
 *     '@CipherOptions' => [
 *         'Cipher' => 'gcm',
 *         'KeySize' => 256,
 *     ],
 *     '@KmsEncryptionContext' => ['foo' => 'bar'],
 *     'Bucket' => 'your-bucket',
 *     'Key' => 'your-key',
 *     'Body' => 'your-encrypted-data',
 * ]);
 *
 *
 * Example read call (using objects from previous example):
 *
 *
 * $encryptionClient->getObject([
 *     '@MaterialsProvider' => $materialsProvider,
 *     '@CipherOptions' => [
 *         'Cipher' => 'gcm',
 *         'KeySize' => 256,
 *     ],
 *     'Bucket' => 'your-bucket',
 *     'Key' => 'your-key',
 * ]);
 *
 */
class S3EncryptionClientV2 extends AbstractCryptoClientV2
{
    use CipherBuilderTrait;
    use CryptoParamsTraitV2;
    use DecryptionTraitV2;
    use EncryptionTraitV2;
    use UserAgentTrait;

    const CRYPTO_VERSION = '2.1';

    private $client;
    private $instructionFileSuffix;
    private $legacyWarningCount;

    /**
     * @param S3Client $client The S3Client to be used for true uploading and
     *                         retrieving objects from S3 when using the
     *                         encryption client.
     * @param string|null $instructionFileSuffix Suffix for a client wide
     *                                           default when using instruction
     *                                           files for metadata storage.
     */
    public function __construct(
        S3Client $client,
        $instructionFileSuffix = null
    ) {
        $this->appendUserAgent($client, 'feat/s3-encrypt/' . self::CRYPTO_VERSION);
        $this->client = $client;
        $this->instructionFileSuffix = $instructionFileSuffix;
        $this->legacyWarningCount = 0;
    }

    private static function getDefaultStrategy()
    {
        return new HeadersMetadataStrategy();
    }

    /**
     * Encrypts the data in the 'Body' field of $args and promises to upload it
     * to the specified location on S3.
     *
     * Note that for PHP versions of < 7.1, this operation uses an AES-GCM
     * polyfill for encryption since there is no native PHP support. The
     * performance for large inputs will be a lot slower than for PHP 7.1+, so
     * upgrading older PHP version environments may be necessary to use this
     * effectively.
     *
     * @param array $args Arguments for encrypting an object and uploading it
     *                    to S3 via PutObject.
     *
     * The required configuration arguments are as follows:
     *
     * - @MaterialsProvider: (MaterialsProviderV2) Provides Cek, Iv, and Cek
     *   encrypting/decrypting for encryption metadata.
     * - @CipherOptions: (array) Cipher options for encrypting data. Only the
     *   Cipher option is required. Accepts the following:
     *       - Cipher: (string) gcm
     *            See also: AbstractCryptoClientV2::$supportedCiphers
     *       - KeySize: (int) 128|256
     *            See also: MaterialsProvider::$supportedKeySizes
     *       - Aad: (string) Additional authentication data. This option is
     *            passed directly to OpenSSL when using gcm. Note if you pass in
     *            Aad, the PHP SDK will be able to decrypt the resulting object,
     *            but other AWS SDKs may not be able to do so.
     * - @KmsEncryptionContext: (array) Only required if using
     *   KmsMaterialsProviderV2. An associative array of key-value
     *   pairs to be added to the encryption context for KMS key encryption. An
     *   empty array may be passed if no additional context is desired.
     *
     * The optional configuration arguments are as follows:
     *
     * - @MetadataStrategy: (MetadataStrategy|string|null) Strategy for storing
     *   MetadataEnvelope information. Defaults to using a
     *   HeadersMetadataStrategy. Can either be a class implementing
     *   MetadataStrategy, a class name of a predefined strategy, or empty/null
     *   to default.
     * - @InstructionFileSuffix: (string|null) Suffix used when writing to an
     *   instruction file if using an InstructionFileMetadataHandler.
     *
     * @return PromiseInterface
     *
     * @throws \InvalidArgumentException Thrown when arguments above are not
     *                                   passed or are passed incorrectly.
     */
    public function putObjectAsync(array $args)
    {
        $provider = $this->getMaterialsProvider($args);
        unset($args['@MaterialsProvider']);

        $instructionFileSuffix = $this->getInstructionFileSuffix($args);
        unset($args['@InstructionFileSuffix']);

        $strategy = $this->getMetadataStrategy($args, $instructionFileSuffix);
        unset($args['@MetadataStrategy']);

        $envelope = new MetadataEnvelope();

        return Promise\Create::promiseFor($this->encrypt(
            Psr7\Utils::streamFor($args['Body']),
            $args,
            $provider,
            $envelope
        ))->then(
            function ($encryptedBodyStream) use ($args) {
                $hash = new PhpHash('sha256');
                $hashingEncryptedBodyStream = new HashingStream(
                    $encryptedBodyStream,
                    $hash,
                    self::getContentShaDecorator($args)
                );
                return [$hashingEncryptedBodyStream, $args];
            }
        )->then(
            function ($putObjectContents) use ($strategy, $envelope) {
                list($bodyStream, $args) = $putObjectContents;
                if ($strategy === null) {
                    $strategy = self::getDefaultStrategy();
                }

                $updatedArgs = $strategy->save($envelope, $args);
                $updatedArgs['Body'] = $bodyStream;
                return $updatedArgs;
            }
        )->then(
            function ($args) {
                unset($args['@CipherOptions']);
                return $this->client->putObjectAsync($args);
            }
        );
    }

    private static function getContentShaDecorator(&$args)
    {
        return function ($hash) use (&$args) {
            $args['ContentSHA256'] = bin2hex($hash);
        };
    }

    /**
     * Encrypts the data in the 'Body' field of $args and uploads it to the
     * specified location on S3.
     *
     * Note that for PHP versions of < 7.1, this operation uses an AES-GCM
     * polyfill for encryption since there is no native PHP support. The
     * performance for large inputs will be a lot slower than for PHP 7.1+, so
     * upgrading older PHP version environments may be necessary to use this
     * effectively.
     *
     * @param array $args Arguments for encrypting an object and uploading it
     *                    to S3 via PutObject.
     *
     * The required configuration arguments are as follows:
     *
     * - @MaterialsProvider: (MaterialsProvider) Provides Cek, Iv, and Cek
     *   encrypting/decrypting for encryption metadata.
     * - @CipherOptions: (array) Cipher options for encrypting data. A Cipher
     *   is required. Accepts the following options:
     *       - Cipher: (string) gcm
     *            See also: AbstractCryptoClientV2::$supportedCiphers
     *       - KeySize: (int) 128|256
     *            See also: MaterialsProvider::$supportedKeySizes
     *       - Aad: (string) Additional authentication data. This option is
     *            passed directly to OpenSSL when using gcm. Note if you pass in
     *            Aad, the PHP SDK will be able to decrypt the resulting object,
     *            but other AWS SDKs may not be able to do so.
     * - @KmsEncryptionContext: (array) Only required if using
     *   KmsMaterialsProviderV2. An associative array of key-value
     *   pairs to be added to the encryption context for KMS key encryption. An
     *   empty array may be passed if no additional context is desired.
     *
     * The optional configuration arguments are as follows:
     *
     * - @MetadataStrategy: (MetadataStrategy|string|null) Strategy for storing
     *   MetadataEnvelope information. Defaults to using a
     *   HeadersMetadataStrategy. Can either be a class implementing
     *   MetadataStrategy, a class name of a predefined strategy, or empty/null
     *   to default.
     * - @InstructionFileSuffix: (string|null) Suffix used when writing to an
     *   instruction file if an using an InstructionFileMetadataHandler was
     *   determined.
     *
     * @return \Aws\Result PutObject call result with the details of uploading
     *                     the encrypted file.
     *
     * @throws \InvalidArgumentException Thrown when arguments above are not
     *                                   passed or are passed incorrectly.
     */
    public function putObject(array $args)
    {
        return $this->putObjectAsync($args)->wait();
    }

    /**
     * Promises to retrieve an object from S3 and decrypt the data in the
     * 'Body' field.
     *
     * @param array $args Arguments for retrieving an object from S3 via
     *                    GetObject and decrypting it.
     *
     * The required configuration argument is as follows:
     *
     * - @MaterialsProvider: (MaterialsProviderInterface) Provides Cek, Iv, and Cek
     *   encrypting/decrypting for decryption metadata. May have data loaded
     *   from the MetadataEnvelope upon decryption.
     * - @SecurityProfile: (string) Must be set to 'V2' or 'V2_AND_LEGACY'.
     *      - 'V2' indicates that only objects encrypted with S3EncryptionClientV2
     *        content encryption and key wrap schemas are able to be decrypted.
     *      - 'V2_AND_LEGACY' indicates that objects encrypted with both
     *        S3EncryptionClientV2 and older legacy encryption clients are able
     *        to be decrypted.
     *
     * The optional configuration arguments are as follows:
     *
     * - SaveAs: (string) The path to a file on disk to save the decrypted
     *   object data. This will be handled by file_put_contents instead of the
     *   Guzzle sink.
     *
     * - @MetadataStrategy: (MetadataStrategy|string|null) Strategy for reading
     *   MetadataEnvelope information. Defaults to determining based on object
     *   response headers. Can either be a class implementing MetadataStrategy,
     *   a class name of a predefined strategy, or empty/null to default.
     * - @InstructionFileSuffix: (string) Suffix used when looking for an
     *   instruction file if an InstructionFileMetadataHandler is being used.
     * - @CipherOptions: (array) Cipher options for decrypting data. A Cipher
     *   is required. Accepts the following options:
     *       - Aad: (string) Additional authentication data. This option is
     *            passed directly to OpenSSL when using gcm. It is ignored when
     *            using cbc.
     * - @KmsAllowDecryptWithAnyCmk: (bool) This allows decryption with
     *   KMS materials for any KMS key ID, instead of needing the KMS key ID to
     *   be specified and provided to the decrypt operation. Ignored for non-KMS
     *   materials providers. Defaults to false.
     *
     * @return PromiseInterface
     *
     * @throws \InvalidArgumentException Thrown when required arguments are not
     *                                   passed or are passed incorrectly.
     */
    public function getObjectAsync(array $args)
    {
        $provider = $this->getMaterialsProvider($args);
        unset($args['@MaterialsProvider']);

        $instructionFileSuffix = $this->getInstructionFileSuffix($args);
        unset($args['@InstructionFileSuffix']);

        $strategy = $this->getMetadataStrategy($args, $instructionFileSuffix);
        unset($args['@MetadataStrategy']);

        if (!isset($args['@SecurityProfile'])
            || !in_array($args['@SecurityProfile'], self::$supportedSecurityProfiles)
        ) {
            throw new CryptoException("@SecurityProfile is required and must be"
                . " set to 'V2' or 'V2_AND_LEGACY'");
        }

        // Only throw this legacy warning once per client
        if (in_array($args['@SecurityProfile'], self::$legacySecurityProfiles)
            && $this->legacyWarningCount < 1
        ) {
            $this->legacyWarningCount++;
            trigger_error(
                "This S3 Encryption Client operation is configured to"
                    . " read encrypted data with legacy encryption modes. If you"
                    . " don't have objects encrypted with these legacy modes,"
                    . " you should disable support for them to enhance security. ",
                E_USER_WARNING
            );
        }

        $saveAs = null;
        if (!empty($args['SaveAs'])) {
            $saveAs = $args['SaveAs'];
        }

        $promise = $this->client->getObjectAsync($args)
            ->then(
                function ($result) use (
                    $provider,
                    $instructionFileSuffix,
                    $strategy,
                    $args
                ) {
                    if ($strategy === null) {
                        $strategy = $this->determineGetObjectStrategy(
                            $result,
                            $instructionFileSuffix
                        );
                    }

                    $envelope = $strategy->load($args + [
                        'Metadata' => $result['Metadata']
                    ]);

                    $result['Body'] = $this->decrypt(
                        $result['Body'],
                        $provider,
                        $envelope,
                        $args
                    );
                    return $result;
                }
            )->then(
                function ($result) use ($saveAs) {
                    if (!empty($saveAs)) {
                        file_put_contents(
                            $saveAs,
                            (string)$result['Body'],
                            LOCK_EX
                        );
                    }
                    return $result;
                }
            );

        return $promise;
    }

    /**
     * Retrieves an object from S3 and decrypts the data in the 'Body' field.
     *
     * @param array $args Arguments for retrieving an object from S3 via
     *                    GetObject and decrypting it.
     *
     * The required configuration argument is as follows:
     *
     * - @MaterialsProvider: (MaterialsProviderInterface) Provides Cek, Iv, and Cek
     *   encrypting/decrypting for decryption metadata. May have data loaded
     *   from the MetadataEnvelope upon decryption.
     * - @SecurityProfile: (string) Must be set to 'V2' or 'V2_AND_LEGACY'.
     *      - 'V2' indicates that only objects encrypted with S3EncryptionClientV2
     *        content encryption and key wrap schemas are able to be decrypted.
     *      - 'V2_AND_LEGACY' indicates that objects encrypted with both
     *        S3EncryptionClientV2 and older legacy encryption clients are able
     *        to be decrypted.
     *
     * The optional configuration arguments are as follows:
     *
     * - SaveAs: (string) The path to a file on disk to save the decrypted
     *   object data. This will be handled by file_put_contents instead of the
     *   Guzzle sink.
     * - @InstructionFileSuffix: (string|null) Suffix used when looking for an
     *   instruction file if an InstructionFileMetadataHandler was detected.
     * - @CipherOptions: (array) Cipher options for encrypting data. A Cipher
     *   is required. Accepts the following options:
     *       - Aad: (string) Additional authentication data. This option is
     *            passed directly to OpenSSL when using gcm. It is ignored when
     *            using cbc.
     * - @KmsAllowDecryptWithAnyCmk: (bool) This allows decryption with
     *   KMS materials for any KMS key ID, instead of needing the KMS key ID to
     *   be specified and provided to the decrypt operation. Ignored for non-KMS
     *   materials providers. Defaults to false.
     *
     * @return \Aws\Result GetObject call result with the 'Body' field
     *                     wrapped in a decryption stream with its metadata
     *                     information.
     *
     * @throws \InvalidArgumentException Thrown when arguments above are not
     *                                   passed or are passed incorrectly.
     */
    public function getObject(array $args)
    {
        return $this->getObjectAsync($args)->wait();
    }
}


<?php
namespace Aws\S3\Crypto;

use Aws\Crypto\AbstractCryptoClient;
use Aws\Crypto\EncryptionTrait;
use Aws\Crypto\MetadataEnvelope;
use Aws\Crypto\Cipher\CipherBuilderTrait;
use Aws\S3\MultipartUploader;
use Aws\S3\S3ClientInterface;
use GuzzleHttp\Promise;

/**
 * Encapsulates the execution of a multipart upload of an encrypted object to S3.
 *
 * Legacy implementation using older encryption workflow. Use
 * S3EncryptionMultipartUploaderV2 if possible.
 *
 * @deprecated
 */
class S3EncryptionMultipartUploader extends MultipartUploader
{
    use CipherBuilderTrait;
    use CryptoParamsTrait;
    use EncryptionTrait;
    use UserAgentTrait;

    const CRYPTO_VERSION = '1n';

    /**
     * Returns if the passed cipher name is supported for encryption by the SDK.
     *
     * @param string $cipherName The name of a cipher to verify is registered.
     *
     * @return bool If the cipher passed is in our supported list.
     */
    public static function isSupportedCipher($cipherName)
    {
        return in_array($cipherName, AbstractCryptoClient::$supportedCiphers);
    }

    private $provider;
    private $instructionFileSuffix;
    private $strategy;

    /**
     * Creates a multipart upload for an S3 object after encrypting it.
     *
     * The required configuration options are as follows:
     *
     * - @MaterialsProvider: (MaterialsProvider) Provides Cek, Iv, and Cek
     *   encrypting/decrypting for encryption metadata.
     * - @CipherOptions: (array) Cipher options for encrypting data. A Cipher
     *   is required. Accepts the following options:
     *       - Cipher: (string) cbc|gcm
     *            See also: AbstractCryptoClient::$supportedCiphers. Note that
     *            cbc is deprecated and gcm should be used when possible.
     *       - KeySize: (int) 128|192|256
     *            See also: MaterialsProvider::$supportedKeySizes
     *       - Aad: (string) Additional authentication data. This option is
     *            passed directly to OpenSSL when using gcm. It is ignored when
     *            using cbc.
     * - bucket: (string) Name of the bucket to which the object is
     *   being uploaded.
     * - key: (string) Key to use for the object being uploaded.
     *
     * The optional configuration arguments are as follows:
     *
     * - @MetadataStrategy: (MetadataStrategy|string|null) Strategy for storing
     *   MetadataEnvelope information. Defaults to using a
     *   HeadersMetadataStrategy. Can either be a class implementing
     *   MetadataStrategy, a class name of a predefined strategy, or empty/null
     *   to default.
     * - @InstructionFileSuffix: (string|null) Suffix used when writing to an
     *   instruction file if an using an InstructionFileMetadataHandler was
     *   determined.
     * - acl: (string) ACL to set on the object being upload. Objects are
     *   private by default.
     * - before_complete: (callable) Callback to invoke before the
     *   `CompleteMultipartUpload` operation. The callback should have a
     *   function signature like `function (Aws\Command $command) {...}`.
     * - before_initiate: (callable) Callback to invoke before the
     *   `CreateMultipartUpload` operation. The callback should have a function
     *   signature like `function (Aws\Command $command) {...}`.
     * - before_upload: (callable) Callback to invoke before any `UploadPart`
     *   operations. The callback should have a function signature like
     *   `function (Aws\Command $command) {...}`.
     * - concurrency: (int, default=int(5)) Maximum number of concurrent
     *   `UploadPart` operations allowed during the multipart upload.
     * - params: (array) An array of key/value parameters that will be applied
     *   to each of the sub-commands run by the uploader as a base.
     *   Auto-calculated options will override these parameters. If you need
     *   more granularity over parameters to each sub-command, use the before_*
     *   options detailed above to update the commands directly.
     * - part_size: (int, default=int(5242880)) Part size, in bytes, to use when
     *   doing a multipart upload. This must between 5 MB and 5 GB, inclusive.
     * - state: (Aws\Multipart\UploadState) An object that represents the state
     *   of the multipart upload and that is used to resume a previous upload.
     *   When this option is provided, the `bucket`, `key`, and `part_size`
     *   options are ignored.
     *
     * @param S3ClientInterface $client Client used for the upload.
     * @param mixed             $source Source of the data to upload.
     * @param array             $config Configuration used to perform the upload.
     */
    public function __construct(
        S3ClientInterface $client,
        $source,
        array $config = []
    ) {
        $this->appendUserAgent($client, 'feat/s3-encrypt/' . self::CRYPTO_VERSION);
        $this->client = $client;
        $config['params'] = [];
        if (!empty($config['bucket'])) {
            $config['params']['Bucket'] = $config['bucket'];
        }
        if (!empty($config['key'])) {
            $config['params']['Key'] = $config['key'];
        }

        $this->provider = $this->getMaterialsProvider($config);
        unset($config['@MaterialsProvider']);

        $this->instructionFileSuffix = $this->getInstructionFileSuffix($config);
        unset($config['@InstructionFileSuffix']);
        $this->strategy = $this->getMetadataStrategy(
            $config,
            $this->instructionFileSuffix
        );
        if ($this->strategy === null) {
            $this->strategy = self::getDefaultStrategy();
        }
        unset($config['@MetadataStrategy']);

        $config['prepare_data_source'] = $this->getEncryptingDataPreparer();

        parent::__construct($client, $source, $config);
    }

    private static function getDefaultStrategy()
    {
        return new HeadersMetadataStrategy();
    }

    private function getEncryptingDataPreparer()
    {
        return function() {
            // Defer encryption work until promise is executed
            $envelope = new MetadataEnvelope();

            list($this->source, $params) = Promise\Create::promiseFor($this->encrypt(
                $this->source,
                $this->config['@cipheroptions'] ?: [],
                $this->provider,
                $envelope
            ))->then(
                function ($bodyStream) use ($envelope) {
                    $params = $this->strategy->save(
                        $envelope,
                        $this->config['params']
                    );
                    return [$bodyStream, $params];
                }
            )->wait();

            $this->source->rewind();
            $this->config['params'] = $params;
        };
    }
}


<?php
namespace Aws\S3\Crypto;

use Aws\Crypto\AbstractCryptoClientV2;
use Aws\Crypto\EncryptionTraitV2;
use Aws\Crypto\MetadataEnvelope;
use Aws\Crypto\Cipher\CipherBuilderTrait;
use Aws\S3\MultipartUploader;
use Aws\S3\S3ClientInterface;
use GuzzleHttp\Promise;

/**
 * Encapsulates the execution of a multipart upload of an encrypted object to S3.
 *
 * Note that for PHP versions of < 7.1, this class uses an AES-GCM polyfill
 * for encryption since there is no native PHP support. The performance for large
 * inputs will be a lot slower than for PHP 7.1+, so upgrading older PHP version
 * environments may be necessary to use this effectively.
 */
class S3EncryptionMultipartUploaderV2 extends MultipartUploader
{
    use CipherBuilderTrait;
    use CryptoParamsTraitV2;
    use EncryptionTraitV2;
    use UserAgentTrait;

    CONST CRYPTO_VERSION = '2.1';

    /**
     * Returns if the passed cipher name is supported for encryption by the SDK.
     *
     * @param string $cipherName The name of a cipher to verify is registered.
     *
     * @return bool If the cipher passed is in our supported list.
     */
    public static function isSupportedCipher($cipherName)
    {
        return in_array($cipherName, AbstractCryptoClientV2::$supportedCiphers);
    }

    private $provider;
    private $instructionFileSuffix;
    private $strategy;

    /**
     * Creates a multipart upload for an S3 object after encrypting it.
     *
     * Note that for PHP versions of < 7.1, this class uses an AES-GCM polyfill
     * for encryption since there is no native PHP support. The performance for
     * large inputs will be a lot slower than for PHP 7.1+, so upgrading older
     * PHP version environments may be necessary to use this effectively.
     *
     * The required configuration options are as follows:
     *
     * - @MaterialsProvider: (MaterialsProviderV2) Provides Cek, Iv, and Cek
     *   encrypting/decrypting for encryption metadata.
     * - @CipherOptions: (array) Cipher options for encrypting data. A Cipher
     *   is required. Accepts the following options:
     *       - Cipher: (string) gcm
     *            See also: AbstractCryptoClientV2::$supportedCiphers
     *       - KeySize: (int) 128|256
     *            See also: MaterialsProvider::$supportedKeySizes
     *       - Aad: (string) Additional authentication data. This option is
     *            passed directly to OpenSSL when using gcm.
     * - @KmsEncryptionContext: (array) Only required if using
     *   KmsMaterialsProviderV2. An associative array of key-value
     *   pairs to be added to the encryption context for KMS key encryption. An
     *   empty array may be passed if no additional context is desired.
     * - bucket: (string) Name of the bucket to which the object is
     *   being uploaded.
     * - key: (string) Key to use for the object being uploaded.
     *
     * The optional configuration arguments are as follows:
     *
     * - @MetadataStrategy: (MetadataStrategy|string|null) Strategy for storing
     *   MetadataEnvelope information. Defaults to using a
     *   HeadersMetadataStrategy. Can either be a class implementing
     *   MetadataStrategy, a class name of a predefined strategy, or empty/null
     *   to default.
     * - @InstructionFileSuffix: (string|null) Suffix used when writing to an
     *   instruction file if an using an InstructionFileMetadataHandler was
     *   determined.
     * - acl: (string) ACL to set on the object being upload. Objects are
     *   private by default.
     * - before_complete: (callable) Callback to invoke before the
     *   `CompleteMultipartUpload` operation. The callback should have a
     *   function signature like `function (Aws\Command $command) {...}`.
     * - before_initiate: (callable) Callback to invoke before the
     *   `CreateMultipartUpload` operation. The callback should have a function
     *   signature like `function (Aws\Command $command) {...}`.
     * - before_upload: (callable) Callback to invoke before any `UploadPart`
     *   operations. The callback should have a function signature like
     *   `function (Aws\Command $command) {...}`.
     * - concurrency: (int, default=int(5)) Maximum number of concurrent
     *   `UploadPart` operations allowed during the multipart upload.
     * - params: (array) An array of key/value parameters that will be applied
     *   to each of the sub-commands run by the uploader as a base.
     *   Auto-calculated options will override these parameters. If you need
     *   more granularity over parameters to each sub-command, use the before_*
     *   options detailed above to update the commands directly.
     * - part_size: (int, default=int(5242880)) Part size, in bytes, to use when
     *   doing a multipart upload. This must between 5 MB and 5 GB, inclusive.
     * - state: (Aws\Multipart\UploadState) An object that represents the state
     *   of the multipart upload and that is used to resume a previous upload.
     *   When this option is provided, the `bucket`, `key`, and `part_size`
     *   options are ignored.
     *
     * @param S3ClientInterface $client Client used for the upload.
     * @param mixed             $source Source of the data to upload.
     * @param array             $config Configuration used to perform the upload.
     */
    public function __construct(
        S3ClientInterface $client,
        $source,
        array $config = []
    ) {
        $this->appendUserAgent($client, 'feat/s3-encrypt/' . self::CRYPTO_VERSION);
        $this->client = $client;
        $config['params'] = [];
        if (!empty($config['bucket'])) {
            $config['params']['Bucket'] = $config['bucket'];
        }
        if (!empty($config['key'])) {
            $config['params']['Key'] = $config['key'];
        }

        $this->provider = $this->getMaterialsProvider($config);
        unset($config['@MaterialsProvider']);

        $this->instructionFileSuffix = $this->getInstructionFileSuffix($config);
        unset($config['@InstructionFileSuffix']);
        $this->strategy = $this->getMetadataStrategy(
            $config,
            $this->instructionFileSuffix
        );
        if ($this->strategy === null) {
            $this->strategy = self::getDefaultStrategy();
        }
        unset($config['@MetadataStrategy']);

        $config['prepare_data_source'] = $this->getEncryptingDataPreparer();

        parent::__construct($client, $source, $config);
    }

    private static function getDefaultStrategy()
    {
        return new HeadersMetadataStrategy();
    }

    private function getEncryptingDataPreparer()
    {
        return function() {
            // Defer encryption work until promise is executed
            $envelope = new MetadataEnvelope();

            list($this->source, $params) = Promise\Create::promiseFor($this->encrypt(
                $this->source,
                $this->config ?: [],
                $this->provider,
                $envelope
            ))->then(
                function ($bodyStream) use ($envelope) {
                    $params = $this->strategy->save(
                        $envelope,
                        $this->config['params']
                    );
                    return [$bodyStream, $params];
                }
            )->wait();

            $this->source->rewind();
            $this->config['params'] = $params;
        };
    }
}


<?php
namespace Aws\S3\Crypto;

use Aws\AwsClientInterface;
use Aws\Middleware;
use Psr\Http\Message\RequestInterface;

trait UserAgentTrait
{
    private function appendUserAgent(AwsClientInterface $client, $agentString)
    {
        $list = $client->getHandlerList();
        $list->appendBuild(Middleware::mapRequest(
            function(RequestInterface $req) use ($agentString) {
                if (!empty($req->getHeader('User-Agent'))
                    && !empty($req->getHeader('User-Agent')[0])
                ) {
                    $userAgent = $req->getHeader('User-Agent')[0];
                    if (strpos($userAgent, $agentString) === false) {
                        $userAgent .= " {$agentString}";
                    };
                } else {
                    $userAgent = $agentString;
                }

                $req =  $req->withHeader('User-Agent', $userAgent);
                return $req;
            }
        ));
    }
}


<?php
namespace Aws\S3\Exception;

use Aws\HasMonitoringEventsTrait;
use Aws\MonitoringEventsInterface;

/**
 * Exception thrown when errors occur while deleting objects using a
 * {@see S3\BatchDelete} object.
 */
class DeleteMultipleObjectsException extends \Exception implements
    MonitoringEventsInterface
{
    use HasMonitoringEventsTrait;

    private $deleted = [];
    private $errors = [];

    /**
     * @param array       $deleted Array of successfully deleted keys
     * @param array       $errors  Array of errors that were encountered
     */
    public function __construct(array $deleted, array $errors)
    {
        $this->deleted = array_values($deleted);
        $this->errors = array_values($errors);
        parent::__construct('Unable to delete certain keys when executing a'
            . ' DeleteMultipleObjects request: '
            . self::createMessageFromErrors($errors));
    }

    /**
     * Create a single error message from multiple errors.
     *
     * @param array $errors Errors encountered
     *
     * @return string
     */
    public static function createMessageFromErrors(array $errors)
    {
        return "\n- " . implode("\n- ", array_map(function ($key) {
            return json_encode($key);
        }, $errors));
    }

    /**
     * Get the errored objects
     *
     * @return array Returns an array of associative arrays, each containing
     *               a 'Code', 'Message', and 'Key' key.
     */
    public function getErrors()
    {
        return $this->errors;
    }

    /**
     * Get the successfully deleted objects
     *
     * @return array Returns an array of associative arrays, each containing
     *               a 'Key' and optionally 'DeleteMarker' and
     *              'DeleterMarkerVersionId'
     */
    public function getDeleted()
    {
        return $this->deleted;
    }
}


<?php
namespace Aws\S3\Exception;

class PermanentRedirectException extends S3Exception {}


<?php
namespace Aws\S3\Exception;

use Aws\Exception\AwsException;

/**
 * Represents an error interacting with the Amazon Simple Storage Service.
 */
class S3Exception extends AwsException {}


<?php
namespace Aws\S3\Exception;

use Aws\CommandInterface;
use Aws\Exception\AwsException;
use Aws\Multipart\UploadState;

class S3MultipartUploadException extends \Aws\Exception\MultipartUploadException
{
    /** @var string Bucket of the transfer object */
    private $bucket;
    /** @var string Key of the transfer object */
    private $key;
    /** @var string Source file name of the transfer object */
    private $filename;

    /**
     * @param UploadState      $state Upload state at time of the exception.
     * @param \Exception|array $prev  Exception being thrown. Could be an array of
     *                                AwsExceptions being thrown when uploading parts
     *                                for one object, or an instance of AwsException
     *                                for a specific Multipart error being thrown in
     *                                the MultipartUpload process.
     */
    public function __construct(UploadState $state, $prev = null) {
        if (is_array($prev) && $error = $prev[key($prev)]) {
            $this->collectPathInfo($error->getCommand());
        } elseif ($prev instanceof AwsException) {
            $this->collectPathInfo($prev->getCommand());
        }
        parent::__construct($state, $prev);
    }

    /**
     * Get the Bucket information of the transfer object
     *
     * @return string|null Returns null when 'Bucket' information
     *                     is unavailable.
     */
    public function getBucket()
    {
        return $this->bucket;
    }

    /**
     * Get the Key information of the transfer object
     *
     * @return string|null Returns null when 'Key' information
     *                     is unavailable.
     */
    public function getKey()
    {
        return $this->key;
    }

    /**
     * Get the source file name of the transfer object
     *
     * @return string|null Returns null when metadata of the stream
     *                     wrapped in 'Body' parameter is unavailable.
     */
    public function getSourceFileName()
    {
        return $this->filename;
    }

    /**
     * Collect file path information when accessible. (Bucket, Key)
     *
     * @param CommandInterface $cmd
     */
    private function collectPathInfo(CommandInterface $cmd)
    {
        if (empty($this->bucket) && isset($cmd['Bucket'])) {
            $this->bucket = $cmd['Bucket'];
        }
        if (empty($this->key) && isset($cmd['Key'])) {
            $this->key = $cmd['Key'];
        }
        if (empty($this->filename) && isset($cmd['Body'])) {
            $this->filename = $cmd['Body']->getMetadata('uri');
        }
    }
}


<?php
namespace Aws\S3\RegionalEndpoint;

class Configuration implements ConfigurationInterface
{
    private $endpointsType;
    private $isFallback;

    public function __construct($endpointsType, $isFallback = false)
    {
        $this->endpointsType = strtolower($endpointsType);
        $this->isFallback = $isFallback;
        if (!in_array($this->endpointsType, ['legacy', 'regional'])) {
            throw new \InvalidArgumentException(
                "Configuration parameter must either be 'legacy' or 'regional'."
            );
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getEndpointsType()
    {
        return $this->endpointsType;
    }

    /**
     * {@inheritdoc}
     */
    public function toArray()
    {
        return [
            'endpoints_type' => $this->getEndpointsType()
        ];
    }

    public function isFallback()
    {
        return $this->isFallback;
    }
}


<?php
namespace Aws\S3\RegionalEndpoint;

/**
 * Provides access to S3 regional endpoints configuration options: endpoints_type
 */
interface ConfigurationInterface
{
    /**
     * Returns the endpoints type
     *
     * @return string
     */
    public function getEndpointsType();

    /**
     * Returns the configuration as an associative array
     *
     * @return array
     */
    public function toArray();
}


<?php
namespace Aws\S3\RegionalEndpoint;

use Aws\AbstractConfigurationProvider;
use Aws\CacheInterface;
use Aws\ConfigurationProviderInterface;
use Aws\S3\RegionalEndpoint\Exception\ConfigurationException;
use GuzzleHttp\Promise;

/**
 * A configuration provider is a function that returns a promise that is
 * fulfilled with a {@see \Aws\S3\RegionalEndpoint\ConfigurationInterface}
 * or rejected with an {@see \Aws\S3\RegionalEndpoint\Exception\ConfigurationException}.
 *
 *
 * use Aws\S3\RegionalEndpoint\ConfigurationProvider;
 * $provider = ConfigurationProvider::defaultProvider();
 * // Returns a ConfigurationInterface or throws.
 * $config = $provider()->wait();
 *
 *
 * 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\S3\RegionalEndpoint\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.
 *
 *
 * // 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();
 *
 */
class ConfigurationProvider extends AbstractConfigurationProvider
    implements ConfigurationProviderInterface
{
    const ENV_ENDPOINTS_TYPE = 'AWS_S3_US_EAST_1_REGIONAL_ENDPOINT';
    const INI_ENDPOINTS_TYPE = 's3_us_east_1_regional_endpoint';
    const DEFAULT_ENDPOINTS_TYPE = 'legacy';

    public static $cacheKey = 'aws_s3_us_east_1_regional_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();

        $memo = self::memoize(
            call_user_func_array([ConfigurationProvider::class, 'chain'], $configProviders)
        );

        if (isset($config['s3_us_east_1_regional_endpoint'])
            && $config['s3_us_east_1_regional_endpoint'] instanceof CacheInterface
        ) {
            return self::cache($memo, $config['s3_us_east_1_regional_endpoint'], self::$cacheKey);
        }

        return $memo;
    }

    public static function env()
    {
        return function () {
            // Use config from environment variables, if available
            $endpointsType = getenv(self::ENV_ENDPOINTS_TYPE);
            if (!empty($endpointsType)) {
                return Promise\Create::promiseFor(
                    new Configuration($endpointsType)
                );
            }

            return self::reject('Could not find environment variable config'
                . ' in ' . self::ENV_ENDPOINTS_TYPE);
        };
    }

    /**
     * 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");
            }
            $data = \Aws\parse_ini_file($filename, true);
            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_ENDPOINTS_TYPE])) {
                return self::reject("Required S3 regional endpoint config values
                    not present in INI profile '{$profile}' ({$filename})");
            }

            return Promise\Create::promiseFor(
                new Configuration($data[$profile][self::INI_ENDPOINTS_TYPE])
            );
        };
    }

    /**
     * Fallback config options when other sources are not set.
     *
     * @return callable
     */
    public static function fallback()
    {
        return function () {
            return Promise\Create::promiseFor(
                new Configuration(self::DEFAULT_ENDPOINTS_TYPE, true)
            );
        };
    }

    /**
     * Unwraps a configuration object in whatever valid form it is in,
     * always returning a ConfigurationInterface object.
     *
     * @param  mixed $config
     * @return ConfigurationInterface
     * @throws \InvalidArgumentException
     */
    public static function unwrap($config)
    {
        if (is_callable($config)) {
            $config = $config();
        }
        if ($config instanceof Promise\PromiseInterface) {
            $config = $config->wait();
        }
        if ($config instanceof ConfigurationInterface) {
            return $config;
        }
        if (is_string($config)) {
            return new Configuration($config);
        }
        if (is_array($config) && isset($config['endpoints_type'])) {
            return new Configuration($config['endpoints_type']);
        }

        throw new \InvalidArgumentException('Not a valid S3 regional endpoint '
            . 'configuration argument.');
    }
}


<?php
namespace Aws\S3\RegionalEndpoint\Exception;

use Aws\HasMonitoringEventsTrait;
use Aws\MonitoringEventsInterface;

/**
 * Represents an error interacting with configuration for sts regional endpoints
 */
class ConfigurationException extends \RuntimeException implements
    MonitoringEventsInterface
{
    use HasMonitoringEventsTrait;
}


<?php
namespace Aws\S3\UseArnRegion;

use Aws;
use Aws\S3\UseArnRegion\Exception\ConfigurationException;

class Configuration implements ConfigurationInterface
{
    private $useArnRegion;

    public function __construct($useArnRegion)
    {
        $this->useArnRegion = Aws\boolean_value($useArnRegion);
        if (is_null($this->useArnRegion)) {
            throw new ConfigurationException("'use_arn_region' config option"
                . " must be a boolean value.");
        }
    }

    /**
     * {@inheritdoc}
     */
    public function isUseArnRegion()
    {
        return $this->useArnRegion;
    }

    /**
     * {@inheritdoc}
     */
    public function toArray()
    {
        return [
            'use_arn_region' => $this->isUseArnRegion(),
        ];
    }
}


<?php
namespace Aws\S3\UseArnRegion;

interface ConfigurationInterface
{
    /**
     * Returns whether or not to use the ARN region if it differs from client
     *
     * @return bool
     */
    public function isUseArnRegion();

    /**
     * Returns the configuration as an associative array
     *
     * @return array
     */
    public function toArray();
}


<?php
namespace Aws\S3\UseArnRegion;

use Aws\AbstractConfigurationProvider;
use Aws\CacheInterface;
use Aws\ConfigurationProviderInterface;
use Aws\S3\UseArnRegion\Exception\ConfigurationException;
use GuzzleHttp\Promise;

/**
 * A configuration provider is a function that returns a promise that is
 * fulfilled with a {@see \Aws\S3\UseArnRegion\ConfigurationInterface}
 * or rejected with an {@see \Aws\S3\UseArnRegion\Exception\ConfigurationException}.
 *
 *
 * use Aws\S3\UseArnRegion\ConfigurationProvider;
 * $provider = ConfigurationProvider::defaultProvider();
 * // Returns a ConfigurationInterface or throws.
 * $config = $provider()->wait();
 *
 *
 * 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\S3\UseArnRegion\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.
 *
 *
 * // 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();
 *
 */
class ConfigurationProvider extends AbstractConfigurationProvider
    implements ConfigurationProviderInterface
{
    const ENV_USE_ARN_REGION = 'AWS_S3_USE_ARN_REGION';
    const INI_USE_ARN_REGION = 's3_use_arn_region';
    const DEFAULT_USE_ARN_REGION = true;

    public static $cacheKey = 'aws_s3_use_arn_region_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();

        $memo = self::memoize(
            call_user_func_array([ConfigurationProvider::class, 'chain'], $configProviders)
        );

        if (isset($config['use_arn_region'])
            && $config['use_arn_region'] instanceof CacheInterface
        ) {
            return self::cache($memo, $config['use_arn_region'], 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
            $useArnRegion = getenv(self::ENV_USE_ARN_REGION);
            if (!empty($useArnRegion)) {
                return Promise\Create::promiseFor(
                    new Configuration($useArnRegion)
                );
            }

            return self::reject('Could not find environment variable config'
                . ' in ' . self::ENV_USE_ARN_REGION);
        };
    }

    /**
     * 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_ARN_REGION])) {
                return self::reject("Required S3 Use Arn Region 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_ARN_REGION] === "") {
                $data[$profile][self::INI_USE_ARN_REGION] = false;
            }

            return Promise\Create::promiseFor(
                new Configuration($data[$profile][self::INI_USE_ARN_REGION])
            );
        };
    }

    /**
     * Fallback config options when other sources are not set.
     *
     * @return callable
     */
    public static function fallback()
    {
        return function () {
            return Promise\Create::promiseFor(
                new Configuration(self::DEFAULT_USE_ARN_REGION)
            );
        };
    }
}


<?php
namespace Aws\S3\UseArnRegion\Exception;

use Aws\HasMonitoringEventsTrait;
use Aws\MonitoringEventsInterface;

/**
 * Represents an error interacting with configuration for S3's UseArnRegion
 */
class ConfigurationException extends \RuntimeException implements
    MonitoringEventsInterface
{
    use HasMonitoringEventsTrait;
}


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


<?php
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 deleteBucketReplication(array $args = [])
 * @method \GuzzleHttp\Promise\Promise deleteBucketReplicationAsync(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 getBucketReplication(array $args = [])
 * @method \GuzzleHttp\Promise\Promise getBucketReplicationAsync(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 putBucketReplication(array $args = [])
 * @method \GuzzleHttp\Promise\Promise putBucketReplicationAsync(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
{
    public static function getArguments()
    {
        $args = parent::getArguments();
        return $args + [
            'use_dual_stack_endpoint' => [
                'type' => 'config',
                'valid' => ['bool'],
                'doc' => 'Set to true to send requests to an S3 Control Dual Stack'
                    . ' endpoint by default, which enables IPv6 Protocol.'
                    . ' Can be enabled or disabled on individual operations by setting'
                    . ' \'@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}
     *
     * In addition to the options available to
     * {@see Aws\AwsClient::__construct}, S3ControlClient accepts the following
     * option:
     *
     * - use_dual_stack_endpoint: (bool) Set to true to send requests to an S3
     *   Control Dual Stack endpoint by default, which enables IPv6 Protocol.
     *   Can be enabled or disabled on individual operations by setting
     *   '@use_dual_stack_endpoint\' to true or false. Note:
     *   you cannot use it together with an accelerate endpoint.
     *
     * @param array $args
     */
    public function __construct(array $args)
    {
        parent::__construct($args);

        if ($this->isUseEndpointV2()) {
            $this->processEndpointV2Model();
        }
        $stack = $this->getHandlerList();
        $stack->appendBuild(
            EndpointArnMiddleware::wrap(
                $this->getApi(),
                $this->getRegion(),
                [
                    '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_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]);
                }
            }
        }
    }
}


<?php
namespace Aws\S3Control\Exception;

use Aws\Exception\AwsException;

/**
 * Represents an error interacting with the **AWS S3 Control** service.
 */
class S3ControlException extends AwsException {}


<?php
namespace Aws\S3Outposts;

use Aws\AwsClient;

/**
 * This client is used to interact with the **Amazon S3 on Outposts** service.
 * @method \Aws\Result createEndpoint(array $args = [])
 * @method \GuzzleHttp\Promise\Promise createEndpointAsync(array $args = [])
 * @method \Aws\Result deleteEndpoint(array $args = [])
 * @method \GuzzleHttp\Promise\Promise deleteEndpointAsync(array $args = [])
 * @method \Aws\Result listEndpoints(array $args = [])
 * @method \GuzzleHttp\Promise\Promise listEndpointsAsync(array $args = [])
 * @method \Aws\Result listOutpostsWithS3(array $args = [])
 * @method \GuzzleHttp\Promise\Promise listOutpostsWithS3Async(array $args = [])
 * @method \Aws\Result listSharedEndpoints(array $args = [])
 * @method \GuzzleHttp\Promise\Promise listSharedEndpointsAsync(array $args = [])
 */
class S3OutpostsClient extends AwsClient {}


<?php
namespace Aws\S3Outposts\Exception;

use Aws\Exception\AwsException;

/**
 * Represents an error interacting with the **Amazon S3 on Outposts** service.
 */
class S3OutpostsException extends AwsException {}