-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathClient.php
More file actions
342 lines (285 loc) · 8.59 KB
/
Client.php
File metadata and controls
342 lines (285 loc) · 8.59 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
<?php
namespace Vault;
use Exception;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Cache\InvalidArgumentException;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Vault\AuthenticationStrategies\AuthenticationStrategy;
use Vault\Exceptions\AuthenticationException;
use Vault\Exceptions\DependencyException;
use Vault\Exceptions\RequestException;
use Vault\Exceptions\RuntimeException;
use Vault\Helpers\ModelHelper;
use Vault\Models\Token;
use Vault\ResponseModels\Response;
/**
* Class Client
*
* @todo make an interface
* @todo add ability to make concurrent requests
*
* @package Vault
*/
class Client extends BaseClient
{
public const TOKEN_CACHE_KEY = 'token';
/**
* @var CacheItemPoolInterface
*/
protected $cache;
/**
* @var AuthenticationStrategy
*/
protected $authenticationStrategy;
/**
* @param string $path
*
* @return Response
* @throws \InvalidArgumentException
* @throws ClientExceptionInterface
*/
public function read(string $path): Response
{
return $this->get($this->buildPath($path));
}
/**
* @param string $path
*
* @return string
*/
public function buildPath(string $path): string
{
if (!$this->version) {
$this->logger->warning('API version is not set!');
return $path;
}
return sprintf('/%s%s', $this->version, $path);
}
/**
* @param string $path
*
* @return Response
* @throws \InvalidArgumentException
* @throws ClientExceptionInterface
*/
public function keys(string $path): Response
{
return $this->list($this->buildPath($path));
}
/**
* @param string $path
* @param array $data
*
* @return Response
* @throws \InvalidArgumentException
* @throws ClientExceptionInterface
*/
public function write(string $path, array $data = []): Response
{
return $this->post($this->buildPath($path), json_encode($data));
}
/**
* @param string $path
*
* @return Response
* @throws \InvalidArgumentException
* @throws ClientExceptionInterface
*/
public function revoke(string $path): Response
{
return $this->delete($this->buildPath($path));
}
/**
* @return CacheItemPoolInterface
*/
public function getCache(): CacheItemPoolInterface
{
return $this->cache;
}
/**
* @param CacheItemPoolInterface $cache
*
* @return $this
*/
public function setCache(CacheItemPoolInterface $cache): self
{
$this->cache = $cache;
return $this;
}
/**
* @return AuthenticationStrategy
*/
public function getAuthenticationStrategy(): AuthenticationStrategy
{
return $this->authenticationStrategy;
}
/**
* @param AuthenticationStrategy $authenticationStrategy
*
* @return $this
*/
public function setAuthenticationStrategy(AuthenticationStrategy $authenticationStrategy): self
{
$authenticationStrategy->setClient($this);
$this->authenticationStrategy = $authenticationStrategy;
return $this;
}
/**
* @inheritdoc
* @throws DependencyException
* @throws AuthenticationException
* @throws Exception
* @throws InvalidArgumentException
* @throws ClientExceptionInterface
*/
public function send(string $method, string $path, string $body = ''): ResponseInterface
{
try {
return parent::send($method, $path, $body);
} /** @noinspection PhpRedundantCatchClauseInspection */ catch (RequestException $e) {
// re-authenticate if 403 and token is expired
if (
$this->token &&
$e->getCode() === 403 &&
$this->isTokenExpired($this->token)
) {
try {
if ($this->authenticate()) {
return parent::send($method, $path, $body);
}
} catch (Exception $e) {
$this->logger->error('Cannot re-authenticate.', [
'code' => $e->getCode(),
'message' => $e->getMessage(),
]);
$this->logger->debug('Trace.', ['exception' => $e]);
}
throw new AuthenticationException('Cannot re-authenticate');
}
throw $e;
}
}
/**
* @param Token $token
*
* @return bool
*/
protected function isTokenExpired(Token $token): bool
{
return !$token ||
(
$token->getCreationTtl() > 0 &&
time() > $token->getCreationTime() + $token->getCreationTtl()
);
}
/**
* @return bool
*
* @throws RuntimeException
* @throws DependencyException
* @throws Exception
* @throws InvalidArgumentException
* @throws ClientExceptionInterface
*/
public function authenticate(): bool
{
if ($this->token = $this->getTokenFromCache()) {
$this->logger->debug('Using token from cache.');
$this->writeTokenInfoToDebugLog();
return (bool)$this->token;
}
if (!$this->authenticationStrategy) {
$this->logger->critical('Trying to authenticate without strategy.');
throw new DependencyException(sprintf(
'Specify authentication strategy before calling this method (%s).',
__METHOD__
));
}
$this->logger->debug('Trying to authenticate.');
if ($auth = $this->authenticationStrategy->authenticate()) {
$this->logger->debug('Authentication was successful.', ['clientToken' => $auth->getClientToken()]);
// temporary
$this->token = new Token(['auth' => $auth]);
// get info about self
$response = $this->get('/v1/auth/token/lookup-self');
$this->token = new Token(array_merge(ModelHelper::camelize($response->getData()), ['auth' => $auth]));
$this->writeTokenInfoToDebugLog();
$this->putTokenIntoCache();
return true;
}
return false;
}
/**
* @TODO: move to separated class
*
* @return Token|null
*
* @throws InvalidArgumentException
*/
protected function getTokenFromCache(): ?Token
{
if (!$this->cache || !$this->cache->hasItem(self::TOKEN_CACHE_KEY)) {
return null;
}
/** @var Token $token */
$token = $this->cache->getItem(self::TOKEN_CACHE_KEY)->get();
if (!$token || !$token->getAuth()) {
$this->logger->debug('No token in cache or auth is empty, returning null.');
return null;
}
// invalidate token
if ($this->isTokenExpired($token)) {
$this->logger->debug('Token is expired.');
$this->writeTokenInfoToDebugLog();
return null;
}
return $token;
}
private function writeTokenInfoToDebugLog(): void
{
if (!$this->token) {
$this->logger->debug('Token is null, cannot write info to debug, potential error.');
return;
}
$this->logger->debug('Token info.', [
'clientToken' => $this->token->getAuth() ? $this->token->getAuth()->getClientToken() : null,
'id' => $this->token->getId(),
'creationTime' => $this->token->getCreationTime(),
'ttl' => $this->token->getCreationTtl(),
]);
}
/**
* @TODO: move to separated class
*
* @return bool
* @throws Exception
* @throws RuntimeException
* @throws InvalidArgumentException
*/
protected function putTokenIntoCache(): bool
{
if (!$this->cache) {
return true; // just ignore
}
if ($this->isTokenExpired($this->token)) {
throw new RuntimeException('Cannot save expired token into cache!');
}
$authItem = $this->cache->getItem(self::TOKEN_CACHE_KEY);
$authItem->set($this->token)->expiresAfter($this->token->getAuth()->getLeaseDuration());
$this->logger->debug('Token is saved into cache.');
return $this->cache->save($authItem);
}
/**
* @inheritdoc
* @throws Exception
* @throws RuntimeException
* @throws InvalidArgumentException
*/
public function setToken(Token $token)
{
parent::setToken($token);
$this->putTokenIntoCache();
return $this;
}
}