From 2111e1769fe1e5b0371ba7176d2ec054341e73cc Mon Sep 17 00:00:00 2001 From: ErickSkrauch Date: Fri, 14 Jun 2024 04:36:49 +0200 Subject: [PATCH] Introduce an API endpoint to obtain public keys, that can be used to verify access tokens on other services --- api/components/Tokens/Component.php | 4 +++ api/controllers/PublicKeysController.php | 35 ++++++++++++++++++++++++ api/tests/functional/PublicKeysCest.php | 23 ++++++++++++++++ 3 files changed, 62 insertions(+) create mode 100644 api/controllers/PublicKeysController.php create mode 100644 api/tests/functional/PublicKeysCest.php diff --git a/api/components/Tokens/Component.php b/api/components/Tokens/Component.php index c617eaa..1483d13 100644 --- a/api/components/Tokens/Component.php +++ b/api/components/Tokens/Component.php @@ -108,6 +108,10 @@ class Component extends BaseComponent { return $rawValue; } + public function getPublicKey(): string { + return $this->getAlgorithmManager()->get(self::PREFERRED_ALGORITHM)->getPublicKey()->getContent(); + } + private function getAlgorithmManager(): AlgorithmsManager { if ($this->algorithmManager === null) { $this->algorithmManager = new AlgorithmsManager([ diff --git a/api/controllers/PublicKeysController.php b/api/controllers/PublicKeysController.php new file mode 100644 index 0000000..2a43027 --- /dev/null +++ b/api/controllers/PublicKeysController.php @@ -0,0 +1,35 @@ + [ + 'class' => NginxCache::class, + 'rules' => [ + 'index' => 3600, // 1h + ], + ], + ]); + } + + public function actionIndex(): array { + return [ + 'keys' => [ + [ + 'alg' => 'ES256', // Hardcoded for awhile since right now there is no way to find used algo + 'pem' => Yii::$app->tokens->getPublicKey(), + ], + ], + ]; + } + +} diff --git a/api/tests/functional/PublicKeysCest.php b/api/tests/functional/PublicKeysCest.php new file mode 100644 index 0000000..5370752 --- /dev/null +++ b/api/tests/functional/PublicKeysCest.php @@ -0,0 +1,23 @@ +sendGet('/api/public-keys'); + $I->canSeeResponseCodeIs(200); + $I->canSeeResponseContainsJson([ + 'keys' => [ + [ + 'alg' => 'ES256', + 'pem' => "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAES2Pyq9r0CyyviLaWwq0ki5uy8hr/\nZbNO++3j4XP43uLD9/GYkrKGIRl+Hu5HT+LwZvrFcEaVhPk5CvtV4zlYJg==\n-----END PUBLIC KEY-----\n", + ], + ], + ]); + } + +}