settings.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. __package__ = 'archivebox.core'
  2. # TODO: add this after we upgrade to Django >=3.2
  3. # https://github.com/typeddjango/django-stubs
  4. # import django_stubs_ext
  5. # django_stubs_ext.monkeypatch()
  6. import os
  7. import sys
  8. import re
  9. import logging
  10. import tempfile
  11. from pathlib import Path
  12. from django.utils.crypto import get_random_string
  13. from ..config import (
  14. DEBUG,
  15. SECRET_KEY,
  16. ALLOWED_HOSTS,
  17. PACKAGE_DIR,
  18. TEMPLATES_DIR_NAME,
  19. CUSTOM_TEMPLATES_DIR,
  20. SQL_INDEX_FILENAME,
  21. OUTPUT_DIR,
  22. LOGS_DIR,
  23. TIMEZONE,
  24. LDAP,
  25. LDAP_SERVER_URI,
  26. LDAP_BIND_DN,
  27. LDAP_BIND_PASSWORD,
  28. LDAP_USER_BASE,
  29. LDAP_USER_FILTER,
  30. LDAP_USERNAME_ATTR,
  31. LDAP_FIRSTNAME_ATTR,
  32. LDAP_LASTNAME_ATTR,
  33. LDAP_EMAIL_ATTR,
  34. )
  35. IS_MIGRATING = 'makemigrations' in sys.argv[:3] or 'migrate' in sys.argv[:3]
  36. IS_TESTING = 'test' in sys.argv[:3] or 'PYTEST_CURRENT_TEST' in os.environ
  37. IS_SHELL = 'shell' in sys.argv[:3] or 'shell_plus' in sys.argv[:3]
  38. ################################################################################
  39. ### Django Core Settings
  40. ################################################################################
  41. WSGI_APPLICATION = 'core.wsgi.application'
  42. ROOT_URLCONF = 'core.urls'
  43. LOGIN_URL = '/accounts/login/'
  44. LOGOUT_REDIRECT_URL = os.environ.get('LOGOUT_REDIRECT_URL', '/')
  45. PASSWORD_RESET_URL = '/accounts/password_reset/'
  46. APPEND_SLASH = True
  47. DEBUG = DEBUG or ('--debug' in sys.argv)
  48. INSTALLED_APPS = [
  49. 'django.contrib.auth',
  50. 'django.contrib.contenttypes',
  51. 'django.contrib.sessions',
  52. 'django.contrib.messages',
  53. 'django.contrib.staticfiles',
  54. 'django.contrib.admin',
  55. 'solo',
  56. 'core',
  57. # Plugins
  58. 'plugins.defaults',
  59. 'plugins.system',
  60. # 'plugins.replaywebpage', # provides UI to view WARC files
  61. # 'plugins.gallerydl', # provides gallerydl dependency + extractor
  62. # 'plugins.browsertrix', # provides browsertrix dependency + extractor
  63. # 'plugins.playwright', # provides playwright dependency
  64. # ...
  65. # someday we may have enough plugins to justify dynamic loading:
  66. # *(path.parent.name for path in (Path(PACKAGE_DIR) / 'plugins').glob('*/apps.py')),,
  67. 'django_extensions',
  68. ]
  69. ################################################################################
  70. ### Staticfile and Template Settings
  71. ################################################################################
  72. STATIC_URL = '/static/'
  73. STATIC_ROOT = Path(PACKAGE_DIR) / 'collected_static'
  74. STATICFILES_DIRS = [
  75. *([str(CUSTOM_TEMPLATES_DIR / 'static')] if CUSTOM_TEMPLATES_DIR else []),
  76. str(Path(PACKAGE_DIR) / TEMPLATES_DIR_NAME / 'static'),
  77. # Plugins
  78. # str(Path(PACKAGE_DIR) / 'plugins/defaults/static'),
  79. # str(Path(PACKAGE_DIR) / 'plugins/replaywebpage/static'),
  80. # str(Path(PACKAGE_DIR) / 'plugins/gallerydl/static'),
  81. # str(Path(PACKAGE_DIR) / 'plugins/browsertrix/static'),
  82. # str(Path(PACKAGE_DIR) / 'plugins/playwright/static'),
  83. # ...
  84. # someday if there are many more plugins / user-addable plugins:
  85. # *(str(path) for path in (Path(PACKAGE_DIR) / 'plugins').glob('*/static')),
  86. ]
  87. MEDIA_URL = '/archive/'
  88. MEDIA_ROOT = OUTPUT_DIR / 'archive'
  89. TEMPLATE_DIRS = [
  90. *([str(CUSTOM_TEMPLATES_DIR)] if CUSTOM_TEMPLATES_DIR else []),
  91. str(Path(PACKAGE_DIR) / TEMPLATES_DIR_NAME / 'core'),
  92. str(Path(PACKAGE_DIR) / TEMPLATES_DIR_NAME / 'admin'),
  93. str(Path(PACKAGE_DIR) / TEMPLATES_DIR_NAME),
  94. # Plugins
  95. # added by plugins.<PluginName>.apps.<AppName>.ready -> .settings.register_plugin_settings
  96. # str(Path(PACKAGE_DIR) / 'plugins/defaults/templates'),
  97. # str(Path(PACKAGE_DIR) / 'plugins/replaywebpage/templates'),
  98. # str(Path(PACKAGE_DIR) / 'plugins/gallerydl/templates'),
  99. # str(Path(PACKAGE_DIR) / 'plugins/browsertrix/templates'),
  100. # str(Path(PACKAGE_DIR) / 'plugins/playwright/templates'),
  101. # ...
  102. #
  103. # someday if there are many more plugins / user-addable plugins:
  104. # *(str(path) for path in (Path(PACKAGE_DIR) / 'plugins').glob('*/templates')),
  105. ]
  106. TEMPLATES = [
  107. {
  108. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  109. 'DIRS': TEMPLATE_DIRS,
  110. 'APP_DIRS': True,
  111. 'OPTIONS': {
  112. 'context_processors': [
  113. 'django.template.context_processors.debug',
  114. 'django.template.context_processors.request',
  115. 'django.contrib.auth.context_processors.auth',
  116. 'django.contrib.messages.context_processors.messages',
  117. ],
  118. },
  119. },
  120. ]
  121. # For usage with https://www.jetadmin.io/integrations/django
  122. # INSTALLED_APPS += ['jet_django']
  123. # JET_PROJECT = 'archivebox'
  124. # JET_TOKEN = 'some-api-token-here'
  125. MIDDLEWARE = [
  126. 'core.middleware.TimezoneMiddleware',
  127. 'django.middleware.security.SecurityMiddleware',
  128. 'django.contrib.sessions.middleware.SessionMiddleware',
  129. 'django.middleware.common.CommonMiddleware',
  130. 'django.middleware.csrf.CsrfViewMiddleware',
  131. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  132. 'core.middleware.ReverseProxyAuthMiddleware',
  133. 'django.contrib.messages.middleware.MessageMiddleware',
  134. 'core.middleware.CacheControlMiddleware',
  135. ]
  136. ################################################################################
  137. ### Authentication Settings
  138. ################################################################################
  139. AUTHENTICATION_BACKENDS = [
  140. 'django.contrib.auth.backends.RemoteUserBackend',
  141. 'django.contrib.auth.backends.ModelBackend',
  142. ]
  143. if LDAP:
  144. try:
  145. import ldap
  146. from django_auth_ldap.config import LDAPSearch
  147. global AUTH_LDAP_SERVER_URI
  148. global AUTH_LDAP_BIND_DN
  149. global AUTH_LDAP_BIND_PASSWORD
  150. global AUTH_LDAP_USER_SEARCH
  151. global AUTH_LDAP_USER_ATTR_MAP
  152. AUTH_LDAP_SERVER_URI = LDAP_SERVER_URI
  153. AUTH_LDAP_BIND_DN = LDAP_BIND_DN
  154. AUTH_LDAP_BIND_PASSWORD = LDAP_BIND_PASSWORD
  155. assert AUTH_LDAP_SERVER_URI and LDAP_USERNAME_ATTR and LDAP_USER_FILTER, 'LDAP_* config options must all be set if LDAP=True'
  156. AUTH_LDAP_USER_SEARCH = LDAPSearch(
  157. LDAP_USER_BASE,
  158. ldap.SCOPE_SUBTREE,
  159. '(&(' + LDAP_USERNAME_ATTR + '=%(user)s)' + LDAP_USER_FILTER + ')',
  160. )
  161. AUTH_LDAP_USER_ATTR_MAP = {
  162. 'username': LDAP_USERNAME_ATTR,
  163. 'first_name': LDAP_FIRSTNAME_ATTR,
  164. 'last_name': LDAP_LASTNAME_ATTR,
  165. 'email': LDAP_EMAIL_ATTR,
  166. }
  167. AUTHENTICATION_BACKENDS = [
  168. 'django.contrib.auth.backends.ModelBackend',
  169. 'django_auth_ldap.backend.LDAPBackend',
  170. ]
  171. except ModuleNotFoundError:
  172. sys.stderr.write('[X] Error: Found LDAP=True config but LDAP packages not installed. You may need to run: pip install archivebox[ldap]\n\n')
  173. # dont hard exit here. in case the user is just running "archivebox version" or "archivebox help", we still want those to work despite broken ldap
  174. # sys.exit(1)
  175. ################################################################################
  176. ### Debug Settings
  177. ################################################################################
  178. # only enable debug toolbar when in DEBUG mode with --nothreading (it doesnt work in multithreaded mode)
  179. DEBUG_TOOLBAR = DEBUG and ('--nothreading' in sys.argv) and ('--reload' not in sys.argv)
  180. if DEBUG_TOOLBAR:
  181. try:
  182. import debug_toolbar # noqa
  183. DEBUG_TOOLBAR = True
  184. except ImportError:
  185. DEBUG_TOOLBAR = False
  186. if DEBUG_TOOLBAR:
  187. INSTALLED_APPS = [*INSTALLED_APPS, 'debug_toolbar']
  188. INTERNAL_IPS = ['0.0.0.0', '127.0.0.1', '*']
  189. DEBUG_TOOLBAR_CONFIG = {
  190. "SHOW_TOOLBAR_CALLBACK": lambda request: True,
  191. "RENDER_PANELS": True,
  192. }
  193. DEBUG_TOOLBAR_PANELS = [
  194. 'debug_toolbar.panels.history.HistoryPanel',
  195. 'debug_toolbar.panels.versions.VersionsPanel',
  196. 'debug_toolbar.panels.timer.TimerPanel',
  197. 'debug_toolbar.panels.settings.SettingsPanel',
  198. 'debug_toolbar.panels.headers.HeadersPanel',
  199. 'debug_toolbar.panels.request.RequestPanel',
  200. 'debug_toolbar.panels.sql.SQLPanel',
  201. 'debug_toolbar.panels.staticfiles.StaticFilesPanel',
  202. # 'debug_toolbar.panels.templates.TemplatesPanel', # buggy/slow
  203. 'debug_toolbar.panels.cache.CachePanel',
  204. 'debug_toolbar.panels.signals.SignalsPanel',
  205. 'debug_toolbar.panels.logging.LoggingPanel',
  206. 'debug_toolbar.panels.redirects.RedirectsPanel',
  207. 'debug_toolbar.panels.profiling.ProfilingPanel',
  208. 'djdt_flamegraph.FlamegraphPanel',
  209. ]
  210. MIDDLEWARE = [*MIDDLEWARE, 'debug_toolbar.middleware.DebugToolbarMiddleware']
  211. ################################################################################
  212. ### External Service Settings
  213. ################################################################################
  214. DATABASE_FILE = Path(OUTPUT_DIR) / SQL_INDEX_FILENAME
  215. DATABASE_NAME = os.environ.get("ARCHIVEBOX_DATABASE_NAME", str(DATABASE_FILE))
  216. DATABASES = {
  217. 'default': {
  218. 'ENGINE': 'django.db.backends.sqlite3',
  219. 'NAME': DATABASE_NAME,
  220. 'OPTIONS': {
  221. 'timeout': 60,
  222. 'check_same_thread': False,
  223. },
  224. 'TIME_ZONE': TIMEZONE,
  225. # DB setup is sometimes modified at runtime by setup_django() in config.py
  226. }
  227. }
  228. CACHE_BACKEND = 'django.core.cache.backends.locmem.LocMemCache'
  229. # CACHE_BACKEND = 'django.core.cache.backends.db.DatabaseCache'
  230. # CACHE_BACKEND = 'django.core.cache.backends.dummy.DummyCache'
  231. CACHES = {
  232. 'default': {
  233. 'BACKEND': CACHE_BACKEND,
  234. 'LOCATION': 'django_cache_default',
  235. }
  236. }
  237. EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
  238. ################################################################################
  239. ### Security Settings
  240. ################################################################################
  241. SECRET_KEY = SECRET_KEY or get_random_string(50, 'abcdefghijklmnopqrstuvwxyz0123456789_')
  242. ALLOWED_HOSTS = ALLOWED_HOSTS.split(',')
  243. SECURE_BROWSER_XSS_FILTER = True
  244. SECURE_CONTENT_TYPE_NOSNIFF = True
  245. SECURE_REFERRER_POLICY = 'strict-origin-when-cross-origin'
  246. CSRF_COOKIE_SECURE = False
  247. SESSION_COOKIE_SECURE = False
  248. SESSION_COOKIE_DOMAIN = None
  249. SESSION_COOKIE_AGE = 1209600 # 2 weeks
  250. SESSION_EXPIRE_AT_BROWSER_CLOSE = False
  251. SESSION_SAVE_EVERY_REQUEST = True
  252. SESSION_ENGINE = "django.contrib.sessions.backends.db"
  253. AUTH_PASSWORD_VALIDATORS = [
  254. {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
  255. {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'},
  256. {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},
  257. {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
  258. ]
  259. # WIP: broken by Django 3.1.2 -> 4.0 migration
  260. DEFAULT_AUTO_FIELD = 'django.db.models.UUIDField'
  261. ################################################################################
  262. ### Shell Settings
  263. ################################################################################
  264. SHELL_PLUS = 'ipython'
  265. SHELL_PLUS_PRINT_SQL = False
  266. IPYTHON_ARGUMENTS = ['--no-confirm-exit', '--no-banner']
  267. IPYTHON_KERNEL_DISPLAY_NAME = 'ArchiveBox Django Shell'
  268. if IS_SHELL:
  269. os.environ['PYTHONSTARTUP'] = str(Path(PACKAGE_DIR) / 'core' / 'welcome_message.py')
  270. ################################################################################
  271. ### Internationalization & Localization Settings
  272. ################################################################################
  273. LANGUAGE_CODE = 'en-us'
  274. USE_I18N = True
  275. USE_L10N = True
  276. USE_TZ = True
  277. DATETIME_FORMAT = 'Y-m-d g:iA'
  278. SHORT_DATETIME_FORMAT = 'Y-m-d h:iA'
  279. TIME_ZONE = TIMEZONE # django convention is TIME_ZONE, archivebox config uses TIMEZONE, they are equivalent
  280. from django.conf.locale.en import formats as en_formats
  281. en_formats.DATETIME_FORMAT = DATETIME_FORMAT
  282. en_formats.SHORT_DATETIME_FORMAT = SHORT_DATETIME_FORMAT
  283. ################################################################################
  284. ### Logging Settings
  285. ################################################################################
  286. IGNORABLE_404_URLS = [
  287. re.compile(r'apple-touch-icon.*\.png$'),
  288. re.compile(r'favicon\.ico$'),
  289. re.compile(r'robots\.txt$'),
  290. re.compile(r'.*\.(css|js)\.map$'),
  291. ]
  292. class NoisyRequestsFilter(logging.Filter):
  293. def filter(self, record) -> bool:
  294. logline = record.getMessage()
  295. # ignore harmless 404s for the patterns in IGNORABLE_404_URLS
  296. for ignorable_url_pattern in IGNORABLE_404_URLS:
  297. ignorable_log_pattern = re.compile(f'^"GET /.*/?{ignorable_url_pattern.pattern[:-1]} HTTP/.*" (200|30.|404) .+$', re.I | re.M)
  298. if ignorable_log_pattern.match(logline):
  299. return False
  300. # ignore staticfile requests that 200 or 30*
  301. ignoreable_200_log_pattern = re.compile(r'"GET /static/.* HTTP/.*" (200|30.) .+', re.I | re.M)
  302. if ignoreable_200_log_pattern.match(logline):
  303. return False
  304. return True
  305. if LOGS_DIR.exists():
  306. ERROR_LOG = (LOGS_DIR / 'errors.log')
  307. else:
  308. # historically too many edge cases here around creating log dir w/ correct permissions early on
  309. # if there's an issue on startup, we trash the log and let user figure it out via stdout/stderr
  310. ERROR_LOG = tempfile.NamedTemporaryFile().name
  311. LOGGING = {
  312. 'version': 1,
  313. 'disable_existing_loggers': False,
  314. 'handlers': {
  315. 'console': {
  316. 'class': 'logging.StreamHandler',
  317. },
  318. 'logfile': {
  319. 'level': 'ERROR',
  320. 'class': 'logging.handlers.RotatingFileHandler',
  321. 'filename': ERROR_LOG,
  322. 'maxBytes': 1024 * 1024 * 25, # 25 MB
  323. 'backupCount': 10,
  324. },
  325. },
  326. 'filters': {
  327. 'noisyrequestsfilter': {
  328. '()': NoisyRequestsFilter,
  329. }
  330. },
  331. 'loggers': {
  332. 'django': {
  333. 'handlers': ['console', 'logfile'],
  334. 'level': 'INFO',
  335. 'filters': ['noisyrequestsfilter'],
  336. },
  337. 'django.server': {
  338. 'handlers': ['console', 'logfile'],
  339. 'level': 'INFO',
  340. 'filters': ['noisyrequestsfilter'],
  341. }
  342. },
  343. }