chores.py 4.1 KB

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