Вход Регистрация
Файл: includes/library/aws/Aws/Credentials/CredentialProvider.php
Строк: 374
<?php
namespace AwsCredentials;

use 
Aws;
use 
AwsExceptionCredentialsException;
use 
GuzzleHttpPromise;

/**
 * Credential providers are functions that accept no arguments and return a
 * promise that is fulfilled with an {@see AwsCredentialsCredentialsInterface}
 * or rejected with an {@see AwsExceptionCredentialsException}.
 *
 * <code>
 * use AwsCredentialsCredentialProvider;
 * $provider = CredentialProvider::defaultProvider();
 * // Returns a CredentialsInterface or throws.
 * $creds = $provider()->wait();
 * </code>
 *
 * Credential providers can be composed to create credentials using conditional
 * logic that can create different credentials in different environments. You
 * can compose multiple providers into a single provider using
 * {@see AwsCredentialsCredentialProvider::chain}. This function accepts
 * providers as variadic arguments and returns a new function that will invoke
 * each provider until a successful set of credentials is returned.
 *
 * <code>
 * // First try an INI file at this location.
 * $a = CredentialProvider::ini(null, '/path/to/file.ini');
 * // Then try an INI file at this location.
 * $b = CredentialProvider::ini(null, '/path/to/other-file.ini');
 * // Then try loading from envrionment variables.
 * $c = CredentialProvider::env();
 * // Combine the three providers together.
 * $composed = CredentialProvider::chain($a, $b, $c);
 * // Returns a promise that is fulfilled with credentials or throws.
 * $promise = $composed();
 * // Wait on the credentials to resolve.
 * $creds = $promise->wait();
 * </code>
 */
class CredentialProvider
{
    const 
ENV_KEY 'AWS_ACCESS_KEY_ID';
    const 
ENV_SECRET 'AWS_SECRET_ACCESS_KEY';
    const 
ENV_SESSION 'AWS_SESSION_TOKEN';
    const 
ENV_PROFILE 'AWS_PROFILE';

    
/**
     * Create a default credential provider that first checks for environment
     * variables, then checks for the "default" profile in ~/.aws/credentials,
     * and finally checks for credentials using EC2 instance profile
     * credentials.
     *
     * This provider is automatically wrapped in a memoize function that caches
     * previously provided credentials.
     *
     * @param array $config Optional array of instance profile credentials
     *                      provider options.
     * @return callable
     */
    
public static function defaultProvider(array $config = [])
    {
        return 
self::memoize(
            
self::chain(
                
self::env(),
                
self::ini(),
                
self::instanceProfile($config)
            )
        );
    }

    
/**
     * Create a credential provider function from a set of static credentials.
     *
     * @param CredentialsInterface $creds
     *
     * @return callable
     */
    
public static function fromCredentials(CredentialsInterface $creds)
    {
        
$promise Promisepromise_for($creds);

        return function () use (
$promise) {
            return 
$promise;
        };
    }

    
/**
     * Creates an aggregate credentials provider that invokes the provided
     * variadic providers one after the other until a provider returns
     * credentials.
     *
     * @return callable
     */
    
public static function chain()
    {
        
$links func_get_args();
        if (empty(
$links)) {
            throw new 
InvalidArgumentException('No providers in chain');
        }

        return function () use (
$links) {
            
/** @var callable $parent */
            
$parent array_shift($links);
            
$promise $parent();
            while (
$next array_shift($links)) {
                
$promise $promise->otherwise($next);
            }
            return 
$promise;
        };
    }

    
/**
     * Wraps a credential provider and caches previously provided credentials.
     *
     * Ensures that cached credentials are refreshed when they expire.
     *
     * @param callable $provider Credentials provider function to wrap.
     *
     * @return callable
     */
    
public static function memoize(callable $provider)
    {
        
// Create the initial promise that will be used as the cached value
        // until it expires.
        
$result $provider();
        
$isConstant false;

        return function () use (&
$result, &$isConstant$provider) {
            
// Constant credentials will be returned constantly.
            
if ($isConstant) {
                return 
$result;
            }

            
// Determine if these are constant credentials.
            
if ($result->getState() === PromisePromiseInterface::FULFILLED
                
&& !$result->wait()->getExpiration()
            ) {
                
$isConstant true;
                return 
$result;
            }

            
// Return credentials that could expire and refresh when needed.
            
return $result
                
->then(function (CredentialsInterface $creds) use ($provider, &$result) {
                    
// Refresh expired credentials.
                    
if (!$creds->isExpired()) {
                        return 
$creds;
                    }
                    
// Refresh the result and forward the promise.
                    
return $result $provider();
                });
        };
    }

    
/**
     * Provider that creates credentials from environment variables
     * AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN.
     *
     * @return callable
     */
    
public static function env()
    {
        return function () {
            
// Use credentials from environment variables, if available
            
$key getenv(self::ENV_KEY);
            
$secret getenv(self::ENV_SECRET);
            if (
$key && $secret) {
                return 
Promisepromise_for(
                    new 
Credentials($key$secretgetenv(self::ENV_SESSION))
                );
            }

            return 
self::reject('Could not find environment variable '
                
'credentials in ' self::ENV_KEY '/' self::ENV_SECRET);
        };
    }

    
/**
     * Credential provider that creates credentials using instance profile
     * credentials.
     *
     * @param array $config Array of configuration data.
     *
     * @return InstanceProfileProvider
     * @see AwsCredentialsInstanceProfileProvider for $config details.
     */
    
public static function instanceProfile(array $config = [])
    {
        return new 
InstanceProfileProvider($config);
    }

    
/**
     * Credentials provider that creates credentials using an ini file stored
     * in the current user's home directory.
     *
     * @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 home directory for the
     *
     * @return callable
     */
    
public static function ini($profile null$filename null)
    {
        
$filename $filename ?: (self::getHomeDir() . '/.aws/credentials');
        
$profile $profile ?: (getenv(self::ENV_PROFILE) ?: 'default');

        return function () use (
$profile$filename) {
            if (!
is_readable($filename)) {
                return 
self::reject("Cannot read credentials from $filename");
            }
            
$data parse_ini_file($filenametrue);
            if (
$data === false) {
                return 
self::reject("Invalid credentials file: $filename");
            }
            if (!isset(
$data[$profile])) {
                return 
self::reject("'$profile' not found in credentials file");
            }
            if (!isset(
$data[$profile]['aws_access_key_id'])
                || !isset(
$data[$profile]['aws_secret_access_key'])
            ) {
                return 
self::reject("No credentials present in INI profile "
                    
"'$profile' ($filename)");
            }

            return 
Promisepromise_for(
                new 
Credentials(
                    
$data[$profile]['aws_access_key_id'],
                    
$data[$profile]['aws_secret_access_key'],
                    isset(
$data[$profile]['aws_security_token'])
                        ? 
$data[$profile]['aws_security_token']
                        : 
null
                
)
            );
        };
    }

    
/**
     * Gets the environment's HOME directory if available.
     *
     * @return null|string
     */
    
private static function getHomeDir()
    {
        
// On Linux/Unix-like systems, use the HOME environment variable
        
if ($homeDir getenv('HOME')) {
            return 
$homeDir;
        }

        
// Get the HOMEDRIVE and HOMEPATH values for Windows hosts
        
$homeDrive getenv('HOMEDRIVE');
        
$homePath getenv('HOMEPATH');

        return (
$homeDrive && $homePath) ? $homeDrive $homePath null;
    }

    private static function 
reject($msg)
    {
        return new 
PromiseRejectedPromise(new CredentialsException($msg));
    }
}
Онлайн: 2
Реклама