/
AwsAuthV4.php
executable file
·94 lines (81 loc) · 2.69 KB
/
AwsAuthV4.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
namespace Elastica\Transport;
use Aws\Credentials\CredentialProvider;
use Aws\Credentials\Credentials;
use Aws\Signature\SignatureV4;
use Elastica\Connection;
use GuzzleHttp;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use Psr\Http\Message\RequestInterface;
class AwsAuthV4 extends Guzzle
{
protected function _getGuzzleClient(bool $persistent = true): Client
{
if (!$persistent || !self::$_guzzleClientConnection) {
$stack = HandlerStack::create(GuzzleHttp\choose_handler());
$stack->push($this->getSigningMiddleware(), 'sign');
self::$_guzzleClientConnection = new Client([
'handler' => $stack,
]);
}
return self::$_guzzleClientConnection;
}
protected function _getBaseUrl(Connection $connection): string
{
$this->initializePortAndScheme();
return parent::_getBaseUrl($connection);
}
private function getSigningMiddleware()
{
$region = $this->getConnection()->hasParam('aws_region')
? $this->getConnection()->getParam('aws_region')
: \getenv('AWS_REGION');
$signer = new SignatureV4('es', $region);
$credProvider = $this->getCredentialProvider();
return Middleware::mapRequest(function (RequestInterface $req) use (
$signer,
$credProvider
) {
return $signer->signRequest($req, $credProvider()->wait());
});
}
private function getCredentialProvider()
{
$connection = $this->getConnection();
if ($connection->hasParam('aws_secret_access_key')) {
return CredentialProvider::fromCredentials(new Credentials(
$connection->getParam('aws_access_key_id'),
$connection->getParam('aws_secret_access_key'),
$connection->hasParam('aws_session_token')
? $connection->getParam('aws_session_token')
: null
));
}
return CredentialProvider::defaultProvider();
}
private function initializePortAndScheme()
{
$connection = $this->getConnection();
if (true === $this->isSslRequired($connection)) {
$this->_scheme = 'https';
$connection->setPort(443);
} else {
$this->_scheme = 'http';
$connection->setPort(80);
}
}
/**
* @param Connection $conn
* @param bool $default
*
* @return bool
*/
private function isSslRequired(Connection $conn, bool $default = false): bool
{
return $conn->hasParam('ssl')
? (bool) $conn->getParam('ssl')
: $default;
}
}