Files
coulobre/src/coulobre/hosting/models.py
T

828 lines
25 KiB
Python

import uuid
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import (
MaxValueValidator,
MinValueValidator,
RegexValidator,
)
from django.db import models, router, transaction
from django.urls import reverse
from django.utils import timezone
from coulobre.account_backup_request import backup_archive
from coulobre.account_backup_retention import MAX_RETAINED_BACKUPS
from coulobre.account_restore_request import MAX_RESTORE_PATH_BYTES
from coulobre.database_node import (
DATABASE_SUFFIX_PATTERN,
INVALID_SUFFIX,
DatabaseSpec,
)
from coulobre.dns_node import (
MAX_SOA_SERIAL,
AddressRecord,
DnsZone,
MxRecord,
TxtRecord,
)
from coulobre.mail_node import (
LOCAL_PART_MAX_LENGTH,
MAX_MAILBOX_QUOTA_MIB,
MailboxSpec,
)
from coulobre.php_pool_settings import (
PHP_SETTING_BOUNDS,
PhpPoolSettings,
PhpPoolSettingsError,
)
from coulobre.web_node import MAX_STORAGE_LIMIT_MIB
from .fields import DomainNameField
class Reseller(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.PROTECT,
related_name="hosting_reseller",
limit_choices_to={
"is_superuser": False,
"hosting_customer__isnull": True,
},
)
account_limit = models.PositiveIntegerField(default=0)
hosting_plans = models.ManyToManyField("HostingPlan", blank=True)
def __str__(self):
return self.user.get_username()
def may_create_accounts(self):
return self.account_limit > 0 and self.hosting_plans.exists()
class Customer(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.PROTECT,
related_name="hosting_customer",
limit_choices_to={
"is_staff": False,
"is_superuser": False,
"hosting_reseller__isnull": True,
},
)
def __str__(self):
return self.user.get_username()
@property
def may_be_impersonated(self):
user = self.user
return (
user.is_active
and not user.is_staff
and not user.is_superuser
and not hasattr(user, "hosting_reseller")
)
class CustomerImpersonation(models.Model):
class EndReason(models.TextChoices):
STOPPED = "stopped", "Ended by administrator"
SIGNED_OUT = "signed_out", "Signed out"
EXPIRED = "expired", "Expired"
ACCESS_REVOKED = "access_revoked", "Access revoked"
operator = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.SET_NULL,
null=True,
related_name="+",
)
customer = models.ForeignKey(
Customer,
on_delete=models.SET_NULL,
null=True,
related_name="+",
)
operator_username = models.CharField(max_length=150)
customer_username = models.CharField(max_length=150)
started_at = models.DateTimeField(default=timezone.now)
expires_at = models.DateTimeField()
ended_at = models.DateTimeField(null=True, blank=True)
end_reason = models.CharField(
max_length=16, choices=EndReason.choices, blank=True
)
class Meta:
ordering = ("-started_at", "-pk")
default_permissions = ("view",)
verbose_name = "customer impersonation session"
permissions = (
("impersonate_customer", "Can view the panel as a customer"),
)
def __str__(self):
return f"{self.operator_username} viewing as {self.customer_username}"
class ServiceCredentialAccess(models.Model):
class Kind(models.TextChoices):
DATABASE = "database", "MariaDB database"
MAILBOX = "mailbox", "Mailbox"
class Outcome(models.TextChoices):
REQUESTED = "requested", "Requested"
REJECTED = "rejected", "Password confirmation failed"
UNAVAILABLE = "unavailable", "Credentials unavailable"
REVEALED = "revealed", "Credentials revealed"
class Method(models.TextChoices):
REVEAL = "reveal", "Show connection details"
PHPMYADMIN = "phpmyadmin", "phpMyAdmin"
method = models.CharField(
max_length=10, choices=Method, default=Method.REVEAL
)
actor = models.ForeignKey(
settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL
)
actor_username = models.CharField(max_length=150)
hosting_account_id = models.PositiveBigIntegerField()
kind = models.CharField(max_length=8, choices=Kind)
resource = models.CharField(max_length=254)
requested_at = models.DateTimeField(default=timezone.now)
outcome = models.CharField(max_length=11, choices=Outcome)
class Meta:
ordering = ("-requested_at", "-pk")
indexes = [models.Index(fields=("actor", "outcome", "requested_at"))]
default_permissions = ("view",)
permissions = [
("reveal_database_credentials", "Can reveal database credentials"),
("reveal_mailbox_credentials", "Can reveal mailbox credentials"),
]
def php_plan_field(option, label):
minimum, maximum = PHP_SETTING_BOUNDS[option]
return models.PositiveIntegerField(
label,
blank=True,
null=True,
validators=[MinValueValidator(minimum), MaxValueValidator(maximum)],
help_text="Leave blank to use the web node default.",
)
class HostingPlan(models.Model):
name = models.CharField(max_length=120, unique=True)
description = models.CharField(max_length=240, blank=True)
database_limit = models.PositiveIntegerField(
blank=True,
null=True,
help_text=(
"Leave blank for unlimited. "
"Enter 0 to block new database requests."
),
)
mailbox_limit = models.PositiveIntegerField(
blank=True,
null=True,
help_text=(
"Leave blank for unlimited. Enter 0 to block new mailbox requests."
),
)
mailbox_quota_mib = models.PositiveIntegerField(
"mailbox storage limit (MiB)",
blank=True,
null=True,
validators=[
MinValueValidator(1),
MaxValueValidator(MAX_MAILBOX_QUOTA_MIB),
],
help_text=(
"Applies to new mailbox requests. Leave blank for unlimited."
),
)
website_storage_limit_mib = models.PositiveIntegerField(
"website storage limit (MiB)",
blank=True,
null=True,
validators=[
MinValueValidator(1),
MaxValueValidator(MAX_STORAGE_LIMIT_MIB),
],
help_text="Default when applying a website storage limit.",
)
php_memory_limit_mib = php_plan_field(
"memory_limit_mib", "PHP memory limit (MiB)"
)
php_upload_limit_mib = php_plan_field(
"upload_limit_mib", "PHP upload limit (MiB)"
)
php_request_timeout_seconds = php_plan_field(
"request_timeout_seconds", "PHP request timeout (seconds)"
)
php_max_children = php_plan_field(
"max_children", "Maximum PHP-FPM workers"
)
class Meta:
ordering = ("name", "pk")
def __str__(self):
return self.name
def clean(self):
super().clean()
try:
self.get_php_settings()
except PhpPoolSettingsError as error:
raise ValidationError(
{f"php_{error.field}": str(error)}
) from error
def get_php_settings(self):
return PhpPoolSettings(
**{
option: getattr(self, f"php_{option}")
for option in PHP_SETTING_BOUNDS
}
)
class HostingAccount(models.Model):
name = models.CharField(max_length=120)
primary_domain = DomainNameField(max_length=253, unique=True)
hosting_plan = models.ForeignKey(
HostingPlan, on_delete=models.PROTECT, null=True, blank=True
)
reseller = models.ForeignKey(
Reseller, on_delete=models.PROTECT, null=True, blank=True
)
customer = models.ForeignKey(
Customer, on_delete=models.PROTECT, null=True, blank=True
)
scheduled_backups_to_keep = models.PositiveSmallIntegerField(
null=True,
blank=True,
validators=[
MinValueValidator(1),
MaxValueValidator(MAX_RETAINED_BACKUPS),
],
)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
constraints = [
models.CheckConstraint(
condition=models.Q(scheduled_backups_to_keep__isnull=True)
| models.Q(
scheduled_backups_to_keep__gte=1,
scheduled_backups_to_keep__lte=MAX_RETAINED_BACKUPS,
),
name="hosting_account_valid_backup_retention",
)
]
def __str__(self):
return str(self.primary_domain)
def save(self, *args, **kwargs):
update_fields = kwargs.get("update_fields")
if update_fields is not None and "primary_domain" not in update_fields:
return super().save(*args, **kwargs)
self.primary_domain = self._meta.get_field("primary_domain").to_python(
self.primary_domain
)
using = kwargs.get("using") or router.db_for_write(
type(self), instance=self
)
with transaction.atomic(using=using):
super().save(*args, **kwargs)
claims = WebsiteDomain.objects.using(using).filter(account=self)
primary = claims.filter(is_primary=True).first()
if primary is None:
claims.create(
domain=self.primary_domain, account=self, is_primary=True
)
elif primary.domain != self.primary_domain:
if claims.filter(is_primary=False).exists():
raise ValidationError(
{
"primary_domain": (
"Remove website aliases before changing the "
"primary domain."
),
}
)
primary.domain = self.primary_domain
primary.save(update_fields=["domain"], using=using)
def get_absolute_url(self):
return reverse("panel:account", kwargs={"pk": self.pk})
def clean(self):
super().clean()
if not self.primary_domain:
return
if WebsiteDomain.objects.filter(
domain=self.primary_domain, is_primary=False
).exists():
raise ValidationError(
{"primary_domain": "This domain is unavailable."}
)
if self.pk:
claims = self.website_domains
if (
claims.filter(is_primary=False).exists()
and claims.filter(is_primary=True)
.exclude(domain=self.primary_domain)
.exists()
):
raise ValidationError(
{
"primary_domain": (
"Remove website aliases before changing the "
"primary domain."
)
}
)
class WebsiteDomain(models.Model):
account = models.ForeignKey(
HostingAccount,
on_delete=models.CASCADE,
related_name="website_domains",
)
domain = DomainNameField(max_length=253, unique=True)
is_primary = models.BooleanField(default=False)
def __str__(self):
return self.domain
class HostingDatabase(models.Model):
account = models.ForeignKey(
HostingAccount, on_delete=models.PROTECT, related_name="databases"
)
suffix = models.CharField(
"database suffix",
max_length=24,
validators=[RegexValidator(DATABASE_SUFFIX_PATTERN, INVALID_SUFFIX)],
help_text=INVALID_SUFFIX,
)
class Meta:
ordering = ("suffix",)
constraints = [
models.UniqueConstraint(
fields=("account", "suffix"),
name="hosting_database_account_suffix_unique",
)
]
def __str__(self):
return self.spec.name
@property
def spec(self):
return DatabaseSpec(self.account_id, self.suffix)
class PhpMyAdminGrant(models.Model):
token_digest = models.CharField(max_length=64, primary_key=True)
actor = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE
)
database = models.ForeignKey(HostingDatabase, on_delete=models.CASCADE)
expires_at = models.DateTimeField(db_index=True)
redeemed_at = models.DateTimeField(null=True, blank=True)
class DirectAdminImport(models.Model):
account = models.OneToOneField(
HostingAccount,
on_delete=models.CASCADE,
related_name="directadmin_import",
)
fingerprint = models.CharField(max_length=64, unique=True)
class HostingDnsZone(models.Model):
account = models.ForeignKey(
HostingAccount, on_delete=models.PROTECT, related_name="dns_zones"
)
domain = DomainNameField(max_length=253, unique=True)
serial = models.PositiveBigIntegerField(default=1)
nameservers = models.JSONField()
responsible_name = DomainNameField(max_length=253)
addresses = models.JSONField(default=list)
mx_records = models.JSONField(default=list)
txt_records = models.JSONField(default=list)
class Meta:
ordering = ("domain",)
constraints = [
models.CheckConstraint(
condition=models.Q(serial__lte=MAX_SOA_SERIAL),
name="hosting_dns_zone_valid_serial",
)
]
def __str__(self):
return str(self.domain)
@property
def spec(self):
return DnsZone(
domain=self.domain,
serial=self.serial,
nameservers=tuple(self.nameservers),
responsible_name=self.responsible_name,
addresses=tuple(
AddressRecord.from_manifest(item) for item in self.addresses
),
mx_records=tuple(
MxRecord.from_manifest(item) for item in self.mx_records
),
txt_records=tuple(
TxtRecord.from_manifest(item) for item in self.txt_records
),
)
class HostingMailDomain(models.Model):
account = models.ForeignKey(
HostingAccount, on_delete=models.PROTECT, related_name="mail_domains"
)
domain = DomainNameField(max_length=253, unique=True)
def __str__(self):
return str(self.domain)
class HostingMailbox(models.Model):
mail_domain = models.ForeignKey(
HostingMailDomain, on_delete=models.PROTECT, related_name="mailboxes"
)
local_part = models.CharField(max_length=LOCAL_PART_MAX_LENGTH)
quota_mib = models.PositiveIntegerField(
"storage limit (MiB)",
blank=True,
null=True,
validators=[
MinValueValidator(1),
MaxValueValidator(MAX_MAILBOX_QUOTA_MIB),
],
)
class Meta:
ordering = ("mail_domain__domain", "local_part")
constraints = [
models.UniqueConstraint(
fields=("mail_domain", "local_part"),
name="hosting_mailbox_domain_local_part_unique",
)
]
def __str__(self):
return self.spec.address
@property
def spec(self):
return MailboxSpec(
self.mail_domain.domain, self.local_part, self.quota_mib
)
class WebProvisioningPlan(models.Model):
account = models.ForeignKey(HostingAccount, on_delete=models.CASCADE)
primary_domain = DomainNameField(max_length=253)
requested_at = models.DateTimeField(auto_now_add=True)
last_dispatched_at = models.DateTimeField(null=True, blank=True)
completed_at = models.DateTimeField(null=True, blank=True)
apache_config = models.TextField(blank=True)
def __str__(self):
return str(self.primary_domain)
@classmethod
def for_account(cls, account):
return cls(account=account, primary_domain=account.primary_domain)
@property
def can_export(self):
return (
self.completed_at is not None
and bool(self.apache_config)
and self.primary_domain == self.account.primary_domain
)
@property
def can_enable_https(self):
activation = getattr(self, "activation", None)
return (
self.can_export
and activation is not None
and activation.state == "configured"
)
class ProvisioningJobManager(models.Manager):
def queue(self, **target):
job, created = self.get_or_create(**target)
if not created:
self.requeue(self.filter(pk=job.pk).exclude(problem=""))
def requeue(self, jobs, **updates):
jobs.filter(finished_at__isnull=False).update(
requested_at=timezone.now(),
last_dispatched_at=None,
started_at=None,
finished_at=None,
problem="",
**updates,
)
class ProvisioningJob(models.Model):
requested_at = models.DateTimeField(default=timezone.now)
last_dispatched_at = models.DateTimeField(null=True, blank=True)
started_at = models.DateTimeField(null=True, blank=True)
finished_at = models.DateTimeField(null=True, blank=True)
problem = models.TextField(blank=True)
objects = ProvisioningJobManager()
class Meta:
abstract = True
@property
def state(self):
if self.finished_at is not None:
return "failed" if self.problem else "configured"
return "running" if self.started_at else "queued"
class WebActivation(ProvisioningJob):
plan = models.OneToOneField(
WebProvisioningPlan,
on_delete=models.CASCADE,
related_name="activation",
)
php_settings = models.JSONField(null=True, blank=True)
class SitePhpSettings(ProvisioningJob):
account = models.OneToOneField(
HostingAccount,
on_delete=models.CASCADE,
related_name="php_settings_job",
)
domain = DomainNameField(max_length=253)
requested_settings = models.JSONField()
applied_settings = models.JSONField(null=True, blank=True)
applied_at = models.DateTimeField(null=True, blank=True)
class SiteStorageUsage(ProvisioningJob):
account = models.OneToOneField(
HostingAccount, on_delete=models.CASCADE, related_name="storage_usage"
)
domain = DomainNameField(max_length=253)
used_bytes = models.PositiveBigIntegerField(null=True, blank=True)
measured_at = models.DateTimeField(null=True, blank=True)
class SiteStorageLimit(ProvisioningJob):
account = models.OneToOneField(
HostingAccount, on_delete=models.CASCADE, related_name="storage_limit"
)
domain = DomainNameField(max_length=253)
limit_mib = models.PositiveIntegerField(null=True)
applied_mib = models.PositiveIntegerField(null=True)
applied_at = models.DateTimeField(null=True)
class WebHTTPS(ProvisioningJob):
plan = models.OneToOneField(
WebProvisioningPlan, on_delete=models.CASCADE, related_name="https"
)
class Meta:
verbose_name = "website HTTPS request"
class WebsiteAlias(ProvisioningJob):
class Operation(models.TextChoices):
ACTIVATE = "activate", "Activate alias"
HTTPS = "https", "Enable HTTPS"
REMOVE = "remove", "Remove alias"
reservation = models.OneToOneField(
WebsiteDomain, on_delete=models.PROTECT, related_name="alias"
)
primary_domain = DomainNameField(max_length=253)
operation = models.CharField(
max_length=8, choices=Operation, default=Operation.ACTIVATE
)
http_active = models.BooleanField(default=False)
https_active = models.BooleanField(default=False)
class Meta:
indexes = [
models.Index(fields=("operation", "finished_at", "requested_at"))
]
permissions = [
("manage_website_aliases", "Can manage website aliases")
]
class SiteSFTP(ProvisioningJob):
account = models.OneToOneField(
HostingAccount, on_delete=models.CASCADE, related_name="sftp"
)
domain = DomainNameField(max_length=253)
public_keys = models.TextField(blank=True)
requested_customer_id = models.PositiveBigIntegerField(
null=True, blank=True
)
class Meta:
verbose_name = "site SFTP access"
verbose_name_plural = "site SFTP access"
class DatabaseProvisioning(ProvisioningJob):
database = models.OneToOneField(
HostingDatabase, on_delete=models.CASCADE, related_name="provisioning"
)
class AccountBackupJob(ProvisioningJob):
account = models.ForeignKey(
HostingAccount, on_delete=models.CASCADE, related_name="backup_jobs"
)
backup_id = models.UUIDField(
default=uuid.uuid4, unique=True, editable=False
)
manifest = models.JSONField()
scheduled_for = models.DateTimeField(null=True, blank=True)
archive_bytes = models.PositiveBigIntegerField(null=True, blank=True)
retention_protected = models.BooleanField(default=False)
expired_at = models.DateTimeField(null=True, blank=True)
class Meta:
indexes = [models.Index(fields=("finished_at", "requested_at"))]
@property
def archive(self):
return str(backup_archive(self.account_id, self.backup_id))
@property
def includes_mailboxes(self):
return "mailboxes" in self.manifest
@property
def archive_is_restorable(self):
if self.state != "configured" or self.expired_at is not None:
return False
expiration = getattr(self, "expiration", None)
return expiration is None or expiration.finished_at is not None
def can_restore_website(self, site):
return (
self.archive_is_restorable
and self.manifest.get("website") == site.manifest()
)
class AccountBackupExpiration(ProvisioningJob):
backup = models.OneToOneField(
AccountBackupJob, on_delete=models.CASCADE, related_name="expiration"
)
keeper_ids = models.JSONField()
class Meta:
indexes = [models.Index(fields=("finished_at", "requested_at"))]
permissions = [
("manage_backup_retention", "Can manage account backup retention"),
]
class WebsiteRestoreJob(ProvisioningJob):
backup = models.ForeignKey(
AccountBackupJob,
on_delete=models.CASCADE,
related_name="website_restores",
)
restore_id = models.UUIDField(unique=True, editable=False)
filename = models.CharField(max_length=MAX_RESTORE_PATH_BYTES, blank=True)
replace = models.BooleanField(default=False)
operator_username = models.CharField(max_length=150)
class Meta:
indexes = [models.Index(fields=("finished_at", "requested_at"))]
class ComponentRestoreJob(ProvisioningJob):
class Kind(models.TextChoices):
DATABASE = "database", "Database"
MAILBOX = "mailbox", "Mailbox"
backup = models.ForeignKey(
AccountBackupJob,
on_delete=models.CASCADE,
related_name="component_restores",
)
restore_id = models.UUIDField(unique=True, editable=False)
kind = models.CharField(max_length=8, choices=Kind)
resource = models.CharField(max_length=254)
operator_username = models.CharField(max_length=150)
class Meta:
indexes = [models.Index(fields=("finished_at", "requested_at"))]
permissions = [
("restore_account_database", "Can restore an account database"),
("restore_account_mailbox", "Can restore an account mailbox"),
]
@property
def target_name(self):
if self.kind == self.Kind.DATABASE:
return DatabaseSpec(self.backup.account_id, self.resource).name
return self.resource
class AccountBackupSchedule(models.Model):
class Frequency(models.TextChoices):
DAILY = "daily", "Daily"
WEEKLY = "weekly", "Weekly"
class Weekday(models.IntegerChoices):
MONDAY = 0, "Monday"
TUESDAY = 1, "Tuesday"
WEDNESDAY = 2, "Wednesday"
THURSDAY = 3, "Thursday"
FRIDAY = 4, "Friday"
SATURDAY = 5, "Saturday"
SUNDAY = 6, "Sunday"
account = models.OneToOneField(
HostingAccount,
on_delete=models.CASCADE,
related_name="backup_schedule",
)
enabled = models.BooleanField(default=True)
frequency = models.CharField(
max_length=6, choices=Frequency, default=Frequency.DAILY
)
weekday = models.PositiveSmallIntegerField(
choices=Weekday, null=True, blank=True
)
time = models.TimeField("time (UTC)")
include_mailboxes = models.BooleanField(default=False)
next_run_at = models.DateTimeField(null=True, blank=True)
class Meta:
indexes = [models.Index(fields=("enabled", "next_run_at"))]
class DnsPublication(ProvisioningJob):
zone = models.OneToOneField(
HostingDnsZone, on_delete=models.CASCADE, related_name="publication"
)
manifest = models.JSONField()
serial = models.PositiveBigIntegerField()
published_serial = models.PositiveBigIntegerField(null=True, blank=True)
class MailboxProvisioning(ProvisioningJob):
mailbox = models.OneToOneField(
HostingMailbox, on_delete=models.CASCADE, related_name="provisioning"
)
quota_update = models.BooleanField(default=False)
class ServiceHealth(models.Model):
node = models.CharField(max_length=63)
service = models.CharField(max_length=24)
result = models.CharField(max_length=24)
observed_at = models.DateTimeField()
class Meta:
default_permissions = ("view",)
constraints = [
models.UniqueConstraint(
fields=("node", "service"),
name="hosting_service_health_identity",
)
]