From 230fd4acbf91e4c1c75fff73b37d49006975da6c Mon Sep 17 00:00:00 2001 From: Tom Udding Date: Sat, 24 Aug 2024 22:00:56 +0200 Subject: [PATCH] feat: check GEWISDB API to ensure it is safe to sync --- .env.dist | 4 ++++ importdb.php | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 66 insertions(+), 1 deletion(-) diff --git a/.env.dist b/.env.dist index d25e1dbd1f..5ebd7439a8 100644 --- a/.env.dist +++ b/.env.dist @@ -42,6 +42,10 @@ MH_SMTP_BIND_ADDR=0.0.0.0:25 # Settings for Pwned Passwords API to check if passwords are present in known breaches PWNED_PASSWORDS_HOST=https://pwned-passwords.gewis.nl/api +# Settings for GEWISDB API health check +GEWISDB_API_HOST=https://database.test.gewis.nl/api +GEWISDB_API_KEY='thiskeyisnotvalid' + # Google Calendar API (Option Calendar) settings DOCKER_GOOGLE_API_KEY=unknown DOCKER_GOOGLE_CALENDAR_KEY=unknown diff --git a/importdb.php b/importdb.php index 3fa2cbe561..d494beeec9 100644 --- a/importdb.php +++ b/importdb.php @@ -8,6 +8,68 @@ * It is a simple PostgreSQL to MySQL copy script. */ +$apiKey = getenv('GEWISDB_API_KEY'); +$apiHost = getenv('GEWISDB_API_HOST'); + +if ( + false === $apiKey + || false === $apiHost +) { + echo 'API: no sync, environment variables are not set properly...' . PHP_EOL; + exit(1); +} + +$ch = curl_init(); + +$headers = [ + sprintf('Authorization: Bearer %s', $apiKey), +]; + +curl_setopt($ch, CURLOPT_URL, $apiHost . '/health'); +curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); +curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); +curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); + +$response = curl_exec($ch); + +if (false === $response) { + echo 'API: no sync, unexpected cURL error...' . PHP_EOL; + curl_close($ch); + exit(1); +} + +$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + +if ( + 200 === $httpCode + || 403 === $httpCode +) { + if (!json_validate($response)) { + echo 'API: no sync, invalid JSON returned...' . PHP_EOL; + curl_close($ch); + exit(1); + } + + $health = json_decode($response, true); + + if ( + $health['healthy'] + && !$health['sync_paused'] + ) { + echo 'API: sync, healthy and syncs are allowed...' . PHP_EOL; + } else { + echo 'API: no sync, sync is paused or API is not healthy...' . PHP_EOL; + curl_close($ch); + exit(1); + } +} else { + echo 'API: no sync, unexpected response...' . PHP_EOL; + curl_close($ch); + exit(1); +} + +curl_close($ch); + echo 'Commencing sync with GEWISDB...' . PHP_EOL; try { @@ -182,7 +244,6 @@ function ($a) use ($i) { /** * Removing old data */ - // Tables without primary keys are skipped if (0 === count($pks[$table])) continue;