-
Notifications
You must be signed in to change notification settings - Fork 0
/
Vaas.php
386 lines (347 loc) · 13.2 KB
/
Vaas.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
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
<?php
namespace VaasSdk;
use Amp\ByteStream\ReadableStream;
use Amp\CompositeCancellation;
use Amp\DeferredCancellation;
use Amp\DeferredFuture;
use Amp\Http\Client\HttpClient;
use Amp\Http\Client\HttpClientBuilder;
use Amp\Http\Client\HttpException;
use Amp\Http\Client\Request;
use Amp\Http\Client\StreamedContent;
use Amp\TimeoutCancellation;
use InvalidArgumentException;
use JsonMapper_Exception;
use Ramsey\Uuid\Rfc4122\UuidV4;
use VaasSdk\Exceptions\TimeoutException;
use VaasSdk\Exceptions\UploadFailedException;
use VaasSdk\Exceptions\VaasInvalidStateException;
use VaasSdk\Exceptions\VaasServerException;
use VaasSdk\Message\Verdict;
use VaasSdk\Message\VerdictRequest;
use VaasSdk\Message\VerdictRequestForStream;
use VaasSdk\Message\VerdictResponse;
use VaasSdk\Message\VerdictRequestForUrl;
use VaasSdk\VaasOptions;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Revolt\EventLoop;
use VaasSdk\Authentication\AuthenticatorInterface;
use VaasSdk\Exceptions\VaasClientException;
use VaasSdk\Message\VaasVerdict;
use WebSocket\BadOpcodeException;
class Vaas
{
private VaasConnection $vaasConnection;
private int $uploadTimeoutInSeconds = 600;
private VaasOptions $options;
private HttpClient $httpClient;
private ?AuthenticatorInterface $authenticator = null;
private ?LoggerInterface $logger;
private ?string $vaasUrl = "wss://gateway.production.vaas.gdatasecurity.de";
public function __destruct() {
if (isset($this->vaasConnection)) {
$this->vaasConnection->close();
}
}
public function withOptions(VaasOptions $options): self
{
$this->options = $options;
return $this;
}
public function withHtttpClient(HttpClient $httpClient): self
{
$this->httpClient = $httpClient;
return $this;
}
public function withAuthenticator(AuthenticatorInterface $authenticator): self
{
$this->authenticator = $authenticator;
return $this;
}
public function withLogger(LoggerInterface $logger): self
{
$this->logger = $logger;
return $this;
}
public function withUrl(string $vaasUrl): self
{
$this->vaasUrl = $vaasUrl;
return $this;
}
public function withVaasConnection(VaasConnection $vaasConnection): self
{
$this->vaasConnection = $vaasConnection;
return $this;
}
public function build(): self
{
if (!isset($this->logger)) {
$this->logger = new NullLogger();
}
if (!isset($this->vaasConnection) && isset($this->authenticator)) {
$this->vaasConnection = (new VaasConnection())
->withAuthenticator($this->authenticator)
->withUrl($this->vaasUrl)
->withLogger($this->logger)
->build();
} else if (!isset($this->vaasConnection)) {
$this->vaasConnection = (new VaasConnection())
->withUrl($this->vaasUrl)
->withLogger($this->logger)
->build();
}
if (!isset($this->options)) {
$this->options = new VaasOptions();
}
if (!isset($this->httpClient)) {
$this->httpClient = HttpClientBuilder::buildDefault();
}
return $this;
}
public function Connect(string $token = "") {
if (!isset($this->vaasConnection)) {
throw new VaasInvalidStateException("No VaasConnection given and build() was not called");
}
$this->vaasConnection->Connect($token);
}
/**
* Gets verdict by hashstring
*
* @param string $hashString the hash to get the verdict for
* @param string $uuid unique identifier
*
* @throws Exceptions\InvalidSha256Exception
* @throws Exceptions\TimeoutException
*
* @return VaasVerdict the verdict
*/
public function ForSha256(string $hashString, string $uuid = null): VaasVerdict {
$this->logger->debug("ForSha256WithFlags", ["Sha256" => $hashString]);
$sha256 = Sha256::TryFromString($hashString);
return new VaasVerdict(
$this->_verdictResponseForSha256(
$sha256,
$uuid
)
);
}
/**
* Gets verdict by url
*
* @param string|null $url url to get the verdict for
* @param string|null $uuid unique identifier
*
* @return VaasVerdict the verdict
*
* @throws TimeoutException
* @throws InvalidArgumentException
*/
public function ForUrl(?string $url, string $uuid = null): VaasVerdict
{
$this->logger->debug("ForUrlWithFlags", ["URL:" => $url]);
if (!filter_var($url, FILTER_VALIDATE_URL)) {
throw new \InvalidArgumentException("Url is not valid");
}
return new VaasVerdict($this->_verdictResponseForUrl(
$url,
$uuid
));
}
/**
* Gets verdict by file
*
* @param string $path the path to get the verdict for
* @param bool $upload should the file be uploaded if initial verdict is unknown
* @param string $uuid unique identifier
*
* @throws Exceptions\TimeoutException
* @throws Exceptions\FileDoesNotExistException
* @throws Exceptions\InvalidSha256Exception
* @throws Exceptions\UploadFailedException
*
* @return VaasVerdict the verdict
*/
public function ForFile(string $path, $upload = true, string $uuid = null): VaasVerdict
{
$this->logger->debug("ForFileWithFlags", ["File" => $path]);
$sha256 = Sha256::TryFromFile($path);
$this->logger->debug("Calculated Hash", ["Sha256" => $sha256]);
$verdictResponse = $this->_verdictResponseForSha256(
$sha256,
$uuid
);
if ($verdictResponse->verdict == Verdict::UNKNOWN && $upload === true) {
$this->logger->debug("UploadToken", ["UploadToken" => $verdictResponse->upload_token]);
$fileStream = \Amp\File\openFile($path, 'r');
$fileSize = \filesize($path);
$verdict = new VaasVerdict(
$this->UploadStream(
$fileStream,
$verdictResponse->url,
$verdictResponse->upload_token,
$fileSize,
$verdictResponse->guid)
);
$fileStream->close();
return $verdict;
}
return new VaasVerdict($verdictResponse);
}
/**
* Gets verdict by stream
*
* @param ReadableStream $stream the path to get the verdict for
* @param bool $upload should the file be uploaded if initial verdict is unknown
* @param string $uuid unique identifier
*
* @throws JsonMapper_Exception
* @throws VaasClientException
* @throws TimeoutException
* @throws VaasServerException
* @throws BadOpcodeException
* @throws VaasInvalidStateException
* @throws UploadFailedException
*/
public function ForStream(ReadableStream $stream, int $size = 0, string $uuid = null): VaasVerdict
{
$this->logger->debug("uuid: ".var_export($uuid, true));
$uuid = $uuid ?? UuidV4::getFactory()->uuid4()->toString();
$this->logger->debug("uuid: ".var_export($uuid, true));
$verdictResponse = $this->_verdictResponseForStream($uuid);
if ($verdictResponse->verdict != Verdict::UNKNOWN) {
throw new VaasServerException("Server returned verdict without receiving content.");
}
if ($verdictResponse->upload_token == null || $verdictResponse->upload_token == "") {
throw new JsonMapper_Exception("VerdictResponse missing UploadToken for stream upload.");
}
if ($verdictResponse->url == null || $verdictResponse->url == "") {
throw new JsonMapper_Exception("VerdictResponse missing URL for stream upload.");
}
return new VaasVerdict(
$this->UploadStream(
$stream,
$verdictResponse->url,
$verdictResponse->upload_token,
$size,
$uuid)
);
}
/**
* @throws TimeoutException
*
* @return VerdictResponse
*/
private function _verdictResponseForSha256(Sha256 $sha256, string $uuid = null): VerdictResponse
{
$this->logger->debug("_verdictResponseForSha256");
if (!isset($this->vaasConnection->SessionId)) {
throw new VaasInvalidStateException("No Authenticator given and connect() was not called");
}
$request = new VerdictRequest(strtolower($sha256), $uuid, $this->vaasConnection->SessionId);
$request->use_cache = $this->options->UseCache;
$request->use_hash_lookup = $this->options->UseHashLookup;
return $this->vaasConnection->SendRequest(json_encode($request), $request->guid)->await();
}
/**
* @throws TimeoutException
*
* @return VerdictResponse
*/
private function _verdictResponseForUrl(string $url, string $uuid = null): VerdictResponse
{
$this->logger->debug("_verdictResponseForUrl");
if (!isset($this->vaasConnection->SessionId)) {
throw new VaasInvalidStateException("No Authenticator given and connect() was not called");
}
$request = new VerdictRequestForUrl($url, $uuid, $this->vaasConnection->SessionId);
$request->use_cache = $this->options->UseCache;
$request->use_hash_lookup = $this->options->UseHashLookup;
return $this->vaasConnection->SendRequest(json_encode($request), $request->guid)->await();
}
/**
* @throws JsonMapper_Exception
* @throws VaasClientException
* @throws TimeoutException
* @throws VaasServerException
* @throws BadOpcodeException
* @throws VaasInvalidStateException
*/
private function _verdictResponseForStream(string $uuid = null): VerdictResponse
{
$this->logger->debug("_verdictResponseForStream");
if (!isset($this->vaasConnection->SessionId)) {
throw new VaasInvalidStateException("No Authenticator given and connect() was not called");
}
$request = new VerdictRequestForStream($this->vaasConnection->SessionId, $uuid);
$request->use_cache = $this->options->UseCache;
$request->use_hash_lookup = $this->options->UseHashLookup;
return $this->vaasConnection->SendRequest(json_encode($request), $request->guid)->await();
}
/**
* Sets the timeout in seconds the websocket client can take for one receive
*
* @param int $timeoutInSeconds timeout for the websocket
*
* @return void
*/
public function setWebsocketTimeOut(int $timeoutInSeconds): void
{
$this->vaasConnection->setTimeout($timeoutInSeconds);
}
/**
* Set the timeout for the httpclient (for the upload) in seconds
*
* @param int $UploadTimeoutInSeconds upload timeout
*
* @return Vaas
*/
public function setUploadTimeout(int $UploadTimeoutInSeconds): self
{
$this->uploadTimeoutInSeconds = $UploadTimeoutInSeconds;
return $this;
}
private function UploadStream(
ReadableStream $fileStream,
string $url, string $uploadToken, int $fileSize,
string $requestId): VerdictResponse
{
$cancellation = new DeferredCancellation();
$times = 0;
$pingTimer = EventLoop::repeat(5, function () use(&$times) {
$this->logger->debug("pinging " . $times++);
$websocket = $this->vaasConnection->GetAuthenticatedWebsocket();
$websocket->ping();
});
$futureResponse = $this->vaasConnection->GetResponse($requestId);
try {
$request = new Request($url, 'PUT');
$request->setProtocolVersions(["1.1"]);
$request->setTransferTimeout($this->uploadTimeoutInSeconds);
$request->setBody(StreamedContent::fromStream($fileStream, $fileSize));
$request->addHeader("Content-Length", $fileSize);
$request->addHeader("Authorization", $uploadToken);
$timeoutCancellation = new TimeoutCancellation($this->uploadTimeoutInSeconds);
$response = $this->httpClient->request($request,
new CompositeCancellation($timeoutCancellation, $cancellation->getCancellation()));
if ($response->getStatus() > 399) {
$reason = $response->getBody()->buffer($cancellation->getCancellation());
throw new UploadFailedException($reason, $response->getStatus());
}
} catch (\Exception $e) {
$this->vaasConnection->RemoveResponse($requestId);
if ($e instanceof HttpException) {
$uploadFailedException = new UploadFailedException($e->getMessage(), $e->getCode());
$futureResponse->getFuture()->error($uploadFailedException);
throw new $uploadFailedException;
}
$vaasClientException = new VaasClientException($e->getMessage());
$futureResponse->getFuture()->error($vaasClientException);
throw $vaasClientException;
} finally {
EventLoop::cancel($pingTimer);
$cancellation->cancel();
return $futureResponse->getFuture()->await();
}
}
}