appwrite/tests/unit/Auth/KeyTest.php

62 lines
1.7 KiB
PHP
Raw Normal View History

2025-02-11 09:02:20 +00:00
<?php
namespace Tests\Unit\Auth;
use Ahc\Jwt\JWT;
use Appwrite\Auth\Key;
2025-11-04 07:51:03 +00:00
use Appwrite\Utopia\Database\Documents\User;
2025-02-11 09:02:20 +00:00
use PHPUnit\Framework\TestCase;
use Utopia\Config\Config;
use Utopia\Database\Document;
use Utopia\System\System;
2025-12-27 18:18:25 +00:00
// TODO: Check diff of Key.php, and update unit tests accordingly
2025-02-11 09:02:20 +00:00
class KeyTest extends TestCase
{
public function testDecode(): void
{
$projectId = 'test';
$usage = false;
$scopes = [
'databases.read',
'collections.read',
'documents.read',
];
2025-11-04 07:51:03 +00:00
$roleScopes = Config::getParam('roles', [])[User::ROLE_APPS]['scopes'];
2025-02-11 09:02:20 +00:00
$key = static::generateKey($projectId, $usage, $scopes);
2025-12-23 14:12:41 +00:00
$decoded = Key::decode(
project: new Document(['$id' => $projectId]),
team: new Document(),
user: new Document(),
key: $key,
);
2025-02-11 09:02:20 +00:00
$this->assertEquals($projectId, $decoded->getProjectId());
$this->assertEquals(API_KEY_DYNAMIC, $decoded->getType());
2025-11-04 07:51:03 +00:00
$this->assertEquals(User::ROLE_APPS, $decoded->getRole());
2025-02-11 09:02:20 +00:00
$this->assertEquals(\array_merge($scopes, $roleScopes), $decoded->getScopes());
}
private static function generateKey(
string $projectId,
bool $usage,
array $scopes,
2025-02-11 09:04:52 +00:00
): string {
2025-02-11 09:02:20 +00:00
$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;
}
2025-02-11 09:04:52 +00:00
}