chores.py 3.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import time
  2. from django.conf import settings
  3. from django.core.mail import get_connection, mail_admins
  4. from django.core.management import BaseCommand
  5. from django.utils import timezone
  6. import dns.message, dns.rdatatype, dns.query
  7. from desecapi import models, serializers
  8. from desecapi.pdns_change_tracker import PDNSChangeTracker
  9. class Command(BaseCommand):
  10. @staticmethod
  11. def delete_expired_captchas():
  12. models.Captcha.objects.filter(created__lt=timezone.now() - settings.CAPTCHA_VALIDITY_PERIOD).delete()
  13. @staticmethod
  14. def delete_never_activated_users():
  15. # delete inactive users whose activation link expired and who never logged in
  16. # (this will not delete users who have used their account and were later disabled)
  17. models.User.objects.filter(is_active=False, last_login__exact=None,
  18. created__lt=timezone.now() - settings.VALIDITY_PERIOD_VERIFICATION_SIGNATURE).delete()
  19. @staticmethod
  20. def update_healthcheck_timestamp():
  21. name = 'internal-timestamp.desec.test'
  22. try:
  23. domain = models.Domain.objects.get(name=name)
  24. except models.Domain.DoesNotExist:
  25. # Fail silently. If external alerting is configured, it will catch the problem; otherwise, we don't need it.
  26. print(f'{name} zone is not configured; skipping TXT record update')
  27. return
  28. instances = domain.rrset_set.filter(subname='', type='TXT').all()
  29. timestamp = int(time.time())
  30. content = f'"{timestamp}"'
  31. data = [{
  32. 'subname': '',
  33. 'type': 'TXT',
  34. 'ttl': '3600',
  35. 'records': [content]
  36. }]
  37. serializer = serializers.RRsetSerializer(instances, domain=domain, data=data, many=True, partial=True)
  38. serializer.is_valid(raise_exception=True)
  39. with PDNSChangeTracker():
  40. serializer.save()
  41. print(f'TXT {name} updated to {content}')
  42. @staticmethod
  43. def alerting_healthcheck():
  44. name = 'external-timestamp.desec.test'
  45. try:
  46. models.Domain.objects.get(name=name)
  47. except models.Domain.DoesNotExist:
  48. print(f'{name} zone is not configured; skipping alerting health check')
  49. return
  50. timestamps = []
  51. qname = dns.name.from_text(name)
  52. query = dns.message.make_query(qname, dns.rdatatype.TXT)
  53. server = 'ns1.desec.io'
  54. response = None
  55. try:
  56. response = dns.query.tcp(query, server, timeout=5)
  57. for content in response.find_rrset(dns.message.ANSWER, qname, dns.rdataclass.IN, dns.rdatatype.TXT):
  58. timestamps.append(str(content)[1:-1])
  59. except Exception:
  60. pass
  61. now = time.time()
  62. if any(now - 600 <= int(timestamp) <= now for timestamp in timestamps):
  63. print(f'TXT {name} up to date.')
  64. return
  65. timestamps = ', '.join(timestamps)
  66. print(f'TXT {name} out of date! Timestamps: {timestamps}')
  67. subject = 'ALERT Alerting system down?'
  68. message = f'TXT query for {name} on {server} gave the following response:\n'
  69. message += f'{str(response)}\n\n'
  70. message += f'Extracted timestamps in TXT RRset:\n{timestamps}'
  71. mail_admins(subject, message, connection=get_connection('django.core.mail.backends.smtp.EmailBackend'))
  72. def handle(self, *args, **kwargs):
  73. try:
  74. self.alerting_healthcheck()
  75. self.update_healthcheck_timestamp()
  76. self.delete_expired_captchas()
  77. self.delete_never_activated_users()
  78. except Exception as e:
  79. subject = 'chores Exception!'
  80. message = f'{type(e)}\n\n{str(e)}'
  81. print(f'Chores exception: {type(e)}, {str(e)}')
  82. mail_admins(subject, message, connection=get_connection('django.core.mail.backends.smtp.EmailBackend'))