This repository has been archived on 2024-05-31. You can view files and clone it, but cannot push or open issues or pull requests.
authentik/passbook/root/settings.py

399 lines
13 KiB
Python
Raw Normal View History

2018-11-11 12:41:48 +00:00
"""
Django settings for passbook project.
Generated by 'django-admin startproject' using Django 2.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
2018-11-16 08:10:35 +00:00
import importlib
2018-11-11 12:41:48 +00:00
import os
2019-02-11 16:36:36 +00:00
import sys
2018-11-11 12:41:48 +00:00
2019-09-30 16:04:04 +00:00
import structlog
from celery.schedules import crontab
2019-04-04 19:48:50 +00:00
from sentry_sdk import init as sentry_init
from sentry_sdk.integrations.celery import CeleryIntegration
from sentry_sdk.integrations.django import DjangoIntegration
2018-11-11 12:41:48 +00:00
from passbook import __version__
2018-11-16 08:10:35 +00:00
from passbook.lib.config import CONFIG
2020-02-24 12:16:05 +00:00
from passbook.lib.logging import add_process_id
from passbook.lib.sentry import before_send
2018-11-16 08:10:35 +00:00
LOGGER = structlog.get_logger()
2018-11-11 12:41:48 +00:00
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
2019-12-31 11:51:16 +00:00
STATIC_ROOT = BASE_DIR + "/static"
2018-11-11 12:41:48 +00:00
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
2019-12-31 11:51:16 +00:00
SECRET_KEY = CONFIG.y(
"secret_key", "9$@r!d^1^jrn#fk#1#@ks#9&i$^s#1)_13%$rwjrhd=e8jfi_s"
) # noqa Debug
2018-11-11 12:41:48 +00:00
2019-12-31 11:51:16 +00:00
DEBUG = CONFIG.y_bool("debug")
INTERNAL_IPS = ["127.0.0.1"]
ALLOWED_HOSTS = ["*"]
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
2018-11-11 12:41:48 +00:00
LOGIN_URL = "passbook_flows:default-authentication"
2018-11-11 12:41:48 +00:00
# Custom user model
2019-12-31 11:51:16 +00:00
AUTH_USER_MODEL = "passbook_core.User"
2018-11-11 12:41:48 +00:00
2020-05-13 21:20:27 +00:00
_cookie_suffix = "_debug" if DEBUG else ""
CSRF_COOKIE_NAME = f"passbook_csrf{_cookie_suffix}"
LANGUAGE_COOKIE_NAME = f"passbook_language{_cookie_suffix}"
SESSION_COOKIE_NAME = f"passbook_session{_cookie_suffix}"
2018-11-11 12:41:48 +00:00
AUTHENTICATION_BACKENDS = [
2019-12-31 11:51:16 +00:00
"django.contrib.auth.backends.ModelBackend",
"guardian.backends.ObjectPermissionBackend",
2018-11-11 12:41:48 +00:00
]
# Application definition
INSTALLED_APPS = [
2019-12-31 11:51:16 +00:00
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"django.contrib.postgres",
"django.contrib.humanize",
2019-12-31 11:51:16 +00:00
"rest_framework",
2020-05-13 09:57:10 +00:00
"django_filters",
2019-12-31 11:51:16 +00:00
"drf_yasg",
"guardian",
"django_prometheus",
"passbook.admin.apps.PassbookAdminConfig",
"passbook.api.apps.PassbookAPIConfig",
"passbook.audit.apps.PassbookAuditConfig",
"passbook.crypto.apps.PassbookCryptoConfig",
"passbook.flows.apps.PassbookFlowsConfig",
"passbook.lib.apps.PassbookLibConfig",
"passbook.policies.apps.PassbookPoliciesConfig",
"passbook.policies.dummy.apps.PassbookPolicyDummyConfig",
"passbook.policies.expiry.apps.PassbookPolicyExpiryConfig",
"passbook.policies.expression.apps.PassbookPolicyExpressionConfig",
"passbook.policies.hibp.apps.PassbookPolicyHIBPConfig",
"passbook.policies.password.apps.PassbookPoliciesPasswordConfig",
"passbook.policies.reputation.apps.PassbookPolicyReputationConfig",
2019-12-31 11:51:16 +00:00
"passbook.providers.app_gw.apps.PassbookApplicationApplicationGatewayConfig",
"passbook.providers.oauth.apps.PassbookProviderOAuthConfig",
"passbook.providers.oidc.apps.PassbookProviderOIDCConfig",
"passbook.providers.saml.apps.PassbookProviderSAMLConfig",
"passbook.providers.samlv2.apps.PassbookProviderSAMLv2Config",
"passbook.recovery.apps.PassbookRecoveryConfig",
"passbook.sources.ldap.apps.PassbookSourceLDAPConfig",
"passbook.sources.oauth.apps.PassbookSourceOAuthConfig",
"passbook.sources.saml.apps.PassbookSourceSAMLConfig",
"passbook.stages.captcha.apps.PassbookStageCaptchaConfig",
WIP Use Flows for Sources and Providers (#32) * core: start migrating to flows for authorisation * sources/oauth: start type-hinting * core: create default user * core: only show user delete button if an unenrollment flow exists * flows: Correctly check initial policies on flow with context * policies: add more verbosity to engine * sources/oauth: migrate to flows * sources/oauth: fix typing errors * flows: add more tests * sources/oauth: start implementing unittests * sources/ldap: add option to disable user sync, move connection init to model * sources/ldap: re-add default PropertyMappings * providers/saml: re-add default PropertyMappings * admin: fix missing stage count * stages/identification: fix sources not being shown * crypto: fix being unable to save with private key * crypto: re-add default self-signed keypair * policies: rewrite cache_key to prevent wrong cache * sources/saml: migrate to flows for auth and enrollment * stages/consent: add new stage * admin: fix PropertyMapping widget not rendering properly * core: provider.authorization_flow is mandatory * flows: add support for "autosubmit" attribute on form * flows: add InMemoryStage for dynamic stages * flows: optionally allow empty flows from FlowPlanner * providers/saml: update to authorization_flow * sources/*: fix flow executor URL * flows: fix pylint error * flows: wrap responses in JSON object to easily handle redirects * flow: dont cache plan's context * providers/oauth: rewrite OAuth2 Provider to use flows * providers/*: update docstrings of models * core: fix forms not passing help_text through safe * flows: fix HttpResponses not being converted to JSON * providers/oidc: rewrite to use flows * flows: fix linting
2020-06-07 14:35:08 +00:00
"passbook.stages.consent.apps.PassbookStageConsentConfig",
2020-05-10 11:06:38 +00:00
"passbook.stages.dummy.apps.PassbookStageDummyConfig",
"passbook.stages.email.apps.PassbookStageEmailConfig",
"passbook.stages.prompt.apps.PassbookStagPromptConfig",
"passbook.stages.identification.apps.PassbookStageIdentificationConfig",
"passbook.stages.invitation.apps.PassbookStageUserInvitationConfig",
"passbook.stages.user_delete.apps.PassbookStageUserDeleteConfig",
"passbook.stages.user_login.apps.PassbookStageUserLoginConfig",
2020-05-10 23:12:14 +00:00
"passbook.stages.user_logout.apps.PassbookStageUserLogoutConfig",
"passbook.stages.user_write.apps.PassbookStageUserWriteConfig",
2020-05-08 17:46:39 +00:00
"passbook.stages.otp.apps.PassbookStageOTPConfig",
"passbook.stages.password.apps.PassbookStagePasswordConfig",
"passbook.static.apps.PassbookStaticConfig",
2018-11-11 12:41:48 +00:00
]
GUARDIAN_MONKEY_PATCH = False
2019-10-28 16:40:57 +00:00
SWAGGER_SETTINGS = {
2019-12-31 11:51:16 +00:00
"DEFAULT_INFO": "passbook.api.v2.urls.info",
2019-10-28 16:40:57 +00:00
}
2018-11-16 08:10:35 +00:00
REST_FRAMEWORK = {
2019-12-31 11:51:16 +00:00
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination",
"PAGE_SIZE": 100,
"DEFAULT_FILTER_BACKENDS": [
"django_filters.rest_framework.DjangoFilterBackend",
"rest_framework.filters.OrderingFilter",
"rest_framework.filters.SearchFilter",
2019-10-28 16:40:57 +00:00
],
2019-12-31 11:51:16 +00:00
"DEFAULT_PERMISSION_CLASSES": (
2019-10-28 16:40:57 +00:00
# 'rest_framework.permissions.IsAuthenticated',
2019-12-31 11:51:16 +00:00
"passbook.api.permissions.CustomObjectPermissions",
2019-10-28 16:40:57 +00:00
),
2019-12-31 11:51:16 +00:00
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework.authentication.SessionAuthentication",
2019-10-28 16:40:57 +00:00
# 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
2018-11-16 08:10:35 +00:00
}
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
2019-12-31 11:51:16 +00:00
"LOCATION": (
f"redis://:{CONFIG.y('redis.password')}@{CONFIG.y('redis.host')}:6379"
f"/{CONFIG.y('redis.cache_db')}"
),
2020-05-27 09:26:48 +00:00
"OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient"},
}
}
2019-09-30 16:04:04 +00:00
DJANGO_REDIS_IGNORE_EXCEPTIONS = True
DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS = True
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
2019-09-30 16:04:04 +00:00
SESSION_CACHE_ALIAS = "default"
2018-11-11 12:41:48 +00:00
MIDDLEWARE = [
2019-12-31 11:51:16 +00:00
"django_prometheus.middleware.PrometheusBeforeMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.middleware.security.SecurityMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"django_prometheus.middleware.PrometheusAfterMiddleware",
2018-11-11 12:41:48 +00:00
]
2019-12-31 11:51:16 +00:00
ROOT_URLCONF = "passbook.root.urls"
2018-11-11 12:41:48 +00:00
TEMPLATES = [
{
2019-12-31 11:51:16 +00:00
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"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",
2018-11-11 12:41:48 +00:00
],
},
},
]
2019-12-31 11:51:16 +00:00
WSGI_APPLICATION = "passbook.root.wsgi.application"
2018-11-11 12:41:48 +00:00
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
2019-09-30 16:04:04 +00:00
DATABASES = {
2019-12-31 11:51:16 +00:00
"default": {
"ENGINE": "django_prometheus.db.backends.postgresql",
"HOST": CONFIG.y("postgresql.host"),
"NAME": CONFIG.y("postgresql.name"),
"USER": CONFIG.y("postgresql.user"),
"PASSWORD": CONFIG.y("postgresql.password"),
2018-11-11 12:41:48 +00:00
}
2019-09-30 16:04:04 +00:00
}
2018-11-11 12:41:48 +00:00
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
2019-12-31 11:51:16 +00:00
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
2018-11-11 12:41:48 +00:00
},
2020-05-27 09:26:48 +00:00
{"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
{"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
2018-11-11 12:41:48 +00:00
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
2019-12-31 11:51:16 +00:00
LANGUAGE_CODE = "en-us"
2018-11-11 12:41:48 +00:00
2019-12-31 11:51:16 +00:00
TIME_ZONE = "UTC"
2018-11-11 12:41:48 +00:00
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Celery settings
# Add a 10 minute timeout to all Celery tasks.
CELERY_TASK_SOFT_TIME_LIMIT = 600
CELERY_BEAT_SCHEDULE = {
2020-05-16 14:11:53 +00:00
"clean_tokens": {
"task": "passbook.core.tasks.clean_tokens",
2019-12-31 11:51:16 +00:00
"schedule": crontab(minute="*/5"), # Run every 5 minutes
}
}
CELERY_CREATE_MISSING_QUEUES = True
2019-12-31 11:51:16 +00:00
CELERY_TASK_DEFAULT_QUEUE = "passbook"
CELERY_BROKER_URL = (
f"redis://:{CONFIG.y('redis.password')}@{CONFIG.y('redis.host')}"
f":6379/{CONFIG.y('redis.message_queue_db')}"
)
CELERY_RESULT_BACKEND = (
f"redis://:{CONFIG.y('redis.password')}@{CONFIG.y('redis.host')}"
f":6379/{CONFIG.y('redis.message_queue_db')}"
)
2019-03-03 19:48:31 +00:00
# Database backup
2019-12-31 11:51:16 +00:00
if CONFIG.y("postgresql.backup"):
INSTALLED_APPS += ["dbbackup"]
DBBACKUP_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"
2020-05-16 12:54:18 +00:00
DBBACKUP_CONNECTOR_MAPPING = {
"django_prometheus.db.backends.postgresql": "dbbackup.db.postgresql.PgDumpConnector"
}
2019-12-31 11:51:16 +00:00
AWS_ACCESS_KEY_ID = CONFIG.y("postgresql.backup.access_key")
AWS_SECRET_ACCESS_KEY = CONFIG.y("postgresql.backup.secret_key")
AWS_STORAGE_BUCKET_NAME = CONFIG.y("postgresql.backup.bucket")
AWS_S3_ENDPOINT_URL = CONFIG.y("postgresql.backup.host")
AWS_DEFAULT_ACL = None
2019-12-31 11:51:16 +00:00
LOGGER.info(
"Database backup is configured", host=CONFIG.y("postgresql.backup.host")
)
# Add automatic task to backup
2019-12-31 11:51:16 +00:00
CELERY_BEAT_SCHEDULE["db_backup"] = {
"task": "passbook.lib.tasks.backup_database",
"schedule": crontab(minute=0, hour=0), # Run every day, midnight
}
2019-04-11 13:30:42 +00:00
# Sentry integration
2019-12-31 11:51:16 +00:00
_ERROR_REPORTING = CONFIG.y_bool("error_reporting", False)
if not DEBUG and _ERROR_REPORTING:
LOGGER.info("Error reporting is enabled.")
2019-04-11 13:30:42 +00:00
sentry_init(
2019-07-03 15:35:54 +00:00
dsn="https://33cdbcb23f8b436dbe0ee06847410b67@sentry.beryju.org/3",
2019-12-31 11:51:16 +00:00
integrations=[DjangoIntegration(), CeleryIntegration()],
2019-04-11 13:30:42 +00:00
send_default_pii=True,
before_send=before_send,
2019-12-31 11:51:16 +00:00
release="passbook@%s" % __version__,
2019-04-11 13:30:42 +00:00
)
2018-11-11 12:41:48 +00:00
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
2019-12-31 11:51:16 +00:00
STATIC_URL = "/static/"
2018-11-11 12:41:48 +00:00
2019-09-30 16:04:04 +00:00
structlog.configure_once(
processors=[
structlog.stdlib.add_log_level,
2020-02-20 12:52:14 +00:00
structlog.stdlib.add_logger_name,
2020-02-24 12:16:05 +00:00
add_process_id,
2019-09-30 16:04:04 +00:00
structlog.stdlib.PositionalArgumentsFormatter(),
structlog.processors.TimeStamper(),
structlog.processors.StackInfoRenderer(),
structlog.processors.format_exc_info,
2019-09-30 16:04:04 +00:00
structlog.stdlib.ProcessorFormatter.wrap_for_formatter,
],
context_class=structlog.threadlocal.wrap_dict(dict),
logger_factory=structlog.stdlib.LoggerFactory(),
wrapper_class=structlog.stdlib.BoundLogger,
cache_logger_on_first_use=True,
)
LOG_PRE_CHAIN = [
# Add the log level and a timestamp to the event_dict if the log entry
# is not from structlog.
structlog.stdlib.add_log_level,
structlog.processors.TimeStamper(),
]
LOGGING = {
2019-12-31 11:51:16 +00:00
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"plain": {
"()": structlog.stdlib.ProcessorFormatter,
"processor": structlog.processors.JSONRenderer(sort_keys=True),
"foreign_pre_chain": LOG_PRE_CHAIN,
2018-11-11 12:41:48 +00:00
},
"colored": {
"()": structlog.stdlib.ProcessorFormatter,
"processor": structlog.dev.ConsoleRenderer(colors=DEBUG),
"foreign_pre_chain": LOG_PRE_CHAIN,
2018-11-11 12:41:48 +00:00
},
},
2019-12-31 11:51:16 +00:00
"handlers": {
"console": {
"level": "DEBUG",
2019-12-31 11:51:16 +00:00
"class": "logging.StreamHandler",
"formatter": "colored" if DEBUG else "plain",
},
},
2019-12-31 11:51:16 +00:00
"loggers": {},
}
LOG_LEVEL = CONFIG.y("log_level").upper()
_LOGGING_HANDLER_MAP = {
"": LOG_LEVEL,
"passbook": LOG_LEVEL,
2019-12-31 11:51:16 +00:00
"django": "WARNING",
"celery": "WARNING",
"grpc": LOG_LEVEL,
"oauthlib": LOG_LEVEL,
"oauth2_provider": LOG_LEVEL,
"oidc_provider": LOG_LEVEL,
}
for handler_name, level in _LOGGING_HANDLER_MAP.items():
# pyright: reportGeneralTypeIssues=false
2019-12-31 11:51:16 +00:00
LOGGING["loggers"][handler_name] = {
"handlers": ["console"],
"level": level,
"propagate": False,
2018-11-11 12:41:48 +00:00
}
2019-02-11 16:36:36 +00:00
TEST = False
2019-12-31 11:51:16 +00:00
TEST_RUNNER = "xmlrunner.extra.djangotestrunner.XMLTestRunner"
TEST_OUTPUT_VERBOSE = 2
2019-02-11 16:36:36 +00:00
2019-12-31 11:51:16 +00:00
TEST_OUTPUT_FILE_NAME = "unittest.xml"
2019-02-11 16:36:36 +00:00
2019-12-31 11:51:16 +00:00
if any("test" in arg for arg in sys.argv):
LOGGER.warning("Testing mode enabled, no logging from now on...")
LOGGING = None
2019-02-11 16:36:36 +00:00
TEST = True
2019-02-26 13:24:50 +00:00
CELERY_TASK_ALWAYS_EAGER = True
2019-02-11 16:36:36 +00:00
2019-09-30 16:04:04 +00:00
_DISALLOWED_ITEMS = [
2019-12-31 11:51:16 +00:00
"INSTALLED_APPS",
"MIDDLEWARE",
"AUTHENTICATION_BACKENDS",
"CELERY_BEAT_SCHEDULE",
]
2018-11-16 08:10:35 +00:00
# Load subapps's INSTALLED_APPS
for _app in INSTALLED_APPS:
2019-12-31 11:51:16 +00:00
if _app.startswith("passbook"):
if "apps" in _app:
_app = ".".join(_app.split(".")[:-2])
2018-11-16 08:10:35 +00:00
try:
app_settings = importlib.import_module("%s.settings" % _app)
2019-12-31 11:51:16 +00:00
INSTALLED_APPS.extend(getattr(app_settings, "INSTALLED_APPS", []))
MIDDLEWARE.extend(getattr(app_settings, "MIDDLEWARE", []))
AUTHENTICATION_BACKENDS.extend(
getattr(app_settings, "AUTHENTICATION_BACKENDS", [])
)
CELERY_BEAT_SCHEDULE.update(
getattr(app_settings, "CELERY_BEAT_SCHEDULE", {})
)
for _attr in dir(app_settings):
2019-12-31 11:51:16 +00:00
if not _attr.startswith("__") and _attr not in _DISALLOWED_ITEMS:
globals()[_attr] = getattr(app_settings, _attr)
2018-11-16 08:10:35 +00:00
except ImportError:
pass
if DEBUG:
2020-05-13 21:20:27 +00:00
SESSION_COOKIE_SAMESITE = None
2019-12-31 11:51:16 +00:00
INSTALLED_APPS.append("debug_toolbar")
MIDDLEWARE.append("debug_toolbar.middleware.DebugToolbarMiddleware")
INSTALLED_APPS.append("passbook.core.apps.PassbookCoreConfig")