Skip to content

Commit

Permalink
Some little more adjustments
Browse files Browse the repository at this point in the history
  • Loading branch information
lennartdohmann committed Dec 16, 2024
1 parent ac30ae0 commit 8b9cdbd
Show file tree
Hide file tree
Showing 7 changed files with 53 additions and 52 deletions.
2 changes: 1 addition & 1 deletion php/examples/VaasExample/GetVerdictByHash.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
->build();


// EICAR
// Malicious hash
$vaasVerdict = $vaas->forSha256Async(Sha256::TryFromString("000005c43196142f01d615a67b7da8a53cb0172f8e9317a2ec9a0a39a1da6fe8"))->await();
fwrite(STDOUT, "Verdict for $vaasVerdict->sha256 is " . $vaasVerdict->verdict->value . " \n");

Expand Down
3 changes: 1 addition & 2 deletions php/src/vaas/Authentication/AuthenticatorInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@
namespace VaasSdk\Authentication;

use Amp\Cancellation;
use Amp\Future;

interface AuthenticatorInterface
{
public function getTokenAsync(?Cancellation $cancellation = null): Future;
public function getTokenAsync(?Cancellation $cancellation = null): string;
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,8 @@
namespace VaasSdk\Authentication;

use Amp\Cancellation;
use Amp\Future;
use Amp\Http\Client\HttpClient;
use VaasSdk\Options\AuthenticationOptions;
use function Amp\async;

class ClientCredentialsGrantAuthenticator implements AuthenticatorInterface
{
Expand Down Expand Up @@ -35,12 +33,10 @@ public function __construct(string $clientId, string $clientSecret, ?string $tok
* If the token is still valid, it will be returned immediately.
* If the token is expired, a new token will be requested.
* @param Cancellation|null $cancellation Cancellation token
* @return Future Future that resolves to the access token string
* @return string The access token string
*/
public function getTokenAsync(?Cancellation $cancellation = null): Future
public function getTokenAsync(?Cancellation $cancellation = null): string
{
return async(function () use ($cancellation) {
return $this->tokenReceiver->getTokenAsync($cancellation)->await();
});
return $this->tokenReceiver->getTokenAsync($cancellation)->await();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,8 @@
namespace VaasSdk\Authentication;

use Amp\Cancellation;
use Amp\Future;
use Amp\Http\Client\HttpClient;
use VaasSdk\Options\AuthenticationOptions;
use function Amp\async;

class ResourceOwnerPasswordGrantAuthenticator implements AuthenticatorInterface
{
Expand Down Expand Up @@ -38,12 +36,10 @@ public function __construct(string $clientId, string $userName, string $password
* If the token is still valid, it will be returned immediately.
* If the token is expired, a new token will be requested.
* @param Cancellation|null $cancellation Cancellation token
* @return Future Future that resolves to the access token string
* @return string The access token string
*/
public function getTokenAsync(?Cancellation $cancellation = null): Future
public function getTokenAsync(?Cancellation $cancellation = null): string
{
return async(function () use ($cancellation) {
return $this->tokenReceiver->getTokenAsync($cancellation)->await();
});
return $this->tokenReceiver->getTokenAsync($cancellation)->await();
}
}
74 changes: 42 additions & 32 deletions php/src/vaas/Vaas.php
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,8 @@ public function forSha256Async(Sha256 $sha256, ?ForSha256Options $options = null
json_encode($options->useHashLookup
));

$request = new Request($url, 'GET');

while (true) {
$request = new Request($url, 'GET');
$this->addRequestHeadersAsync($request, $options->vaasRequestId)->await($cancellation);
$this->logger->debug("Send request for SHA256: " . self::logUri($request));
$response = $this->httpClient->request($request, $cancellation);
Expand Down Expand Up @@ -211,11 +210,9 @@ public function forFileAsync(string $path, ?ForFileOptions $options = null, ?Can
$this->logger->debug("File $path is already known from cache or G DATA cloud by its SHA256: $sha256");
return $response;
}
$this->logger->debug("File $path is not known from cache or G DATA cloud by its SHA256: $sha256");
}

$stream = openFile($path, 'r');
$stream->onClose(fn() => $stream->close());

$forStreamOptions = new ForStreamOptions([
'vaasRequestId' => $options->vaasRequestId,
Expand All @@ -238,32 +235,35 @@ public function forFileAsync(string $path, ?ForFileOptions $options = null, ?Can
public function forStreamAsync(ReadableStream $stream, int $fileSize, ?ForStreamOptions $options = null, ?Cancellation $cancellation = null): Future
{
return async(function () use ($stream, $fileSize, $options, $cancellation) {
$this->logger->debug("Requesting verdict for stream");
try {
$this->logger->debug("Requesting verdict for stream");

if (!$stream->isReadable() || $stream->isClosed()) {
$this->logger->error("Stream is not readable");
throw new VaasClientException('Stream is not readable');
}
if (!$stream->isReadable() || $stream->isClosed()) {
$this->logger->error("Stream is not readable");
throw new VaasClientException('Stream is not readable');
}

if ($options === null) {
$options = new ForStreamOptions(
[
'vaasRequestId' => null,
'timeout' => $this->options->timeout,
'useHashLookup' => $this->options->useHashLookup ?? true,
]
);
}
$url = sprintf('%s/files?useHashLookup=%s', $this->options->vaasUrl, json_encode($options->useHashLookup));
if ($options === null) {
$options = new ForStreamOptions(
[
'vaasRequestId' => null,
'timeout' => $this->options->timeout,
'useHashLookup' => $this->options->useHashLookup ?? true,
]
);
}
$url = sprintf('%s/files?useHashLookup=%s', $this->options->vaasUrl, json_encode($options->useHashLookup));

$request = new Request($url, 'POST');
$request = new Request($url, 'POST');

$request->setBody(StreamedContent::fromStream($stream, $fileSize));
$request->setTransferTimeout($options->timeout);
$this->addRequestHeadersAsync($request, $options->vaasRequestId)->await();
$this->logger->debug("Send request for file stream: " . self::logUri($request));
$response = $this->httpClient->request($request);
$stream->close();
$request->setBody(StreamedContent::fromStream($stream, $fileSize));
$request->setTransferTimeout($options->timeout);
$this->addRequestHeadersAsync($request, $options->vaasRequestId)->await();
$this->logger->debug("Send request for file stream: " . self::logUri($request));
$response = $this->httpClient->request($request);
} finally {
$stream->close();
}
switch ($response->getStatus()) {
case 201:
$fileAnalysisStarted = json_decode($response->getBody()->buffer(), true);
Expand Down Expand Up @@ -310,11 +310,7 @@ public function forUrlAsync(string $uri, ?ForUrlOptions $options = null, ?Cancel
{
return async(function () use ($uri, $options, $cancellation) {
$this->logger->debug("Requesting verdict for URL: $uri");

if (!filter_var($uri, FILTER_VALIDATE_URL)) {
$this->logger->error("Invalid URL: $uri");
throw new VaasClientException('Invalid URL');
}
$uri = Vaas::validUri($uri);

if ($options === null) {
$options = new ForUrlOptions(
Expand Down Expand Up @@ -400,7 +396,7 @@ private function addRequestHeadersAsync(Request $request, ?string $requestId = '
{
return async(function () use ($request, $requestId) {
$this->logger->debug("Add request headers");
$request->setHeader('Authorization', 'Bearer ' . $this->authenticator->getTokenAsync()->await());
$request->setHeader('Authorization', 'Bearer ' . $this->authenticator->getTokenAsync());
$this->logger->debug("Successfully added authorization header with bearer token");
$request->setHeader('User-Agent', sprintf('%s/%s', self::PRODUCT_NAME, self::PRODUCT_VERSION));
if (!empty($requestId)) {
Expand Down Expand Up @@ -453,4 +449,18 @@ private static function logUri(Request $request): string
$fragment = $request->getUri()->getFragment();
return $uri . (!empty($query) ? '?' . $query : '') . (!empty($fragment) ? '#' . $fragment : '');
}

/**
* Validate the URI per RFC 2396 (https://datatracker.ietf.org/doc/html/rfc2396)
* @param string $uri The URI to validate
* @return string The validated URI
* @throws VaasClientException If the URI is invalid
*/
private static function validUri(string $uri): string
{
if (!filter_var($uri, FILTER_VALIDATE_URL)) {
throw new VaasClientException('Invalid URI');
}
return $uri;
}
}
4 changes: 2 additions & 2 deletions php/tests/VaasTesting/AuthenticatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public function testClientCredentialsGrantAuthenticator_withValidCredentials_Ret
tokenUrl: $_ENV["TOKEN_URL"]
);

$token = $authenticator->getTokenAsync()->await();
$token = $authenticator->getTokenAsync();

$this->assertNotNull($token);
}
Expand All @@ -93,7 +93,7 @@ public function testResourceOwnerPasswordGrantAuthenticator_withValidCredentials
tokenUrl: $_ENV["TOKEN_URL"]
);

$token = $authenticator->getTokenAsync()->await();
$token = $authenticator->getTokenAsync();

$this->assertNotNull($token);
}
Expand Down
2 changes: 1 addition & 1 deletion php/tests/VaasTesting/VaasTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ public function testForUrl_WithCleanUrl_GetsCleanResponse(): void
public function testForUrl_WithInvalidUrl_ThrowsVaasClientException(): void
{
$this->expectException(VaasClientException::class);
$this->expectExceptionMessage("Invalid URL");
$this->expectExceptionMessage("Invalid URI");

$this->vaas->forUrlAsync("invalid")->await();
}
Expand Down

0 comments on commit 8b9cdbd

Please sign in to comment.