From 5b0cc3672b56ca5f8c4225d2097d2bf115190dd3 Mon Sep 17 00:00:00 2001 From: Jens L Date: Thu, 25 May 2023 18:52:21 +0200 Subject: [PATCH] root: add method to get install_id without django being loaded (#5755) Signed-off-by: Jens Langhammer --- authentik/root/install_id.py | 28 ++++++++++++++++++++++++++-- lifecycle/gunicorn.conf.py | 4 ++-- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/authentik/root/install_id.py b/authentik/root/install_id.py index 415cd0664..a77e7b9ac 100644 --- a/authentik/root/install_id.py +++ b/authentik/root/install_id.py @@ -2,16 +2,40 @@ from functools import lru_cache from uuid import uuid4 -from django.conf import settings -from django.db import connection +from psycopg2 import connect + +from authentik.lib.config import CONFIG @lru_cache def get_install_id() -> str: """Get install ID of this instance. The method is cached as the install ID is not expected to change""" + from django.conf import settings + from django.db import connection + if settings.TEST: return str(uuid4()) with connection.cursor() as cursor: cursor.execute("SELECT id FROM authentik_install_id LIMIT 1;") return cursor.fetchone()[0] + + +@lru_cache +def get_install_id_raw(): + """Get install_id without django loaded, this is required for the startup when we get + the install_id but django isn't loaded yet and we can't use the function above.""" + conn = connect( + dbname=CONFIG.y("postgresql.name"), + user=CONFIG.y("postgresql.user"), + password=CONFIG.y("postgresql.password"), + host=CONFIG.y("postgresql.host"), + port=int(CONFIG.y("postgresql.port")), + sslmode=CONFIG.y("postgresql.sslmode"), + sslrootcert=CONFIG.y("postgresql.sslrootcert"), + sslcert=CONFIG.y("postgresql.sslcert"), + sslkey=CONFIG.y("postgresql.sslkey"), + ) + cursor = conn.cursor() + cursor.execute("SELECT id FROM authentik_install_id LIMIT 1;") + return cursor.fetchone()[0] diff --git a/lifecycle/gunicorn.conf.py b/lifecycle/gunicorn.conf.py index ccf80ffb4..641e23528 100644 --- a/lifecycle/gunicorn.conf.py +++ b/lifecycle/gunicorn.conf.py @@ -15,7 +15,7 @@ from authentik import get_full_version from authentik.lib.config import CONFIG from authentik.lib.utils.http import get_http_session from authentik.lib.utils.reflection import get_env -from authentik.root.install_id import get_install_id +from authentik.root.install_id import get_install_id_raw from lifecycle.worker import DjangoUvicornWorker if TYPE_CHECKING: @@ -149,7 +149,7 @@ if not CONFIG.y_bool("disable_startup_analytics", False): ), }, headers={ - "User-Agent": sha512(get_install_id().encode("ascii")).hexdigest()[:16], + "User-Agent": sha512(get_install_id_raw().encode("ascii")).hexdigest()[:16], "Content-Type": "application/json", }, timeout=5,