authentik.root.db.base
authentik database backend
1"""authentik database backend""" 2 3from django.core.checks import Warning 4from django.db.backends.base.validation import BaseDatabaseValidation 5from django.db.backends.postgresql.schema import DatabaseSchemaEditor as PostgresSchemaEditor 6from django_prometheus.db.backends.postgresql.base import DatabaseWrapper as BaseDatabaseWrapper 7 8from authentik.lib.config import CONFIG, DIRECT_DB_ALIAS 9 10ENCODING_DOCS_URL = "https://docs.goauthentik.io/install-config/configuration/#postgresql-settings" 11 12 13class DatabaseSchemaEditor(PostgresSchemaEditor): 14 # Workaround for https://github.com/AmbitionEng/django-pgtrigger/issues/222 15 def execute(self, sql, params=()): 16 schema = CONFIG.get("postgresql.default_schema") 17 pgtrigger_public_ignore_func = '"public"._pgtrigger_should_ignore' 18 if schema != "public" and isinstance(sql, str) and pgtrigger_public_ignore_func in sql: 19 sql = sql.replace(pgtrigger_public_ignore_func, f'"{schema}"._pgtrigger_should_ignore') 20 return super().execute(sql, params) 21 22 23class DatabaseValidation(BaseDatabaseValidation): 24 25 def check(self, **kwargs): 26 return self._check_encoding() 27 28 def _check_encoding(self): 29 """Throw a warning when the server_encoding is not UTF-8 or 30 server_encoding and client_encoding are mismatched""" 31 messages = [] 32 with self.connection.cursor() as cursor: 33 cursor.execute("SHOW server_encoding;") 34 server_encoding = cursor.fetchone()[0] 35 cursor.execute("SHOW client_encoding;") 36 client_encoding = cursor.fetchone()[0] 37 if server_encoding != client_encoding: 38 messages.append( 39 Warning( 40 "PostgreSQL Server and Client encoding are mismatched: Server: " 41 f"{server_encoding}, Client: {client_encoding}", 42 id="ak.db.W001", 43 ) 44 ) 45 if server_encoding != "UTF8": 46 messages.append( 47 Warning( 48 f"PostgreSQL Server encoding is not UTF8: {server_encoding}", 49 hint="Dump the database, re-create it with `ENCODING 'UTF8'` " 50 f"and restore the dump. See {ENCODING_DOCS_URL}", 51 id="ak.db.W002", 52 ) 53 ) 54 return messages 55 56 57class DatabaseWrapper(BaseDatabaseWrapper): 58 """database backend which supports rotating credentials""" 59 60 validation_class = DatabaseValidation 61 SchemaEditorClass = DatabaseSchemaEditor 62 63 @property 64 def schema_name(self) -> str: 65 return CONFIG.get("postgresql.default_schema") 66 67 def get_connection_params(self): 68 """Refresh host/port/user/password from CONFIG on each connection open. 69 70 Supports file-mounted secrets rotating without a process restart. Uses 71 the alias-specific prefix (``postgresql.read_replicas.<name>.*`` or 72 ``postgresql.direct.*``) when applicable, falling back to 73 ``postgresql.*`` for unset keys. OPTIONS (sslmode etc.) is unchanged. 74 """ 75 conn_params = super().get_connection_params() 76 77 prefix = "postgresql" 78 if self.alias.startswith("replica_"): 79 prefix = f"postgresql.read_replicas.{self.alias.removeprefix('replica_')}" 80 elif self.alias == DIRECT_DB_ALIAS: 81 prefix = "postgresql.direct" 82 83 for setting in ("host", "port", "user", "password"): 84 conn_params[setting] = CONFIG.refresh(f"{prefix}.{setting}") 85 if conn_params[setting] is None and prefix != "postgresql": 86 conn_params[setting] = CONFIG.refresh(f"postgresql.{setting}") 87 88 return conn_params
ENCODING_DOCS_URL =
'https://docs.goauthentik.io/install-config/configuration/#postgresql-settings'
class
DatabaseSchemaEditor(django.db.backends.postgresql.schema.DatabaseSchemaEditor):
14class DatabaseSchemaEditor(PostgresSchemaEditor): 15 # Workaround for https://github.com/AmbitionEng/django-pgtrigger/issues/222 16 def execute(self, sql, params=()): 17 schema = CONFIG.get("postgresql.default_schema") 18 pgtrigger_public_ignore_func = '"public"._pgtrigger_should_ignore' 19 if schema != "public" and isinstance(sql, str) and pgtrigger_public_ignore_func in sql: 20 sql = sql.replace(pgtrigger_public_ignore_func, f'"{schema}"._pgtrigger_should_ignore') 21 return super().execute(sql, params)
This class and its subclasses are responsible for emitting schema-changing statements to the databases - model creation/removal/alteration, field renaming, index fiddling, and so on.
def
execute(self, sql, params=()):
16 def execute(self, sql, params=()): 17 schema = CONFIG.get("postgresql.default_schema") 18 pgtrigger_public_ignore_func = '"public"._pgtrigger_should_ignore' 19 if schema != "public" and isinstance(sql, str) and pgtrigger_public_ignore_func in sql: 20 sql = sql.replace(pgtrigger_public_ignore_func, f'"{schema}"._pgtrigger_should_ignore') 21 return super().execute(sql, params)
Execute the given SQL statement, with optional parameters.
class
DatabaseValidation(django.db.backends.base.validation.BaseDatabaseValidation):
24class DatabaseValidation(BaseDatabaseValidation): 25 26 def check(self, **kwargs): 27 return self._check_encoding() 28 29 def _check_encoding(self): 30 """Throw a warning when the server_encoding is not UTF-8 or 31 server_encoding and client_encoding are mismatched""" 32 messages = [] 33 with self.connection.cursor() as cursor: 34 cursor.execute("SHOW server_encoding;") 35 server_encoding = cursor.fetchone()[0] 36 cursor.execute("SHOW client_encoding;") 37 client_encoding = cursor.fetchone()[0] 38 if server_encoding != client_encoding: 39 messages.append( 40 Warning( 41 "PostgreSQL Server and Client encoding are mismatched: Server: " 42 f"{server_encoding}, Client: {client_encoding}", 43 id="ak.db.W001", 44 ) 45 ) 46 if server_encoding != "UTF8": 47 messages.append( 48 Warning( 49 f"PostgreSQL Server encoding is not UTF8: {server_encoding}", 50 hint="Dump the database, re-create it with `ENCODING 'UTF8'` " 51 f"and restore the dump. See {ENCODING_DOCS_URL}", 52 id="ak.db.W002", 53 ) 54 ) 55 return messages
Encapsulate backend-specific validation.
class
DatabaseWrapper(django_prometheus.db.backends.postgresql.base.DatabaseWrapper):
58class DatabaseWrapper(BaseDatabaseWrapper): 59 """database backend which supports rotating credentials""" 60 61 validation_class = DatabaseValidation 62 SchemaEditorClass = DatabaseSchemaEditor 63 64 @property 65 def schema_name(self) -> str: 66 return CONFIG.get("postgresql.default_schema") 67 68 def get_connection_params(self): 69 """Refresh host/port/user/password from CONFIG on each connection open. 70 71 Supports file-mounted secrets rotating without a process restart. Uses 72 the alias-specific prefix (``postgresql.read_replicas.<name>.*`` or 73 ``postgresql.direct.*``) when applicable, falling back to 74 ``postgresql.*`` for unset keys. OPTIONS (sslmode etc.) is unchanged. 75 """ 76 conn_params = super().get_connection_params() 77 78 prefix = "postgresql" 79 if self.alias.startswith("replica_"): 80 prefix = f"postgresql.read_replicas.{self.alias.removeprefix('replica_')}" 81 elif self.alias == DIRECT_DB_ALIAS: 82 prefix = "postgresql.direct" 83 84 for setting in ("host", "port", "user", "password"): 85 conn_params[setting] = CONFIG.refresh(f"{prefix}.{setting}") 86 if conn_params[setting] is None and prefix != "postgresql": 87 conn_params[setting] = CONFIG.refresh(f"postgresql.{setting}") 88 89 return conn_params
database backend which supports rotating credentials
validation_class =
<class 'DatabaseValidation'>
SchemaEditorClass =
<class 'DatabaseSchemaEditor'>
def
get_connection_params(self):
68 def get_connection_params(self): 69 """Refresh host/port/user/password from CONFIG on each connection open. 70 71 Supports file-mounted secrets rotating without a process restart. Uses 72 the alias-specific prefix (``postgresql.read_replicas.<name>.*`` or 73 ``postgresql.direct.*``) when applicable, falling back to 74 ``postgresql.*`` for unset keys. OPTIONS (sslmode etc.) is unchanged. 75 """ 76 conn_params = super().get_connection_params() 77 78 prefix = "postgresql" 79 if self.alias.startswith("replica_"): 80 prefix = f"postgresql.read_replicas.{self.alias.removeprefix('replica_')}" 81 elif self.alias == DIRECT_DB_ALIAS: 82 prefix = "postgresql.direct" 83 84 for setting in ("host", "port", "user", "password"): 85 conn_params[setting] = CONFIG.refresh(f"{prefix}.{setting}") 86 if conn_params[setting] is None and prefix != "postgresql": 87 conn_params[setting] = CONFIG.refresh(f"postgresql.{setting}") 88 89 return conn_params
Refresh host/port/user/password from CONFIG on each connection open.
Supports file-mounted secrets rotating without a process restart. Uses
the alias-specific prefix (postgresql.read_replicas.<name>.* or
postgresql.direct.*) when applicable, falling back to
postgresql.* for unset keys. OPTIONS (sslmode etc.) is unchanged.