From 6768c03b3d8cc2dffa5c6e74136ff8948cc49bae Mon Sep 17 00:00:00 2001
From: Christoph Reiter <reiter.christoph@gmail.com>
Date: Wed, 9 Feb 2022 14:17:05 +0100
Subject: [PATCH] Add a health check for local validation

Checks that the OID config can be fetched and the public key
for token validation.
---
 src/Resources/config/services.yaml |  4 ++
 src/Service/HealthCheck.php        | 59 ++++++++++++++++++++++++++++++
 2 files changed, 63 insertions(+)
 create mode 100644 src/Service/HealthCheck.php

diff --git a/src/Resources/config/services.yaml b/src/Resources/config/services.yaml
index 9487916..3ad8b15 100644
--- a/src/Resources/config/services.yaml
+++ b/src/Resources/config/services.yaml
@@ -28,5 +28,9 @@ services:
     autowire: true
     autoconfigure: true
 
+  Dbp\Relay\AuthBundle\Service\HealthCheck:
+    autowire: true
+    autoconfigure: true
+
   Dbp\Relay\AuthBundle\API\UserRolesInterface:
     '@Dbp\Relay\AuthBundle\Service\DefaultUserRoles'
\ No newline at end of file
diff --git a/src/Service/HealthCheck.php b/src/Service/HealthCheck.php
new file mode 100644
index 0000000..29e6c39
--- /dev/null
+++ b/src/Service/HealthCheck.php
@@ -0,0 +1,59 @@
+<?php
+
+declare(strict_types=1);
+
+namespace Dbp\Relay\AuthBundle\Service;
+
+use Dbp\Relay\AuthBundle\OIDC\OIDProvider;
+use Dbp\Relay\CoreBundle\HealthCheck\CheckInterface;
+use Dbp\Relay\CoreBundle\HealthCheck\CheckOptions;
+use Dbp\Relay\CoreBundle\HealthCheck\CheckResult;
+
+class HealthCheck implements CheckInterface
+{
+    private $provider;
+
+    public function __construct(OIDProvider $provider)
+    {
+        $this->provider = $provider;
+    }
+
+    public function getName(): string
+    {
+        return 'auth';
+    }
+
+    private function checkMethod(string $description, callable $func): CheckResult
+    {
+        $result = new CheckResult($description);
+        try {
+            $func();
+        } catch (\Throwable $e) {
+            $result->set(CheckResult::STATUS_FAILURE, $e->getMessage(), ['exception' => $e]);
+
+            return $result;
+        }
+        $result->set(CheckResult::STATUS_SUCCESS);
+
+        return $result;
+    }
+
+    public function checkConfig()
+    {
+        $this->provider->getProviderConfig();
+    }
+
+    public function checkPublicKey()
+    {
+        $this->provider->getJWKs();
+    }
+
+    public function check(CheckOptions $options): array
+    {
+        $results = [];
+        $results[] = $this->checkMethod('Check if the OIDC config can be fetched', [$this, 'checkConfig']);
+        $results[] = $this->checkMethod('Check if the OIDC public key can be fetched', [$this, 'checkPublicKey']);
+
+        return $results;
+    }
+}
-- 
GitLab