mirror of
https://github.com/appwrite/appwrite.git
synced 2026-05-26 13:51:13 +00:00
Add unit test
This commit is contained in:
@@ -52,6 +52,15 @@ class Key
|
||||
return $this->usage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode the given secret key into a Key object, containing the project ID, type, role, scopes, and name.
|
||||
* Can be a stored API key or a dynamic key (JWT).
|
||||
*
|
||||
* @param Document $project
|
||||
* @param string $key
|
||||
* @return Key
|
||||
* @throws Exception
|
||||
*/
|
||||
public static function decode(
|
||||
Document $project,
|
||||
string $key
|
||||
|
||||
@@ -193,6 +193,7 @@ class Migrations extends Action
|
||||
protected function generateAPIKey(Document $project): string
|
||||
{
|
||||
$jwt = new JWT(System::getEnv('_APP_OPENSSL_KEY_V1'), 'HS256', 86400, 0);
|
||||
|
||||
$apiKey = $jwt->encode([
|
||||
'projectId' => $project->getId(),
|
||||
'usage' => false,
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Auth;
|
||||
|
||||
use Ahc\Jwt\JWT;
|
||||
use Appwrite\Auth\Auth;
|
||||
use Appwrite\Auth\Key;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Utopia\Config\Config;
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\System\System;
|
||||
|
||||
class KeyTest extends TestCase
|
||||
{
|
||||
public function testDecode(): void
|
||||
{
|
||||
$projectId = 'test';
|
||||
$usage = false;
|
||||
$scopes = [
|
||||
'databases.read',
|
||||
'collections.read',
|
||||
'documents.read',
|
||||
];
|
||||
$roleScopes = Config::getParam('roles', [])[Auth::USER_ROLE_APPS]['scopes'];
|
||||
|
||||
$key = static::generateKey($projectId, $usage, $scopes);
|
||||
$project = new Document(['$id' => $projectId,]);
|
||||
$decoded = Key::decode($project, $key);
|
||||
|
||||
$this->assertEquals($projectId, $decoded->getProjectId());
|
||||
$this->assertEquals(API_KEY_DYNAMIC, $decoded->getType());
|
||||
$this->assertEquals(Auth::USER_ROLE_APPS, $decoded->getRole());
|
||||
$this->assertEquals(\array_merge($scopes, $roleScopes), $decoded->getScopes());
|
||||
}
|
||||
|
||||
private static function generateKey(
|
||||
string $projectId,
|
||||
bool $usage,
|
||||
array $scopes,
|
||||
): string
|
||||
{
|
||||
$jwt = new JWT(
|
||||
key: System::getEnv('_APP_OPENSSL_KEY_V1'),
|
||||
algo: 'HS256',
|
||||
maxAge: 86400,
|
||||
leeway: 0,
|
||||
);
|
||||
|
||||
$apiKey = $jwt->encode([
|
||||
'projectId' => $projectId,
|
||||
'usage' => $usage,
|
||||
'scopes' => $scopes,
|
||||
]);
|
||||
|
||||
return API_KEY_DYNAMIC . '_' . $apiKey;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user