authentik.root.settings

root settings for authentik

  1"""root settings for authentik"""
  2
  3import importlib
  4from collections import OrderedDict
  5from pathlib import Path
  6
  7from django.utils import http as utils_http
  8
  9from authentik import authentik_version
 10from authentik.lib.config import (
 11    CONFIG,
 12    DIRECT_DB_ALIAS,
 13    django_db_config,
 14    postgresql_direct_db_enabled,
 15)
 16from authentik.lib.logging import get_logger_config, structlog_configure
 17from authentik.lib.utils.time import timedelta_from_string
 18from authentik.stages.password import BACKEND_APP_PASSWORD, BACKEND_INBUILT, BACKEND_LDAP
 19
 20BASE_DIR = Path(__file__).absolute().parent.parent.parent
 21
 22DEBUG = CONFIG.get_bool("debug")
 23SECRET_KEY = CONFIG.get("secret_key")
 24
 25INTERNAL_IPS = ["127.0.0.1"]
 26ALLOWED_HOSTS = ["*"]
 27SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
 28SECURE_CROSS_ORIGIN_OPENER_POLICY = None
 29LOGIN_URL = "authentik_flows:default-authentication"
 30
 31# Custom user model
 32AUTH_USER_MODEL = "authentik_core.User"
 33
 34CSRF_COOKIE_PATH = LANGUAGE_COOKIE_PATH = SESSION_COOKIE_PATH = CONFIG.get("web.path", "/")
 35
 36CSRF_COOKIE_NAME = "authentik_csrf"
 37CSRF_HEADER_NAME = "HTTP_X_AUTHENTIK_CSRF"
 38LANGUAGE_COOKIE_NAME = "authentik_language"
 39SESSION_COOKIE_NAME = "authentik_session"
 40SESSION_COOKIE_DOMAIN = CONFIG.get("cookie_domain", None)
 41USER_SWITCHING_COOKIE_NAME = "authentik_user_switching"
 42USER_SWITCHING_COOKIE_AGE = timedelta_from_string(
 43    CONFIG.get("sessions.user_switching_age", "days=365")
 44).total_seconds()
 45APPEND_SLASH = False
 46
 47AUTHENTICATION_BACKENDS = [
 48    BACKEND_INBUILT,
 49    BACKEND_APP_PASSWORD,
 50    BACKEND_LDAP,
 51    "guardian.backends.ObjectPermissionBackend",
 52]
 53
 54DEFAULT_AUTO_FIELD = "django.db.models.AutoField"
 55
 56# Application definition
 57INSTALLED_APPS = [
 58    "authentik.commands",
 59    "django_dramatiq_postgres",
 60    "authentik.tasks",
 61    "authentik.admin",
 62    "django.contrib.messages",
 63    "django.contrib.staticfiles",
 64    "django.contrib.humanize",
 65    "django.contrib.postgres",
 66    "psqlextra",
 67    "rest_framework",
 68    "django_filters",
 69    "drf_spectacular",
 70    "django_prometheus",
 71    "django_countries",
 72    "pgactivity",
 73    "pglock",
 74    "channels",
 75    "django_channels_postgres",
 76    "django.contrib.auth",
 77    "django.contrib.contenttypes",
 78    "django.contrib.sessions",
 79    "pgtrigger",
 80    "django_postgres_cache",
 81    "authentik.api",
 82    "authentik.core",
 83    "authentik.crypto",
 84    "authentik.endpoints",
 85    "authentik.endpoints.connectors.agent",
 86    "authentik.events",
 87    "authentik.admin.files",
 88    "authentik.flows",
 89    "authentik.outposts",
 90    "authentik.policies.dummy",
 91    "authentik.policies.event_matcher",
 92    "authentik.policies.expiry",
 93    "authentik.policies.expression",
 94    "authentik.policies.geoip",
 95    "authentik.policies.password",
 96    "authentik.policies.reputation",
 97    "authentik.policies",
 98    "authentik.providers.ldap",
 99    "authentik.providers.oauth2",
100    "authentik.providers.proxy",
101    "authentik.providers.rac",
102    "authentik.providers.radius",
103    "authentik.providers.saml",
104    "authentik.providers.scim",
105    "authentik.rbac",
106    "authentik.recovery",
107    "authentik.sources.kerberos",
108    "authentik.sources.ldap",
109    "authentik.sources.oauth",
110    "authentik.sources.plex",
111    "authentik.sources.saml",
112    "authentik.sources.scim",
113    "authentik.sources.telegram",
114    "authentik.stages.authenticator",
115    "authentik.stages.authenticator_duo",
116    "authentik.stages.authenticator_email",
117    "authentik.stages.authenticator_sms",
118    "authentik.stages.authenticator_static",
119    "authentik.stages.authenticator_totp",
120    "authentik.stages.authenticator_validate",
121    "authentik.stages.authenticator_webauthn",
122    "authentik.stages.captcha",
123    "authentik.stages.consent",
124    "authentik.stages.deny",
125    "authentik.stages.dummy",
126    "authentik.stages.email",
127    "authentik.stages.identification",
128    "authentik.stages.invitation",
129    "authentik.stages.password",
130    "authentik.stages.prompt",
131    "authentik.stages.redirect",
132    "authentik.stages.user_delete",
133    "authentik.stages.user_login",
134    "authentik.stages.user_logout",
135    "authentik.stages.user_write",
136    "authentik.tasks.schedules",
137    # TODO: remove in 2027
138    "authentik.tenants",
139    "authentik.brands",
140    "authentik.blueprints",
141    "guardian",
142]
143
144GUARDIAN_GROUP_MODEL = "authentik_core.Group"
145GUARDIAN_ROLE_MODEL = "authentik_rbac.Role"
146GUARDIAN_GET_INIT_ANONYMOUS_USER = "authentik.core.models.get_init_anonymous_user"
147
148SPECTACULAR_SETTINGS = {
149    "TITLE": "authentik",
150    "DESCRIPTION": "Making authentication simple.",
151    "VERSION": authentik_version(),
152    "COMPONENT_SPLIT_REQUEST": True,
153    "SCHEMA_PATH_PREFIX": "/api/v([0-9]+(beta)?)",
154    "SCHEMA_PATH_PREFIX_TRIM": True,
155    "SERVERS": [
156        {
157            "url": "/api/v3",
158        },
159    ],
160    "CONTACT": {
161        "email": "hello@goauthentik.io",
162    },
163    "AUTHENTICATION_WHITELIST": [
164        "authentik.endpoints.connectors.agent.auth.AgentAuth",
165        "authentik.endpoints.connectors.agent.auth.AgentEnrollmentAuth",
166        "authentik.endpoints.connectors.agent.auth.DeviceAuthFedAuthentication",
167        "authentik.api.authentication.TokenAuthentication",
168    ],
169    "LICENSE": {
170        "name": "MIT",
171        "url": "https://github.com/goauthentik/authentik/blob/main/LICENSE",
172    },
173    "ENUM_NAME_OVERRIDES": {
174        "ActivityBasisEnum": "authentik.enterprise.lifecycle.expiration.models.ActivityBasis",
175        "AppEnum": "authentik.lib.api.Apps",
176        "AuthenticationEnum": "authentik.flows.models.FlowAuthenticationRequirement",
177        "ClientTypeEnum": "authentik.providers.oauth2.models.ClientType",
178        "ConsentModeEnum": "authentik.stages.consent.models.ConsentMode",
179        "CountryCodeEnum": "django_countries.countries",
180        "DeviceClassesEnum": "authentik.stages.authenticator_validate.models.DeviceClasses",
181        "DeviceFactsOSFamily": "authentik.endpoints.facts.OSFamily",
182        "EventActions": "authentik.events.models.EventAction",
183        "FlowDesignationEnum": "authentik.flows.models.FlowDesignation",
184        "FlowLayoutEnum": "authentik.flows.models.FlowLayout",
185        "FlowMessageLevelEnum": "authentik.flows.challenge.FLOW_MESSAGE_LEVELS",
186        "GrantTypeEnum": "authentik.providers.oauth2.models.GrantType",
187        "LDAPAPIAccessMode": "authentik.providers.ldap.models.APIAccessMode",
188        "ModelEnum": "authentik.lib.api.Models",
189        "OffboardingActionEnum": (
190            "authentik.enterprise.lifecycle.offboarding.models.OffboardingAction"
191        ),
192        "OffboardingStatusEnum": (
193            "authentik.enterprise.lifecycle.offboarding.models.OffboardingStatus"
194        ),
195        "OutgoingSyncDeleteAction": "authentik.lib.sync.outgoing.models.OutgoingSyncDeleteAction",
196        "PKCEMethodEnum": "authentik.sources.oauth.models.PKCEMethod",
197        "PolicyEngineMode": "authentik.policies.models.PolicyEngineMode",
198        "PromptTypeEnum": "authentik.stages.prompt.models.FieldTypes",
199        "ProxyMode": "authentik.providers.proxy.models.ProxyMode",
200        "RedirectURITypeEnum": "authentik.providers.oauth2.models.RedirectURIType",
201        "RequestStatus": "authentik.enterprise.requests.models.RequestStatus",
202        "SAMLBindingsEnum": "authentik.providers.saml.models.SAMLBindings",
203        "SAMLLogoutMethods": "authentik.providers.saml.models.SAMLLogoutMethods",
204        "SAMLNameIDPolicyEnum": "authentik.sources.saml.models.SAMLNameIDPolicy",
205        "SCIMAuthenticationModeEnum": "authentik.providers.scim.models.SCIMAuthenticationMode",
206        "StageModeEnum": "authentik.endpoints.models.StageMode",
207        "TaskAggregatedStatusEnum": "authentik.tasks.models.TaskStatus",
208        "TaskStatusEnum": "django_dramatiq_postgres.models.TaskState",
209        "TransportModeEnum": "authentik.events.models.TransportMode",
210        "UserTypeEnum": "authentik.core.models.UserTypes",
211        "UserVerificationEnum": "authentik.stages.authenticator_webauthn.models.UserVerification",
212        "WebAuthnHintEnum": "authentik.stages.authenticator_webauthn.models.WebAuthnHint",
213        "WSFedSAMLVersionEnum": (
214            "authentik.enterprise.providers.ws_federation.models.WSFederationSAMLVersion"
215        ),
216    },
217    "ENUM_ADD_EXPLICIT_BLANK_NULL_CHOICE": False,
218    "ENUM_GENERATE_CHOICE_DESCRIPTION": False,
219    "PREPROCESSING_HOOKS": [
220        "authentik.api.v3.schema.cleanup.preprocess_schema_exclude_non_api",
221    ],
222    "POSTPROCESSING_HOOKS": [
223        "authentik.api.v3.schema.response.postprocess_schema_register",
224        "authentik.api.v3.schema.response.postprocess_schema_responses",
225        "authentik.api.v3.schema.query.postprocess_schema_query_params",
226        "authentik.api.v3.schema.cleanup.postprocess_schema_remove_unused",
227        "authentik.api.v3.schema.search.postprocess_schema_search_autocomplete",
228        "authentik.api.v3.schema.enum.postprocess_schema_enums",
229    ],
230}
231
232REST_FRAMEWORK = {
233    "DEFAULT_PAGINATION_CLASS": "authentik.api.pagination.Pagination",
234    "DEFAULT_FILTER_BACKENDS": [
235        "authentik.api.search.ql.QLSearch",
236        "authentik.rbac.filters.ObjectFilter",
237        "django_filters.rest_framework.DjangoFilterBackend",
238        "authentik.api.ordering.NullsAwareOrderingFilter",
239    ],
240    "DEFAULT_PERMISSION_CLASSES": ("authentik.rbac.permissions.ObjectPermissions",),
241    "DEFAULT_AUTHENTICATION_CLASSES": (
242        "authentik.api.authentication.TokenAuthentication",
243        "rest_framework.authentication.SessionAuthentication",
244    ),
245    "DEFAULT_RENDERER_CLASSES": [
246        "authentik.api.renderers.MsgspecJSONRenderer",
247    ],
248    "DEFAULT_PARSER_CLASSES": [
249        "authentik.api.parsers.MsgspecJSONParser",
250    ],
251    "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
252    "TEST_REQUEST_DEFAULT_FORMAT": "json",
253    "DEFAULT_THROTTLE_CLASSES": ["authentik.api.throttle.LocalAnonRateThrottle"],
254    "DEFAULT_THROTTLE_RATES": {
255        "anon": CONFIG.get("throttle.default"),
256    },
257}
258
259
260CACHES = {
261    "default": {
262        "BACKEND": "django_postgres_cache.backend.DatabaseCache",
263        "KEY_FUNCTION": "authentik.root.cache.make_key",
264        "REVERSE_KEY_FUNCTION": "authentik.root.cache.reverse_key",
265    },
266    # In-process cache for DRF throttle counters. Per-worker rather than
267    # cluster-wide, so the per-IP ceiling is ``throttle.default`` × (pods × workers)
268    "throttle": {
269        "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
270        "LOCATION": "authentik-throttle",
271        "OPTIONS": {
272            "MAX_ENTRIES": 10000,
273        },
274    },
275}
276SESSION_ENGINE = "authentik.core.sessions"
277# Configured via custom SessionMiddleware
278# SESSION_COOKIE_SAMESITE = "None"
279# SESSION_COOKIE_SECURE = True
280SESSION_COOKIE_AGE = timedelta_from_string(
281    CONFIG.get("sessions.unauthenticated_age", "days=1")
282).total_seconds()
283SESSION_EXPIRE_AT_BROWSER_CLOSE = True
284
285MESSAGE_STORAGE = "django.contrib.messages.storage.session.SessionStorage"
286
287MIDDLEWARE_FIRST = [
288    "authentik.root.middleware.LivenessMiddleware",
289    "django_prometheus.middleware.PrometheusBeforeMiddleware",
290]
291MIDDLEWARE = [
292    "authentik.root.middleware.LoggingMiddleware",
293    "authentik.root.middleware.ClientIPMiddleware",
294    "authentik.stages.user_login.middleware.BoundSessionMiddleware",
295    "django.middleware.locale.LocaleMiddleware",
296    "authentik.core.middleware.AuthenticationMiddleware",
297    "authentik.core.middleware.RequestIDMiddleware",
298    "authentik.brands.middleware.BrandMiddleware",
299    "authentik.events.middleware.AuditMiddleware",
300    "django.middleware.security.SecurityMiddleware",
301    "django.middleware.common.CommonMiddleware",
302    "authentik.root.middleware.CsrfViewMiddleware",
303    "django.contrib.messages.middleware.MessageMiddleware",
304    "django.middleware.clickjacking.XFrameOptionsMiddleware",
305    "authentik.core.middleware.ImpersonateMiddleware",
306    "authentik.core.middleware.LocaleOverrideMiddleware",
307    "authentik.rbac.middleware.InitialPermissionsMiddleware",
308    "authentik.rbac.middleware.AlterResponseMiddleware",
309]
310MIDDLEWARE_LAST = [
311    "django_prometheus.middleware.PrometheusAfterMiddleware",
312]
313
314ROOT_URLCONF = "authentik.root.urls"
315
316TEMPLATES = [
317    {
318        "BACKEND": "django.template.backends.django.DjangoTemplates",
319        "DIRS": [CONFIG.get("email.template_dir")],
320        "APP_DIRS": True,
321        "OPTIONS": {
322            "context_processors": [
323                "django.template.context_processors.debug",
324                "django.template.context_processors.request",
325                "django.contrib.auth.context_processors.auth",
326                "django.contrib.messages.context_processors.messages",
327                "authentik.brands.utils.context_processor",
328            ],
329        },
330    },
331]
332
333ASGI_APPLICATION = "authentik.root.asgi.application"
334
335
336# Database
337# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
338
339# Custom overrides for database backends
340# The tree looks like this:
341# psqlextra backend
342#   -> authentik custom backend
343#     -> django_prometheus backend
344#       -> django built-in backend
345POSTGRES_EXTRA_DB_BACKEND_BASE = "authentik.root.db"
346DATABASES = django_db_config()
347
348DATABASE_ROUTERS = ("authentik.root.db.router.FailoverRouter",)
349
350# We don't use HStore
351POSTGRES_EXTRA_AUTO_EXTENSION_SET_UP = False
352
353# When a direct endpoint is configured (postgresql.direct.*), route the
354# Channels Postgres layer through it — its LISTEN connection can't tolerate
355# a transaction pooler swapping the backend.
356CHANNEL_LAYERS = {
357    "default": {
358        "BACKEND": "django_channels_postgres.layer.PostgresChannelLayer",
359        "CONFIG": ({"using": DIRECT_DB_ALIAS} if postgresql_direct_db_enabled(CONFIG) else {}),
360    },
361}
362
363# Email
364# These values should never actually be used, emails are only sent from email stages, which
365# loads the config directly from CONFIG
366# See authentik/stages/email/models.py, line 105
367EMAIL_HOST = CONFIG.get("email.host")
368EMAIL_PORT = CONFIG.get_int("email.port")
369EMAIL_HOST_USER = CONFIG.get("email.username")
370EMAIL_HOST_PASSWORD = CONFIG.get("email.password")
371EMAIL_USE_TLS = CONFIG.get_bool("email.use_tls", False)
372EMAIL_USE_SSL = CONFIG.get_bool("email.use_ssl", False)
373EMAIL_TIMEOUT = CONFIG.get_int("email.timeout")
374DEFAULT_FROM_EMAIL = CONFIG.get("email.from")
375SERVER_EMAIL = DEFAULT_FROM_EMAIL
376EMAIL_SUBJECT_PREFIX = "[authentik] "
377
378# The first hasher is used for new passwords. The rest remain available so existing
379# hashes still verify.
380PASSWORD_HASHERS = [
381    "django.contrib.auth.hashers.PBKDF2PasswordHasher",
382    "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher",
383    "django.contrib.auth.hashers.Argon2PasswordHasher",
384    "django.contrib.auth.hashers.BCryptSHA256PasswordHasher",
385    "django.contrib.auth.hashers.ScryptPasswordHasher",
386]
387# Keep in sync with `authentik.lib.validators.PasswordHashValidator.current_parameters`
388PASSWORD_HASHERS_IMPORT_ALLOWED = [
389    "django.contrib.auth.hashers.PBKDF2PasswordHasher",
390    "django.contrib.auth.hashers.Argon2PasswordHasher",
391    "django.contrib.auth.hashers.BCryptSHA256PasswordHasher",
392    "django.contrib.auth.hashers.ScryptPasswordHasher",
393]
394
395# Password validation
396# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
397
398AUTH_PASSWORD_VALIDATORS = [
399    {
400        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
401    },
402    {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
403    {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
404    {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
405]
406
407
408# Internationalization
409# https://docs.djangoproject.com/en/2.1/topics/i18n/
410
411LANGUAGE_CODE = "en-us"
412
413TIME_ZONE = "UTC"
414
415USE_I18N = True
416
417USE_TZ = True
418
419LOCALE_PATHS = ["./locale"]
420
421
422# Tests
423
424TEST = False
425TEST_RUNNER = "authentik.root.test_runner.PytestTestRunner"
426
427
428# Dramatiq
429
430DRAMATIQ = {
431    "channel_prefix": "authentik",
432    "task_model": "authentik.tasks.models.Task",
433    # Route the broker's LISTEN connection and advisory-lock connection through
434    # the direct endpoint when configured. ORM queries continue via db_alias=default.
435    "broker_kwargs": (
436        {"direct_db_alias": DIRECT_DB_ALIAS} if postgresql_direct_db_enabled(CONFIG) else {}
437    ),
438    "task_purge_interval": timedelta_from_string(
439        CONFIG.get("worker.task_purge_interval")
440    ).total_seconds(),
441    "task_expiration": timedelta_from_string(CONFIG.get("worker.task_expiration")).total_seconds(),
442    "autodiscovery": {
443        "enabled": True,
444        "setup_module": "authentik.tasks.setup",
445        "apps_prefix": "authentik",
446    },
447    "worker": {
448        "processes": CONFIG.get_int("worker.processes", 2),
449        "threads": CONFIG.get_int("worker.threads", 1),
450        "consumer_listen_timeout": timedelta_from_string(
451            CONFIG.get("worker.consumer_listen_timeout")
452        ).total_seconds(),
453        "watch_folder": BASE_DIR / "authentik",
454    },
455    "scheduler_class": "authentik.tasks.schedules.scheduler.Scheduler",
456    "schedule_model": "authentik.tasks.schedules.models.Schedule",
457    "scheduler_interval": timedelta_from_string(
458        CONFIG.get("worker.scheduler_interval")
459    ).total_seconds(),
460    "middlewares": (
461        ("django_dramatiq_postgres.middleware.FullyQualifiedActorName", {}),
462        ("django_dramatiq_postgres.middleware.DbConnectionMiddleware", {}),
463        ("django_dramatiq_postgres.middleware.TaskStateBeforeMiddleware", {}),
464        ("dramatiq.middleware.age_limit.AgeLimit", {}),
465        (
466            "dramatiq.middleware.time_limit.TimeLimit",
467            {
468                "time_limit": timedelta_from_string(
469                    CONFIG.get("worker.task_default_time_limit")
470                ).total_seconds()
471                * 1000
472            },
473        ),
474        ("dramatiq.middleware.shutdown.ShutdownNotifications", {}),
475        ("dramatiq.middleware.callbacks.Callbacks", {}),
476        ("dramatiq.middleware.pipelines.Pipelines", {}),
477        (
478            "dramatiq.middleware.retries.Retries",
479            {
480                "max_retries": CONFIG.get_int("worker.task_max_retries") if not TEST else 0,
481                "max_backoff": 60 * 60 * 1000,  # 1 hour
482            },
483        ),
484        ("dramatiq.results.middleware.Results", {"store_results": True}),
485        ("authentik.tasks.middleware.StartupSignalsMiddleware", {}),
486        ("authentik.tasks.middleware.CurrentTask", {}),
487        ("authentik.tasks.middleware.ModelDataMiddleware", {}),
488        ("authentik.tasks.middleware.TaskLogMiddleware", {}),
489        ("authentik.tasks.middleware.LoggingMiddleware", {}),
490        ("authentik.tasks.middleware.DescriptionMiddleware", {}),
491        (
492            "authentik.tasks.middleware.MetricsMiddleware",
493            {
494                "prefix": "authentik",
495            },
496        ),
497        ("django_dramatiq_postgres.middleware.TaskStateAfterMiddleware", {}),
498    ),
499    "test": TEST,
500}
501
502
503# Static files (CSS, JavaScript, Images)
504# https://docs.djangoproject.com/en/2.1/howto/static-files/
505
506STATICFILES_DIRS = [BASE_DIR / Path("web")]
507STATIC_URL = CONFIG.get("web.path", "/") + "static/"
508
509STORAGES = {
510    "staticfiles": {
511        "BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage",
512    },
513}
514
515# Django 5.2.8 and CVE-2025-64458 added a strong enforcement of 2048 characters
516# as the maximum for a URL to redirect to, mostly for running on Windows.
517# However, our URLs can easily exceed that with OAuth/SAML Query parameters or hash values.
518# 8192 should cover most cases.
519utils_http.MAX_URL_LENGTH = utils_http.MAX_URL_LENGTH * 4
520
521structlog_configure()
522LOGGING = get_logger_config()
523
524
525_DISALLOWED_ITEMS = [
526    "INSTALLED_APPS",
527    "MIDDLEWARE_FIRST",
528    "MIDDLEWARE",
529    "MIDDLEWARE_LAST",
530    "AUTHENTICATION_BACKENDS",
531    "SPECTACULAR_SETTINGS",
532    "REST_FRAMEWORK",
533]
534
535SILENCED_SYSTEM_CHECKS = [
536    # We use our own subclass of django.middleware.csrf.CsrfViewMiddleware
537    "security.W003",
538    # We don't set SESSION_COOKIE_SECURE since we use a custom SessionMiddleware subclass
539    "security.W010",
540    # HSTS: This is configured in reverse proxies/the go proxy, not in django
541    "security.W004",
542    # https redirect: This is configured in reverse proxies/the go proxy, not in django
543    "security.W008",
544]
545
546
547def subtract_list(a: list, b: list) -> list:
548    return [item for item in a if item not in b]
549
550
551def _filter_and_update(apps: list[str]) -> None:
552    for _app in set(apps):
553        if not _app.startswith("authentik"):
554            continue
555        _update_settings(f"{_app}.settings")
556
557
558def _update_settings(app_path: str) -> None:
559    try:
560        settings_module = importlib.import_module(app_path)
561        CONFIG.log("debug", "Loaded app settings", path=app_path)
562
563        new_apps = subtract_list(getattr(settings_module, "INSTALLED_APPS", []), INSTALLED_APPS)
564        INSTALLED_APPS.extend(new_apps)
565        _filter_and_update(new_apps)
566
567        MIDDLEWARE_FIRST.extend(getattr(settings_module, "MIDDLEWARE_FIRST", []))
568        MIDDLEWARE.extend(getattr(settings_module, "MIDDLEWARE", []))
569
570        AUTHENTICATION_BACKENDS.extend(getattr(settings_module, "AUTHENTICATION_BACKENDS", []))
571        SPECTACULAR_SETTINGS.update(getattr(settings_module, "SPECTACULAR_SETTINGS", {}))
572        REST_FRAMEWORK.update(getattr(settings_module, "REST_FRAMEWORK", {}))
573
574        for _attr in dir(settings_module):
575            if not _attr.startswith("__") and _attr not in _DISALLOWED_ITEMS:
576                globals()[_attr] = getattr(settings_module, _attr)
577    except ImportError:
578        pass
579
580
581# Attempt to load enterprise app, if available
582try:
583    importlib.import_module("authentik.enterprise.apps")
584    CONFIG.log("info", "Enabled authentik enterprise")
585    INSTALLED_APPS.insert(INSTALLED_APPS.index("authentik.events"), "authentik.enterprise")
586except ImportError:
587    pass
588
589if DEBUG:
590    INSTALLED_APPS.insert(INSTALLED_APPS.index("django.contrib.staticfiles"), "daphne")
591    INSTALLED_APPS.append("django_migration_linter")
592    from xmlsec import enable_debug_trace
593
594    enable_debug_trace(True)
595
596
597CONFIG.log("info", "Booting authentik", version=authentik_version())
598
599# Load subapps's settings
600_filter_and_update(INSTALLED_APPS)
601_update_settings("data.user_settings")
602
603MIDDLEWARE = list(OrderedDict.fromkeys(MIDDLEWARE_FIRST + MIDDLEWARE + MIDDLEWARE_LAST))
604
605# Error-reporting tracers (OpenTelemetry, Sentry) are initialized from
606# AuthentikCoreConfig.ready(), since it needs to run after Django settings have fully
607# loaded (see authentik/core/apps.py)
BASE_DIR = PosixPath('/home/runner/work/authentik/authentik')
DEBUG = False
SECRET_KEY = 'mGvgxdSV9rqHFaYuSNjPu3I7SJWAYp2PDteRuoub'
INTERNAL_IPS = ['127.0.0.1']
ALLOWED_HOSTS = ['*']
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_CROSS_ORIGIN_OPENER_POLICY = None
LOGIN_URL = 'authentik_flows:default-authentication'
AUTH_USER_MODEL = 'authentik_core.User'
CSRF_HEADER_NAME = 'HTTP_X_AUTHENTIK_CSRF'
APPEND_SLASH = False
AUTHENTICATION_BACKENDS = ['authentik.core.auth.InbuiltBackend', 'authentik.core.auth.TokenBackend', 'authentik.sources.ldap.auth.LDAPBackend', 'guardian.backends.ObjectPermissionBackend']
DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'
INSTALLED_APPS = ['authentik.commands', 'django_dramatiq_postgres', 'authentik.tasks', 'authentik.admin', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'django.contrib.postgres', 'psqlextra', 'rest_framework', 'django_filters', 'drf_spectacular', 'django_prometheus', 'django_countries', 'pgactivity', 'pglock', 'channels', 'django_channels_postgres', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'pgtrigger', 'django_postgres_cache', 'authentik.api', 'authentik.core', 'authentik.crypto', 'authentik.endpoints', 'authentik.endpoints.connectors.agent', 'authentik.enterprise', 'authentik.events', 'authentik.admin.files', 'authentik.flows', 'authentik.outposts', 'authentik.policies.dummy', 'authentik.policies.event_matcher', 'authentik.policies.expiry', 'authentik.policies.expression', 'authentik.policies.geoip', 'authentik.policies.password', 'authentik.policies.reputation', 'authentik.policies', 'authentik.providers.ldap', 'authentik.providers.oauth2', 'authentik.providers.proxy', 'authentik.providers.rac', 'authentik.providers.radius', 'authentik.providers.saml', 'authentik.providers.scim', 'authentik.rbac', 'authentik.recovery', 'authentik.sources.kerberos', 'authentik.sources.ldap', 'authentik.sources.oauth', 'authentik.sources.plex', 'authentik.sources.saml', 'authentik.sources.scim', 'authentik.sources.telegram', 'authentik.stages.authenticator', 'authentik.stages.authenticator_duo', 'authentik.stages.authenticator_email', 'authentik.stages.authenticator_sms', 'authentik.stages.authenticator_static', 'authentik.stages.authenticator_totp', 'authentik.stages.authenticator_validate', 'authentik.stages.authenticator_webauthn', 'authentik.stages.captcha', 'authentik.stages.consent', 'authentik.stages.deny', 'authentik.stages.dummy', 'authentik.stages.email', 'authentik.stages.identification', 'authentik.stages.invitation', 'authentik.stages.password', 'authentik.stages.prompt', 'authentik.stages.redirect', 'authentik.stages.user_delete', 'authentik.stages.user_login', 'authentik.stages.user_logout', 'authentik.stages.user_write', 'authentik.tasks.schedules', 'authentik.tenants', 'authentik.brands', 'authentik.blueprints', 'guardian', 'authentik.enterprise.agents', 'authentik.enterprise.audit', 'authentik.enterprise.endpoints.connectors.agent', 'authentik.enterprise.endpoints.connectors.fleet', 'authentik.enterprise.endpoints.connectors.google_chrome', 'authentik.enterprise.endpoints.connectors.microsoft_intune', 'authentik.enterprise.lifecycle', 'authentik.enterprise.policies.unique_password', 'authentik.enterprise.providers.google_workspace', 'authentik.enterprise.providers.microsoft_entra', 'authentik.enterprise.providers.radius', 'authentik.enterprise.providers.scim', 'authentik.enterprise.providers.ssf', 'authentik.enterprise.providers.ws_federation', 'authentik.enterprise.reports', 'authentik.enterprise.requests', 'authentik.enterprise.stages.account_lockdown', 'authentik.enterprise.stages.authenticator_endpoint_gdtc', 'authentik.enterprise.stages.mtls', 'authentik.enterprise.stages.source']
GUARDIAN_GROUP_MODEL = 'authentik_core.Group'
GUARDIAN_ROLE_MODEL = 'authentik_rbac.Role'
GUARDIAN_GET_INIT_ANONYMOUS_USER = 'authentik.core.models.get_init_anonymous_user'
SPECTACULAR_SETTINGS = {'TITLE': 'authentik', 'DESCRIPTION': 'Making authentication simple.', 'VERSION': '2027.2.0-rc1', 'COMPONENT_SPLIT_REQUEST': True, 'SCHEMA_PATH_PREFIX': '/api/v([0-9]+(beta)?)', 'SCHEMA_PATH_PREFIX_TRIM': True, 'SERVERS': [{'url': '/api/v3'}], 'CONTACT': {'email': 'hello@goauthentik.io'}, 'AUTHENTICATION_WHITELIST': ['authentik.endpoints.connectors.agent.auth.AgentAuth', 'authentik.endpoints.connectors.agent.auth.AgentEnrollmentAuth', 'authentik.endpoints.connectors.agent.auth.DeviceAuthFedAuthentication', 'authentik.api.authentication.TokenAuthentication'], 'LICENSE': {'name': 'MIT', 'url': 'https://github.com/goauthentik/authentik/blob/main/LICENSE'}, 'ENUM_NAME_OVERRIDES': {'ActivityBasisEnum': 'authentik.enterprise.lifecycle.expiration.models.ActivityBasis', 'AppEnum': 'authentik.lib.api.Apps', 'AuthenticationEnum': 'authentik.flows.models.FlowAuthenticationRequirement', 'ClientTypeEnum': 'authentik.providers.oauth2.models.ClientType', 'ConsentModeEnum': 'authentik.stages.consent.models.ConsentMode', 'CountryCodeEnum': 'django_countries.countries', 'DeviceClassesEnum': 'authentik.stages.authenticator_validate.models.DeviceClasses', 'DeviceFactsOSFamily': 'authentik.endpoints.facts.OSFamily', 'EventActions': 'authentik.events.models.EventAction', 'FlowDesignationEnum': 'authentik.flows.models.FlowDesignation', 'FlowLayoutEnum': 'authentik.flows.models.FlowLayout', 'FlowMessageLevelEnum': 'authentik.flows.challenge.FLOW_MESSAGE_LEVELS', 'GrantTypeEnum': 'authentik.providers.oauth2.models.GrantType', 'LDAPAPIAccessMode': 'authentik.providers.ldap.models.APIAccessMode', 'ModelEnum': 'authentik.lib.api.Models', 'OffboardingActionEnum': 'authentik.enterprise.lifecycle.offboarding.models.OffboardingAction', 'OffboardingStatusEnum': 'authentik.enterprise.lifecycle.offboarding.models.OffboardingStatus', 'OutgoingSyncDeleteAction': 'authentik.lib.sync.outgoing.models.OutgoingSyncDeleteAction', 'PKCEMethodEnum': 'authentik.sources.oauth.models.PKCEMethod', 'PolicyEngineMode': 'authentik.policies.models.PolicyEngineMode', 'PromptTypeEnum': 'authentik.stages.prompt.models.FieldTypes', 'ProxyMode': 'authentik.providers.proxy.models.ProxyMode', 'RedirectURITypeEnum': 'authentik.providers.oauth2.models.RedirectURIType', 'RequestStatus': 'authentik.enterprise.requests.models.RequestStatus', 'SAMLBindingsEnum': 'authentik.providers.saml.models.SAMLBindings', 'SAMLLogoutMethods': 'authentik.providers.saml.models.SAMLLogoutMethods', 'SAMLNameIDPolicyEnum': 'authentik.sources.saml.models.SAMLNameIDPolicy', 'SCIMAuthenticationModeEnum': 'authentik.providers.scim.models.SCIMAuthenticationMode', 'StageModeEnum': 'authentik.endpoints.models.StageMode', 'TaskAggregatedStatusEnum': 'authentik.tasks.models.TaskStatus', 'TaskStatusEnum': 'django_dramatiq_postgres.models.TaskState', 'TransportModeEnum': 'authentik.events.models.TransportMode', 'UserTypeEnum': 'authentik.core.models.UserTypes', 'UserVerificationEnum': 'authentik.stages.authenticator_webauthn.models.UserVerification', 'WebAuthnHintEnum': 'authentik.stages.authenticator_webauthn.models.WebAuthnHint', 'WSFedSAMLVersionEnum': 'authentik.enterprise.providers.ws_federation.models.WSFederationSAMLVersion'}, 'ENUM_ADD_EXPLICIT_BLANK_NULL_CHOICE': False, 'ENUM_GENERATE_CHOICE_DESCRIPTION': False, 'PREPROCESSING_HOOKS': ['authentik.api.v3.schema.cleanup.preprocess_schema_exclude_non_api'], 'POSTPROCESSING_HOOKS': ['authentik.api.v3.schema.response.postprocess_schema_register', 'authentik.api.v3.schema.response.postprocess_schema_responses', 'authentik.api.v3.schema.query.postprocess_schema_query_params', 'authentik.api.v3.schema.cleanup.postprocess_schema_remove_unused', 'authentik.api.v3.schema.search.postprocess_schema_search_autocomplete', 'authentik.api.v3.schema.enum.postprocess_schema_enums']}
REST_FRAMEWORK = {'DEFAULT_PAGINATION_CLASS': 'authentik.api.pagination.Pagination', 'DEFAULT_FILTER_BACKENDS': ['authentik.api.search.ql.QLSearch', 'authentik.rbac.filters.ObjectFilter', 'django_filters.rest_framework.DjangoFilterBackend', 'authentik.api.ordering.NullsAwareOrderingFilter'], 'DEFAULT_PERMISSION_CLASSES': ('authentik.rbac.permissions.ObjectPermissions',), 'DEFAULT_AUTHENTICATION_CLASSES': ('authentik.api.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication'), 'DEFAULT_RENDERER_CLASSES': ['authentik.api.renderers.MsgspecJSONRenderer'], 'DEFAULT_PARSER_CLASSES': ['authentik.api.parsers.MsgspecJSONParser'], 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', 'TEST_REQUEST_DEFAULT_FORMAT': 'json', 'DEFAULT_THROTTLE_CLASSES': ['authentik.api.throttle.LocalAnonRateThrottle'], 'DEFAULT_THROTTLE_RATES': {'anon': '1000/second'}}
CACHES = {'default': {'BACKEND': 'django_postgres_cache.backend.DatabaseCache', 'KEY_FUNCTION': 'authentik.root.cache.make_key', 'REVERSE_KEY_FUNCTION': 'authentik.root.cache.reverse_key'}, 'throttle': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'authentik-throttle', 'OPTIONS': {'MAX_ENTRIES': 10000}}}
SESSION_ENGINE = 'authentik.core.sessions'
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'
MIDDLEWARE_FIRST = ['authentik.root.middleware.LivenessMiddleware', 'django_prometheus.middleware.PrometheusBeforeMiddleware']
MIDDLEWARE_LAST = ['django_prometheus.middleware.PrometheusAfterMiddleware']
ROOT_URLCONF = 'authentik.root.urls'
TEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['/templates'], 'APP_DIRS': True, 'OPTIONS': {'context_processors': ['django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'authentik.brands.utils.context_processor']}}]
ASGI_APPLICATION = 'authentik.root.asgi.application'
POSTGRES_EXTRA_DB_BACKEND_BASE = 'authentik.root.db'
DATABASES = {'default': {'ENGINE': 'psqlextra.backend', 'HOST': 'localhost', 'NAME': 'authentik', 'USER': 'authentik', 'PASSWORD': 'EK-5jnKfjrGRm<77', 'PORT': 5432, 'OPTIONS': {'sslmode': 'disable', 'sslrootcert': None, 'sslcert': None, 'sslkey': None, 'pool': False, 'options': '-c TimeZone=UTC'}, 'CONN_MAX_AGE': 0, 'CONN_HEALTH_CHECKS': False, 'DISABLE_SERVER_SIDE_CURSORS': False, 'TEST': {'NAME': 'test_authentik', 'CHARSET': None, 'COLLATION': None, 'MIGRATE': True, 'MIRROR': None}, 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'TIME_ZONE': None}}
DATABASE_ROUTERS = ('authentik.root.db.router.FailoverRouter',)
POSTGRES_EXTRA_AUTO_EXTENSION_SET_UP = False
CHANNEL_LAYERS = {'default': {'BACKEND': 'django_channels_postgres.layer.PostgresChannelLayer', 'CONFIG': {}}}
EMAIL_HOST = 'localhost'
EMAIL_PORT = 25
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False
EMAIL_USE_SSL = False
EMAIL_TIMEOUT = 10
DEFAULT_FROM_EMAIL = 'authentik@localhost'
SERVER_EMAIL = 'authentik@localhost'
EMAIL_SUBJECT_PREFIX = '[authentik] '
PASSWORD_HASHERS = ['django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.Argon2PasswordHasher', 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.ScryptPasswordHasher']
PASSWORD_HASHERS_IMPORT_ALLOWED = ['django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.Argon2PasswordHasher', 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.ScryptPasswordHasher']
AUTH_PASSWORD_VALIDATORS = [{'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'}, {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'}, {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'}, {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'}]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
LOCALE_PATHS = ['./locale']
TEST = False
DRAMATIQ = {'channel_prefix': 'authentik', 'task_model': 'authentik.tasks.models.Task', 'broker_kwargs': {}, 'task_purge_interval': 86400.0, 'task_expiration': 2592000.0, 'autodiscovery': {'enabled': True, 'setup_module': 'authentik.tasks.setup', 'apps_prefix': 'authentik'}, 'worker': {'processes': 1, 'threads': 2, 'consumer_listen_timeout': 30.0, 'watch_folder': PosixPath('/home/runner/work/authentik/authentik/authentik')}, 'scheduler_class': 'authentik.tasks.schedules.scheduler.Scheduler', 'schedule_model': 'authentik.tasks.schedules.models.Schedule', 'scheduler_interval': 60.0, 'middlewares': (('django_dramatiq_postgres.middleware.FullyQualifiedActorName', {}), ('django_dramatiq_postgres.middleware.DbConnectionMiddleware', {}), ('django_dramatiq_postgres.middleware.TaskStateBeforeMiddleware', {}), ('dramatiq.middleware.age_limit.AgeLimit', {}), ('dramatiq.middleware.time_limit.TimeLimit', {'time_limit': 600000.0}), ('dramatiq.middleware.shutdown.ShutdownNotifications', {}), ('dramatiq.middleware.callbacks.Callbacks', {}), ('dramatiq.middleware.pipelines.Pipelines', {}), ('dramatiq.middleware.retries.Retries', {'max_retries': 5, 'max_backoff': 3600000}), ('dramatiq.results.middleware.Results', {'store_results': True, 'backend': <django_dramatiq_postgres.results.PostgresBackend object>}), ('authentik.tasks.middleware.StartupSignalsMiddleware', {}), ('authentik.tasks.middleware.CurrentTask', {}), ('authentik.tasks.middleware.ModelDataMiddleware', {}), ('authentik.tasks.middleware.TaskLogMiddleware', {}), ('authentik.tasks.middleware.LoggingMiddleware', {}), ('authentik.tasks.middleware.DescriptionMiddleware', {}), ('authentik.tasks.middleware.MetricsMiddleware', {'prefix': 'authentik'}), ('django_dramatiq_postgres.middleware.TaskStateAfterMiddleware', {})), 'test': False}
STATICFILES_DIRS = [PosixPath('/home/runner/work/authentik/authentik/web')]
STATIC_URL = '/static/'
STORAGES = {'staticfiles': {'BACKEND': 'django.contrib.staticfiles.storage.StaticFilesStorage'}}
LOGGING = {'version': 1, 'disable_existing_loggers': False, 'formatters': {'json': {'()': <class 'structlog.stdlib.ProcessorFormatter'>, 'processor': <structlog.processors.JSONRenderer object>, 'foreign_pre_chain': [<function add_log_level>, <function add_logger_name>, <structlog.processors.TimeStamper object>, <structlog.processors.StackInfoRenderer object>, <structlog.processors.ExceptionRenderer object>]}, 'console': {'()': <class 'structlog.stdlib.ProcessorFormatter'>, 'processor': <structlog.dev.ConsoleRenderer object>, 'foreign_pre_chain': [<function add_log_level>, <function add_logger_name>, <structlog.processors.TimeStamper object>, <structlog.processors.StackInfoRenderer object>]}}, 'handlers': {'console': {'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'json'}}, 'loggers': {'': {'handlers': ['console'], 'level': 'DEBUG', 'propagate': False}, 'authentik': {'handlers': ['console'], 'level': 'DEBUG', 'propagate': False}, 'django': {'handlers': ['console'], 'level': 'WARNING', 'propagate': False}, 'django.request': {'handlers': ['console'], 'level': 'ERROR', 'propagate': False}, 'selenium': {'handlers': ['console'], 'level': 'WARNING', 'propagate': False}, 'docker': {'handlers': ['console'], 'level': 'WARNING', 'propagate': False}, 'urllib3': {'handlers': ['console'], 'level': 'WARNING', 'propagate': False}, 'websockets': {'handlers': ['console'], 'level': 'WARNING', 'propagate': False}, 'daphne': {'handlers': ['console'], 'level': 'WARNING', 'propagate': False}, 'kubernetes': {'handlers': ['console'], 'level': 'INFO', 'propagate': False}, 'asyncio': {'handlers': ['console'], 'level': 'WARNING', 'propagate': False}, 'fsevents': {'handlers': ['console'], 'level': 'WARNING', 'propagate': False}, 'uvicorn': {'handlers': ['console'], 'level': 'WARNING', 'propagate': False}, 'gunicorn': {'handlers': ['console'], 'level': 'INFO', 'propagate': False}, 'requests_mock': {'handlers': ['console'], 'level': 'WARNING', 'propagate': False}, 'hpack': {'handlers': ['console'], 'level': 'WARNING', 'propagate': False}, 'httpx': {'handlers': ['console'], 'level': 'WARNING', 'propagate': False}, 'azure': {'handlers': ['console'], 'level': 'WARNING', 'propagate': False}, 'httpcore': {'handlers': ['console'], 'level': 'WARNING', 'propagate': False}, 'django_migration_linter': {'handlers': ['console'], 'level': 'WARNING', 'propagate': False}}}
SILENCED_SYSTEM_CHECKS = ['security.W003', 'security.W010', 'security.W004', 'security.W008']
def subtract_list(a: list, b: list) -> list:
548def subtract_list(a: list, b: list) -> list:
549    return [item for item in a if item not in b]