Connect hosting workspaces to scoped services and backups

This commit is contained in:
parkel committed 2026-11-23 22:31:20 +01:00
1 parent fd2bdb8a18
commit 377344e591
58 files changed
+2920 -172

No files matched your search

+20 -2
View File
@@ -20,6 +20,7 @@ from .web_node import WebSite
BASE_MANIFEST_VERSION = 1
MAIL_MANIFEST_VERSION = 2
MULTI_SITE_MANIFEST_VERSION = 3
SELECTIVE_MANIFEST_VERSION = 4
MANIFEST_KIND = "coulobre_account_backup"
MANIFEST_NAME = "manifest.json"
MAX_MANIFEST_BYTES = 1024 * 1024
@@ -32,8 +33,13 @@ class AccountBackup:
databases: tuple[DatabaseSpec, ...]
mailboxes: tuple[MailboxSpec, ...] | None = None
additional_websites: tuple[WebSite, ...] = ()
include_website: bool = True
def __post_init__(self):
if type(self.include_website) is not bool or (
not self.include_website and self.additional_websites
):
raise ValueError("Choose whether to include the account websites.")
if self.website.site_id is not None:
raise ValueError(
"The primary website must use its account identity."
@@ -83,6 +89,9 @@ class AccountBackup:
manifest["additional_websites"] = [
site.manifest() for site in self.additional_websites
]
if not self.include_website:
manifest["version"] = SELECTIVE_MANIFEST_VERSION
manifest["include_website"] = False
return manifest
@classmethod
@@ -94,13 +103,20 @@ class AccountBackup:
BASE_MANIFEST_VERSION,
MAIL_MANIFEST_VERSION,
MULTI_SITE_MANIFEST_VERSION,
SELECTIVE_MANIFEST_VERSION,
):
raise ValueError("Unsupported account backup manifest version.")
fields = {"version", "kind", "website", "databases"}
if version == MULTI_SITE_MANIFEST_VERSION:
fields.add("additional_websites")
if version == SELECTIVE_MANIFEST_VERSION:
fields.add("include_website")
if data.get("include_website") is not False:
raise ValueError("Expected a selective account backup.")
if version == MAIL_MANIFEST_VERSION or (
version == MULTI_SITE_MANIFEST_VERSION and "mailboxes" in data
version
in (MULTI_SITE_MANIFEST_VERSION, SELECTIVE_MANIFEST_VERSION)
and "mailboxes" in data
):
fields.add("mailboxes")
if data.keys() != fields or not isinstance(data["databases"], list):
@@ -124,10 +140,12 @@ class AccountBackup:
),
mailboxes,
tuple(WebSite.from_manifest(site) for site in sites),
data.get("include_website", True),
)
def components(self):
yield self.website, "website.json", "website.tar.gz"
if self.include_website:
yield self.website, "website.json", "website.tar.gz"
for site in self.additional_websites:
name = f"websites/{site.node_key}"
yield site, f"{name}.json", f"{name}.tar.gz"
+33 -6
View File
@@ -17,6 +17,7 @@ from .node_requests import serve_apply_request
REQUEST_VERSION = 1
REMOTE_MAIL_VERSION = 2
CUSTOMER_EXPORT_VERSION = 3
BACKUP_DIRECTORY = Path("/var/lib/coulobre/account-backups")
BACKUP_SOCKET = "/run/coulobre-account-backup.sock"
BACKUP_TIMEOUT_SECONDS = 30 * 60
@@ -27,33 +28,53 @@ class AccountBackupRequest:
backup_id: UUID
backup: AccountBackup
remote_mail: bool = False
publish_to_customer: bool = False
@classmethod
def from_manifest(cls, data):
if not isinstance(data, dict) or type(data.get("version")) is not int:
raise ValueError("Expected a local account backup request.")
version = data["version"]
fields = {"version", "backup_id", "backup"}
if version == CUSTOMER_EXPORT_VERSION:
fields.add("remote_mail")
if (
not isinstance(data, dict)
or data.keys() != {"version", "backup_id", "backup"}
or type(data["version"]) is not int
or data["version"] not in (REQUEST_VERSION, REMOTE_MAIL_VERSION)
data.keys() != fields
or version
not in (
REQUEST_VERSION,
REMOTE_MAIL_VERSION,
CUSTOMER_EXPORT_VERSION,
)
or not isinstance(data["backup_id"], str)
or type(data.get("remote_mail", False)) is not bool
):
raise ValueError("Expected a local account backup request.")
backup_id = UUID(data["backup_id"])
if str(backup_id) != data["backup_id"]:
raise ValueError("Expected a canonical backup ID.")
backup = AccountBackup.from_manifest(data["backup"])
remote_mail = data["version"] == REMOTE_MAIL_VERSION
remote_mail = version == REMOTE_MAIL_VERSION or data.get(
"remote_mail", False
)
if remote_mail and backup.mailboxes is None:
raise ValueError(
"Expected mailboxes in the remote backup request."
)
return cls(backup_id, backup, remote_mail)
return cls(
backup_id, backup, remote_mail, version == CUSTOMER_EXPORT_VERSION
)
def manifest(self):
return {
"version": self.version,
"backup_id": str(self.backup_id),
"backup": self.backup.manifest(),
**(
{"remote_mail": self.remote_mail}
if self.publish_to_customer
else {}
),
}
def identity(self):
@@ -65,6 +86,8 @@ class AccountBackupRequest:
@property
def version(self):
if self.publish_to_customer:
return CUSTOMER_EXPORT_VERSION
return REMOTE_MAIL_VERSION if self.remote_mail else REQUEST_VERSION
@@ -120,6 +143,10 @@ def create_requested_backup(request):
)
with locked_root_directory(BACKUP_DIRECTORY):
archive = ensure_requested_archive(request)
if request.publish_to_customer:
from .customer_backup_export import export_latest_backup
export_latest_backup(request.backup.website, archive)
return {"archive_bytes": archive.stat().st_size}
+74
View File
@@ -0,0 +1,74 @@
import fcntl
import os
import shutil
import stat
from pathlib import Path
from tempfile import NamedTemporaryFile
from .node_files import check_root_file, require_root_directory
from .web_node_apply import (
SitePaths,
check_reservation,
current_user,
locked_web_node,
)
def export_latest_backup(site, archive):
# A root-owned directory protects the published export.
with locked_web_node(fcntl.LOCK_EX):
check_reservation(site)
account = SitePaths.for_site(site).account
require_root_directory(account)
user = current_user(site.service_user)
if (
user is None
or user.pw_uid <= 0
or user.pw_gid <= 0
or user.pw_dir != str(account)
):
raise ValueError("The hosting account has no matching SFTP login.")
destination = account / "backups"
try:
destination.mkdir(mode=0o700)
except FileExistsError:
pass
else:
os.chown(destination, 0, user.pw_gid, follow_symlinks=False)
destination.chmod(0o750)
info = destination.lstat()
if (
not stat.S_ISDIR(info.st_mode)
or info.st_uid != 0
or info.st_gid != user.pw_gid
or stat.S_IMODE(info.st_mode) != 0o750
or account.stat().st_dev != info.st_dev
):
raise ValueError(
"The backup directory has unexpected ownership or permissions."
)
latest = destination / "latest.zip"
if os.path.lexists(latest):
info = latest.lstat()
if (
not stat.S_ISREG(info.st_mode)
or info.st_uid != user.pw_uid
or info.st_nlink != 1
):
raise ValueError(
"The previous backup export has unexpected ownership "
"or type."
)
check_root_file(archive, mode=0o600)
with NamedTemporaryFile(dir=destination, delete=False) as staged:
temporary = Path(staged.name)
try:
with archive.open("rb") as source:
shutil.copyfileobj(source, staged, length=1024 * 1024)
staged.flush()
os.fchown(staged.fileno(), user.pw_uid, user.pw_gid)
os.fchmod(staged.fileno(), 0o400)
os.fsync(staged.fileno())
os.replace(temporary, latest)
finally:
temporary.unlink(missing_ok=True)
+127 -61
View File
@@ -12,6 +12,8 @@ from django.db import IntegrityError, transaction
from django.db.models import Count, Q
from django.shortcuts import redirect
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic import FormView, ListView
from coulobre.domain_names import canonical_domain
@@ -23,8 +25,18 @@ from .installation_features import (
default_dns_zones_allowed,
panel_feature_allowed,
)
from .invitations import InviteLoginForm, queue_invitation
from .models import Customer, HostingAccount, HostingPlan, Reseller
from .invitations import (
InviteLoginForm,
queue_invitation,
render_welcome_message,
)
from .models import (
Customer,
DomainServicePolicy,
HostingAccount,
HostingPlan,
Reseller,
)
from .reseller_accounts import (
create_reseller_account,
lock_resellers,
@@ -102,6 +114,9 @@ class ManagerOnboardingForm(InviteLoginForm):
return cleaned
@method_decorator(
sensitive_post_parameters("initial_password"), name="dispatch"
)
class ManagerOnboardingView(UserPassesTestMixin, FormView):
form_class = ManagerOnboardingForm
template_name = "hosting/workspace_form.html"
@@ -123,6 +138,22 @@ class ManagerOnboardingView(UserPassesTestMixin, FormView):
def form_valid(self, form):
data = form.cleaned_data
if self.request.POST.get("action") == "preview":
defaults = zone_defaults()
preview = render_welcome_message(
username=data["username"],
welcome_message=data["welcome_message"],
setup_url="[Personal password setup link]",
account=HostingAccount(
primary_domain=data["primary_domain"],
hosting_plan=data["plan"],
),
nameservers=defaults.nameservers if data["manage_dns"] else (),
mail_configured=data["manage_mail"],
)
return self.render_to_response(
self.get_context_data(form=form, welcome_preview=preview)
)
try:
with transaction.atomic():
user = form.save(commit=False)
@@ -139,6 +170,12 @@ class ManagerOnboardingView(UserPassesTestMixin, FormView):
hosting_plan=data["plan"],
)
create_reseller_account(self.manager, account)
DomainServicePolicy.objects.create(
account=account,
domain=account.primary_domain,
dns_managed=data["manage_dns"],
mail_managed=data["manage_mail"],
)
defaults = zone_defaults()
setup_new_account(
account,
@@ -239,6 +276,9 @@ class OperatorLoginForm(UserCreationForm):
fields = ("username", "email")
@method_decorator(
sensitive_post_parameters("password1", "password2"), name="dispatch"
)
class OperatorCreateView(OperatorAuthorization, FormView):
form_class = OperatorLoginForm
template_name = "hosting/workspace_form.html"
@@ -274,7 +314,8 @@ class MoveHostingForm(forms.Form):
)
)
confirm = forms.BooleanField(
label="I reviewed the destination and its hosting plan policy"
required=False,
label="I reviewed the destination and its hosting plan policy",
)
@@ -283,71 +324,96 @@ class MoveHostingView(OperatorAuthorization, FormView):
template_name = "hosting/workspace_form.html"
extra_context = {
"title": "Move hosting to another manager",
"submit_label": "Move hosting account",
"submit_label": "Move hosting",
"move_preview_enabled": True,
}
def form_valid(self, form):
selected = form.cleaned_data["account"]
chosen = form.cleaned_data["manager"]
try:
with transaction.atomic():
account = lock_hosting_account(
form.cleaned_data["account"].pk, customer_id=None
)
require_open_account(account)
if account.reseller_id == chosen.pk:
raise ValidationError("Choose a different manager.")
managers = lock_resellers(
Reseller.objects.filter(
pk__in=[chosen.pk, account.reseller_id]
)
).select_related("user")
destination = next(
(
manager
for manager in managers
if manager.pk == chosen.pk
),
None,
)
if destination is None or not destination.user.is_active:
raise ValidationError(
"The destination is no longer available."
)
if (
destination.hostingaccount_set.filter(
retired_at__isnull=True
).count()
>= destination.account_limit
or not destination.hosting_plans.filter(
pk=account.hosting_plan_id
).exists()
):
raise ValidationError(
"The destination must have room and allow this plan."
)
customer_id = account.customer_id
if customer_id is not None:
customer = Customer.objects.select_for_update().get(
pk=customer_id
)
if (
customer.hostingaccount_set.exclude(pk=account.pk)
.filter(retired_at__isnull=True)
.exists()
):
raise ValidationError(
"This customer has other active hosting accounts. "
"Move them together when changing their manager."
)
customer.reseller = destination
customer.save(update_fields=["reseller"])
account.reseller = destination
save_operator_account(
account,
self.request.user.get_username(),
changed_fields=["reseller"],
)
return self.review_or_move(form, selected, chosen)
except ValidationError as error:
form.add_error(None, ValidationError(error.messages))
return self.form_invalid(form)
def review_or_move(self, form, selected, chosen):
account = lock_hosting_account(selected.pk, customer_id=None)
require_open_account(account)
accounts = [account]
customer = None
if account.customer_id:
customer = Customer.objects.select_for_update().get(
pk=account.customer_id
)
account_ids = (
customer.hostingaccount_set.filter(retired_at__isnull=True)
.exclude(pk=account.pk)
.order_by("pk")
.values_list("pk", flat=True)
)
accounts.extend(
lock_hosting_account(pk, customer_id=customer.pk)
for pk in account_ids
)
if all(item.reseller_id == chosen.pk for item in accounts):
raise ValidationError("Choose a different manager.")
managers = lock_resellers(
Reseller.objects.filter(
pk__in={chosen.pk}
| {item.reseller_id for item in accounts if item.reseller_id}
)
).select_related("user")
destination = next(
(manager for manager in managers if manager.pk == chosen.pk),
None,
)
if destination is None or not destination.user.is_active:
raise ValidationError("The destination is no longer available.")
moving = [item for item in accounts if item.reseller_id != chosen.pk]
allowed_plans = set(
destination.hosting_plans.values_list("pk", flat=True)
)
if destination.hostingaccount_set.count() + len(
moving
) > destination.account_limit or any(
item.hosting_plan_id not in allowed_plans for item in moving
):
raise ValidationError(
"The destination must have room and allow every hosting plan."
)
revision = [
destination.pk,
[
[item.pk, item.reseller_id, item.hosting_plan_id]
for item in accounts
],
]
if self.request.POST.get("action") != "move":
self.request.session["move_hosting_preview"] = revision
return self.render_to_response(
self.get_context_data(
form=form, moving=moving, destination=destination
)
)
if (
not form.cleaned_data["confirm"]
or self.request.session.pop("move_hosting_preview", None)
!= revision
):
raise ValidationError(
"Preview and confirm the transfer before moving hosting."
)
if customer:
customer.reseller = destination
customer.save(update_fields=["reseller"])
for item in moving:
item.reseller = destination
save_operator_account(
item,
self.request.user.get_username(),
changed_fields=["reseller"],
)
messages.success(self.request, "The hosting accounts were moved.")
return redirect(account)
+42 -7
View File
@@ -25,7 +25,13 @@ def mail_backups_enabled():
)
def account_backup_manifest(account, *, include_mailboxes=False):
def account_backup_manifest(
account,
*,
include_mailboxes=False,
include_website=True,
include_databases=True,
):
mailboxes = None
if include_mailboxes:
requests = HostingMailbox.objects.filter(
@@ -34,32 +40,61 @@ def account_backup_manifest(account, *, include_mailboxes=False):
mailboxes = tuple(mailbox.spec for mailbox in requests)
return AccountBackup(
WebSite(account.pk, account.primary_domain),
tuple(database.spec for database in account.databases.all()),
tuple(database.spec for database in account.databases.all())
if include_databases
else (),
mailboxes,
tuple(site.spec for site in active_websites(account)),
tuple(site.spec for site in active_websites(account))
if include_website
else (),
include_website,
).manifest()
@transaction.atomic
def queue_account_backup(
account_id, *, include_mailboxes=False, customer_id=None
account_id,
*,
include_mailboxes=False,
customer_id=None,
include_website=True,
include_databases=True,
):
account = lock_hosting_account(account_id, customer_id=customer_id)
require_open_account(account)
_enqueue_backup(account, include_mailboxes=include_mailboxes)
if not any((include_mailboxes, include_website, include_databases)):
raise ValidationError("Select at least one backup component.")
_enqueue_backup(
account,
include_mailboxes=include_mailboxes,
include_website=include_website,
include_databases=include_databases,
export_customer_id=customer_id,
)
def _enqueue_backup(
account, *, include_mailboxes, scheduled_for=None, offsite_destination=""
account,
*,
include_mailboxes,
scheduled_for=None,
offsite_destination="",
include_website=True,
include_databases=True,
export_customer_id=None,
):
if not account.backup_jobs.filter(finished_at__isnull=True).exists():
job = account.backup_jobs.create(
manifest=account_backup_manifest(
account, include_mailboxes=include_mailboxes
account,
include_mailboxes=include_mailboxes,
include_website=include_website,
include_databases=include_databases,
),
remote_mail=include_mailboxes
and settings.REMOTE_ACCOUNT_BACKUP_MAIL,
scheduled_for=scheduled_for,
export_customer_id=export_customer_id,
)
if scheduled_for is not None and offsite_destination:
OffsiteBackupTransfer.objects.create(
+17 -4
View File
@@ -76,11 +76,20 @@ def available_website_restore_targets(backup, current=None):
@transaction.atomic
def queue_website_restore(
backup, *, restore_id, filename, replace, operator_username, site_key=None
backup,
*,
restore_id,
filename,
replace,
operator_username,
site_key=None,
customer_id=None,
):
account = lock_hosting_account(backup.account_id, customer_id=None)
account = lock_hosting_account(backup.account_id, customer_id=customer_id)
require_active_services(account)
backup.refresh_from_db()
if customer_id is not None and backup.export_customer_id != customer_id:
raise ValidationError("This backup is no longer available.")
backup.account = account
targets = available_website_restore_targets(backup)
site = targets.get(site_key or str(account.pk))
@@ -96,6 +105,7 @@ def queue_website_restore(
operator_username,
{
"filename": filename,
"requested_customer_id": customer_id,
"replace": replace,
"site_manifest": site.manifest()
if site.site_id is not None
@@ -110,11 +120,13 @@ def queue_website_restore(
@transaction.atomic
def queue_component_restore(
backup, *, restore_id, kind, resource, operator_username
backup, *, restore_id, kind, resource, operator_username, customer_id=None
):
account = lock_hosting_account(backup.account_id, customer_id=None)
account = lock_hosting_account(backup.account_id, customer_id=customer_id)
require_active_services(account)
backup.refresh_from_db()
if customer_id is not None and backup.export_customer_id != customer_id:
raise ValidationError("This backup is no longer available.")
targets = available_restore_resources(
backup, kind, current_restore_resources(account, kind)
)
@@ -128,6 +140,7 @@ def queue_component_restore(
operator_username,
{
"kind": kind,
"requested_customer_id": customer_id,
"resource": resource,
"remote_mail": kind == RestoreKind.MAILBOX
and settings.REMOTE_MAILBOX_RESTORE,
+174 -4
View File
@@ -1,4 +1,5 @@
from django import forms
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.mixins import UserPassesTestMixin
from django.core.exceptions import ValidationError
@@ -8,12 +9,28 @@ from django.utils.functional import cached_property
from django.views.generic import FormView
from .access import customer_for_user
from .account_backup_forms import ComponentRestoreForm, WebsiteRestoreForm
from .account_backups import mail_backups_enabled, queue_account_backup
from .backup_restores import (
available_restore_resources,
available_website_restore_targets,
current_restore_resources,
enabled_component_restores,
queue_component_restore,
queue_website_restore,
)
from .installation_features import panel_feature_allowed
from .models import HostingAccount
from .models import ComponentRestoreJob, HostingAccount, WebsiteRestoreJob
from .sftp import site_is_active
class CustomerBackupForm(forms.Form):
include_website = forms.BooleanField(
required=False, initial=True, label="Include websites"
)
include_databases = forms.BooleanField(
required=False, initial=True, label="Include databases"
)
include_mailboxes = forms.BooleanField(
required=False, label="Include mailboxes"
)
@@ -40,16 +57,71 @@ class CustomerBackupView(UserPassesTestMixin, FormView):
form.fields["include_mailboxes"].disabled = not mail_backups_enabled()
return form
def can_export(self):
return (
panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS")
and settings.LOCAL_WEB_SFTP
and site_is_active(self.account)
)
def get_context_data(self, **kwargs):
backups = (
self.account.backup_jobs.filter(
export_customer_id=self.account.customer_id
)
.select_related("expiration")
.order_by("-requested_at")[:30]
)
kinds = enabled_component_restores()
current = {
kind: current_restore_resources(self.account, kind)
for kind in kinds
}
return super().get_context_data(
account=self.account,
backups=self.account.backup_jobs.order_by("-requested_at")[:30],
may_create=panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS"),
backups=[
(
backup,
[
*(
["website"]
if settings.LOCAL_WEBSITE_RESTORE
and available_website_restore_targets(backup)
else []
),
*(
kind
for kind, resources in current.items()
if available_restore_resources(
backup, kind, resources
)
),
],
)
for backup in backups
],
may_create=self.can_export(),
restores=[
*self.website_restores(),
*self.component_restores(),
],
**kwargs,
)
def website_restores(self):
return WebsiteRestoreJob.objects.filter(
backup__account=self.account,
requested_customer_id=self.account.customer_id,
).order_by("-requested_at")[:15]
def component_restores(self):
return ComponentRestoreJob.objects.filter(
backup__account=self.account,
requested_customer_id=self.account.customer_id,
).order_by("-requested_at")[:15]
def form_valid(self, form):
if not panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS"):
if not self.can_export():
raise Http404
customer = customer_for_user(self.request.user)
try:
@@ -57,6 +129,8 @@ class CustomerBackupView(UserPassesTestMixin, FormView):
self.account.pk,
include_mailboxes=form.cleaned_data["include_mailboxes"],
customer_id=customer.pk,
include_website=form.cleaned_data["include_website"],
include_databases=form.cleaned_data["include_databases"],
)
except HostingAccount.DoesNotExist as error:
raise Http404 from error
@@ -65,3 +139,99 @@ class CustomerBackupView(UserPassesTestMixin, FormView):
return self.form_invalid(form)
messages.success(self.request, "Backup requested.")
return redirect("panel:customer_backups", pk=self.account.pk)
class CustomerRestoreView(CustomerBackupView):
template_name = "hosting/customer_restore.html"
@cached_property
def kind(self):
kind = self.kwargs["kind"]
if (
not panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS")
or (kind == "website" and not settings.LOCAL_WEBSITE_RESTORE)
or (kind != "website" and kind not in enabled_component_restores())
):
raise Http404
return kind
@cached_property
def backup(self):
backup = get_object_or_404(
self.account.backup_jobs.select_related("account", "expiration"),
pk=self.kwargs["backup_pk"],
export_customer_id=self.account.customer_id,
)
if not backup.archive_is_restorable:
raise Http404
return backup
@cached_property
def targets(self):
if self.kind == "website":
targets = available_website_restore_targets(self.backup)
else:
targets = available_restore_resources(
self.backup,
self.kind,
current_restore_resources(self.account, self.kind),
)
if not targets:
raise Http404
return targets
def get_form(self, form_class=None):
form_class = (
WebsiteRestoreForm
if self.kind == "website"
else ComponentRestoreForm
)
return form_class(targets=self.targets, **self.get_form_kwargs())
def get_context_data(self, **kwargs):
return FormView.get_context_data(
self,
account=self.account,
backup=self.backup,
kind=self.kind,
**kwargs,
)
def form_valid(self, form):
data = form.cleaned_data.copy()
revision = {
"backup": self.backup.pk,
"kind": self.kind,
"fields": data | {"restore_id": str(data["restore_id"])},
}
if self.request.POST.get("action") != "restore":
self.request.session["customer_restore_preview"] = revision
target = self.targets[data.get("site_key") or data["resource"]]
return self.render_to_response(
self.get_context_data(form=form, target=target, preview=data)
)
if (
self.request.session.pop("customer_restore_preview", None)
!= revision
):
form.add_error(None, "Review the destination before restoring.")
return self.form_invalid(form)
try:
common = {
"operator_username": self.request.user.get_username(),
"customer_id": self.account.customer_id,
}
if self.kind == "website":
data.pop("scope")
queue_website_restore(self.backup, **common, **data)
else:
queue_component_restore(
self.backup, kind=self.kind, **common, **data
)
except HostingAccount.DoesNotExist as error:
raise Http404 from error
except ValidationError as error:
form.add_error(None, error)
return self.form_invalid(form)
messages.success(self.request, "Restore requested.")
return redirect("panel:customer_backups", pk=self.account.pk)
+2
View File
@@ -6,6 +6,7 @@ from django.db.models import Q
from coulobre.dns_node import DNS_REQUEST_LIMIT
from .access import is_tenant, manages_account
from .domain_policies import require_managed
from .models import DnsPublication, HostingDnsZone
from .node_client import encode_manifest
from .resource_requests import lock_hosting_account, require_open_account
@@ -33,6 +34,7 @@ def publish_for_account(account_id, zone_id, expected_serial, *, actor=None):
):
raise PermissionDenied
require_open_account(account)
require_managed(account, zone.domain, "dns_managed")
if str(zone.serial) != expected_serial:
raise ValueError(
"This zone changed before publication. "
+15
View File
@@ -0,0 +1,15 @@
from django.core.exceptions import ValidationError
from .models import DomainServicePolicy
def policy_for(account, domain):
policy = DomainServicePolicy.objects.filter(
account=account, domain=domain
).first()
return policy or DomainServicePolicy(account=account, domain=domain)
def require_managed(account, domain, field):
if not getattr(policy_for(account, domain), field):
raise ValidationError("This domain uses an external service provider.")
+176
View File
@@ -0,0 +1,176 @@
from django import forms
from django.contrib import messages
from django.core.exceptions import PermissionDenied, ValidationError
from django.db import transaction
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_http_methods
from coulobre.domain_names import canonical_domain
from .access import customer_for_user
from .dns_forms import zone_record_rows
from .domain_policies import policy_for
from .independent_websites import account_websites
from .installation_features import panel_feature_allowed
from .models import DomainServicePolicy, HostingAccount
from .resource_requests import lock_hosting_account, require_open_account
from .sftp import site_is_active
DNS_PUBLISHING = "LOCAL_DNS_PUBLISHING"
MAIL_PROVISIONING = "LOCAL_MAILBOX_PROVISIONING"
class DomainServicesForm(forms.Form):
dns_managed = forms.BooleanField(
required=False, label="Manage DNS in Coulobre"
)
mail_managed = forms.BooleanField(
required=False, label="Manage email in Coulobre"
)
def clean(self):
cleaned = super().clean()
for field, feature in (
("dns_managed", DNS_PUBLISHING),
("mail_managed", MAIL_PROVISIONING),
):
if (
cleaned.get(field)
and field in self.changed_data
and not panel_feature_allowed(feature)
):
self.add_error(
field, "This managed service needs setup on the server."
)
return cleaned
def allowed_domains(account):
domains = {account.primary_domain}
domains.update(
account_websites(account)
.filter(retired_at__isnull=True)
.values_list("reservation__domain", flat=True)
)
domains.update(
account.website_domains.filter(alias__isnull=False).values_list(
"domain", flat=True
)
)
return sorted(domains)
@transaction.atomic
def save_domain_policy(account_id, domain, customer_id, choices):
account = lock_hosting_account(account_id, customer_id=customer_id)
require_open_account(account)
if domain not in allowed_domains(account):
raise Http404
DomainServicePolicy.objects.update_or_create(
account=account, domain=domain, defaults=choices
)
@never_cache
@require_http_methods(("GET", "HEAD", "POST"))
def domain_workspace(request, pk, page):
if page not in {"domains", "dns", "php", "files", "forwarders", "replies"}:
raise Http404
customer = customer_for_user(request.user)
if customer is None:
raise PermissionDenied
account = get_object_or_404(
HostingAccount, pk=pk, customer=customer, retired_at__isnull=True
)
domains = allowed_domains(account)
try:
domain = canonical_domain(
request.GET.get("domain", account.primary_domain)
)
except ValueError as error:
raise Http404 from error
if domain not in domains:
raise Http404
policy = policy_for(account, domain)
initial = {
field: getattr(policy, field)
for field in ("dns_managed", "mail_managed")
}
form = DomainServicesForm(
request.POST if request.method == "POST" else None, initial=initial
)
destination = reverse(
"panel:domain_workspace",
args=[account.pk, page],
query={"domain": domain},
)
if request.method == "POST":
if page != "domains":
raise PermissionDenied
if form.is_valid():
try:
save_domain_policy(
account.pk, domain, customer.pk, form.cleaned_data
)
except HostingAccount.DoesNotExist as error:
raise Http404 from error
except ValidationError as error:
form.add_error(None, error)
else:
messages.success(request, "Domain service preferences saved.")
return redirect(destination)
website = (
account_websites(account)
.filter(
reservation__domain=domain,
activated=True,
retired_at__isnull=True,
suspended=False,
)
.first()
)
primary = domain == account.primary_domain and site_is_active(account)
zone = (
account.dns_zones.filter(domain=domain).first()
if page == "dns"
else None
)
mail_domain = (
account.mail_domains.filter(domain=domain).first()
if page in {"forwarders", "replies"}
else None
)
titles = {
"domains": "Domains",
"dns": "DNS Editor",
"php": "PHP Settings",
"files": "File Manager",
"forwarders": "Forwarders",
"replies": "Automatic replies",
}
return render(
request,
"hosting/domain_workspace.html",
{
"title": titles[page],
"page": page,
"account": account,
"domains": domains,
"domain": domain,
"form": form,
"policy": policy,
"zone": zone,
"records": zone_record_rows(zone.spec) if zone else (),
"mail_domain": mail_domain,
"website": website,
"primary": primary,
"can_add_site": panel_feature_allowed("LOCAL_WEB_ACTIVATION"),
"may_edit_dns": bool(
zone and zone.delegate_dns and policy.dns_managed
),
},
)
+70 -5
View File
@@ -1,12 +1,14 @@
from importlib.metadata import PackageNotFoundError, version
from django import forms
from django.conf import settings
from django.contrib import messages
from django.contrib.admin.models import CHANGE, LogEntry
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.db import transaction
from django.db.models import F
from django.urls import reverse_lazy
from django.http import Http404
from django.urls import reverse, reverse_lazy
from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache
from django.views.generic import FormView, TemplateView
@@ -47,14 +49,45 @@ class InstallationView(LoginRequiredMixin, TemplateView):
)
OPERATOR_FEATURE_SECTIONS = {
"general": ("General", ()),
"server": (
"Server",
(
"LOCAL_WEB_ACTIVATION",
"WEB_FILE_MANAGER",
"WEBSITE_JOBS",
"LOCAL_DNS_PUBLISHING",
"DEFAULT_DNS_ZONES",
),
),
"security": ("Security", ("LOCAL_WEB_HTTPS",)),
"email": (
"Email",
("LOCAL_MAILBOX_PROVISIONING", "MANAGE_MAIL_DNS", "ROUNDCUBE_URL"),
),
"database": (
"Database",
("LOCAL_DATABASE_PROVISIONING", "PHPMYADMIN_URL"),
),
"backups": (
"Backups",
("LOCAL_ACCOUNT_BACKUPS", "OFFSITE_BACKUP_DESTINATIONS"),
),
}
class FeatureConfigurationForm(forms.Form):
revision = forms.IntegerField(min_value=0, widget=forms.HiddenInput)
def __init__(self, *args, policy, **kwargs):
def __init__(self, *args, policy, section=None, **kwargs):
super().__init__(*args, **kwargs)
self.initial["revision"] = policy.saved.revision
self.configured_features = [
feature for feature in FEATURES if feature.configured
feature
for feature in FEATURES
if (section is None or feature.setting in section)
and feature.configured
]
for feature in self.configured_features:
self.fields[feature.setting] = forms.BooleanField(
@@ -98,7 +131,11 @@ def check_features(form, changed):
)
if (
feature.setting == "DEFAULT_DNS_ZONES"
and not form.cleaned_data.get("LOCAL_DNS_PUBLISHING")
and not form.cleaned_data.get(
"LOCAL_DNS_PUBLISHING",
settings.LOCAL_DNS_PUBLISHING
and "LOCAL_DNS_PUBLISHING" not in FeaturePolicy().disabled,
)
):
form.add_error(feature.setting, "Enable DNS publishing first.")
@@ -115,7 +152,35 @@ class FeatureConfigurationView(UserPassesTestMixin, FormView):
)
def get_form_kwargs(self):
return {**super().get_form_kwargs(), "policy": FeaturePolicy()}
section = self.kwargs.get("section")
if section is not None and section not in OPERATOR_FEATURE_SECTIONS:
raise Http404
return super().get_form_kwargs() | {
"policy": FeaturePolicy(),
"section": (
OPERATOR_FEATURE_SECTIONS[section][1]
if section is not None
else None
),
}
def get_context_data(self, **kwargs):
section = self.kwargs.get("section")
return super().get_context_data(
selected_section=section,
settings_tabs=tuple(
(key, label)
for key, (label, _) in OPERATOR_FEATURE_SECTIONS.items()
)
if section
else (),
**kwargs,
)
def get_success_url(self):
if "section" in self.kwargs:
return reverse("panel:operator_settings", kwargs=self.kwargs)
return super().get_success_url()
def form_valid(self, form):
revision = form.cleaned_data["revision"]
+42 -23
View File
@@ -179,29 +179,18 @@ def deliver_invitation(invitation_id, revision):
if account
else None
)
message = render_to_string(
"hosting/panel_invitation.txt",
{
"username": user.get_username(),
"welcome_message": invitation.welcome_message,
"setup_url": origin + path,
"panel_url": origin + "/",
"account": account,
"nameservers": zone.nameservers if zone else (),
"website_records": (
website_records(account.primary_domain, wildcard=False)
if account and zone is None
else ()
),
"imap_host": settings.MAIL_IMAP_HOST,
"submission_host": settings.MAIL_SUBMISSION_HOST,
"mail_configured": bool(
account
and account.mail_domains.filter(
domain=account.primary_domain
).exists()
),
},
message = render_welcome_message(
username=user.get_username(),
welcome_message=invitation.welcome_message,
setup_url=origin + path,
account=account,
nameservers=zone.nameservers if zone else (),
mail_configured=bool(
account
and account.mail_domains.filter(
domain=account.primary_domain
).exists()
),
)
try:
sent = send_mail(
@@ -215,6 +204,36 @@ def deliver_invitation(invitation_id, revision):
pending.update(delivery=PanelInvitation.Delivery.SENT)
def render_welcome_message(
*,
username,
welcome_message,
setup_url,
account,
nameservers,
mail_configured,
):
return render_to_string(
"hosting/panel_invitation.txt",
{
"username": username,
"welcome_message": welcome_message,
"setup_url": setup_url,
"panel_url": settings.PASSWORD_RESET_ORIGIN.rstrip("/") + "/",
"account": account,
"nameservers": nameservers,
"website_records": (
website_records(account.primary_domain, wildcard=False)
if account and not nameservers
else ()
),
"imap_host": settings.MAIL_IMAP_HOST,
"submission_host": settings.MAIL_SUBMISSION_HOST,
"mail_configured": mail_configured,
},
)
class AcceptInvitation(PasswordResetConfirmView):
template_name = "hosting/accept_invitation.html"
token_generator = invitation_token
+75 -5
View File
@@ -1,18 +1,23 @@
from datetime import timedelta
from django import forms
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.exceptions import PermissionDenied
from django.db import transaction
from django.http import Http404
from django.http import Http404, HttpResponseBadRequest
from django.shortcuts import get_object_or_404, redirect
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache
from django.views.generic import TemplateView
from django.views.decorators.http import require_POST
from django.views.generic import ListView, TemplateView
from coulobre.mail_queue import QUEUE_ACTIONS, MailQueueAction
from .access import OperatorOnlyMixin
from .installation_features import panel_feature_allowed
from .models import HostingMailDomain
from .tasks import refresh_mail_queue
from .models import HostingMailDomain, MailQueueOperation
from .tasks import refresh_mail_queue, run_mail_queue_operation
@method_decorator(never_cache, name="dispatch")
@@ -35,7 +40,11 @@ class MailQueueView(OperatorOnlyMixin, PermissionRequiredMixin, TemplateView):
def get_context_data(self, **kwargs):
return super().get_context_data(
mail_domain=self.get_domain(), **kwargs
mail_domain=(domain := self.get_domain()),
operations=MailQueueOperation.objects.filter(
domain=domain
).order_by("-pk")[:10],
**kwargs,
)
def post(self, request, *args, **kwargs):
@@ -54,3 +63,64 @@ class MailQueueView(OperatorOnlyMixin, PermissionRequiredMixin, TemplateView):
)
)
return redirect("panel:mail_queue", pk=domain.pk)
class MailQueueActionForm(forms.Form):
queue_id = forms.CharField(max_length=32)
arrival = forms.IntegerField(min_value=1, max_value=2**53 - 1)
action = forms.ChoiceField(
choices=[(key, key.capitalize()) for key in QUEUE_ACTIONS]
)
@require_POST
def mail_queue_action(request, pk):
if not request.user.is_superuser or not request.user.is_verified():
raise PermissionDenied
if not panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING"):
raise Http404
form = MailQueueActionForm(request.POST)
if not form.is_valid():
return HttpResponseBadRequest("Choose a queue entry and action.")
data = form.cleaned_data
try:
with transaction.atomic():
domain = get_object_or_404(
HostingMailDomain.objects.select_for_update(),
pk=pk,
account__retired_at__isnull=True,
)
if not any(
entry.get("queue_id") == data["queue_id"]
and entry.get("arrival") == data["arrival"]
for entry in domain.queue_report.get("entries", [])
):
return HttpResponseBadRequest(
"Refresh the queue before requesting an action."
)
spec = MailQueueAction(domain.domain, **data)
if not MailQueueOperation.objects.filter(
domain=domain, queue_id=spec.queue_id, finished_at__isnull=True
).exists():
job = MailQueueOperation.objects.create(
domain=domain, actor=request.user, **data
)
transaction.on_commit(
lambda: run_mail_queue_operation.delay(job.pk)
)
except ValueError:
return HttpResponseBadRequest("Choose a queue entry and action.")
return redirect("panel:mail_queue", pk=pk)
class MailQueueIndex(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
permission_required = MailQueueView.permission_required
model = HostingMailDomain
context_object_name = "domains"
template_name = "hosting/mail_queue_index.html"
paginate_by = 40
def get_queryset(self):
return HostingMailDomain.objects.filter(
account__retired_at__isnull=True
).order_by("domain")
@@ -0,0 +1,50 @@
# Generated by Django 5.2.19 on 2026-11-23 21:11
import django.db.models.deletion
from django.db import migrations, models
import coulobre.hosting.fields
class Migration(migrations.Migration):
dependencies = [
("hosting", "0060_welcome_message"),
]
operations = [
migrations.CreateModel(
name="DomainServicePolicy",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"domain",
coulobre.hosting.fields.DomainNameField(max_length=253),
),
("dns_managed", models.BooleanField(default=True)),
("mail_managed", models.BooleanField(default=True)),
(
"account",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="hosting.hostingaccount",
),
),
],
options={
"constraints": [
models.UniqueConstraint(
fields=("account", "domain"),
name="hosting_unique_domain_service_policy",
)
],
},
),
]
@@ -0,0 +1,96 @@
# Generated by Django 5.2.19 on 2026-11-23 21:14
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0061_domain_service_policy"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="PanelTheme",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(max_length=80, unique=True)),
("colors", models.JSONField()),
],
),
migrations.CreateModel(
name="PanelAnnouncement",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"audience",
models.CharField(
choices=[
("all", "All users"),
("managers", "Managers"),
],
max_length=8,
),
),
("subject", models.CharField(max_length=140)),
("body", models.TextField(max_length=4000)),
("published_at", models.DateTimeField(auto_now_add=True)),
(
"author",
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
to=settings.AUTH_USER_MODEL,
),
),
],
),
migrations.CreateModel(
name="UserTheme",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"theme",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
to="hosting.paneltheme",
),
),
(
"user",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
],
),
]
@@ -0,0 +1,65 @@
# Generated by Django 5.2.19 on 2026-11-23 21:16
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0062_panel_themes_and_announcements"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="OperatorOperation",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"requested_at",
models.DateTimeField(default=django.utils.timezone.now),
),
(
"last_dispatched_at",
models.DateTimeField(blank=True, null=True),
),
("started_at", models.DateTimeField(blank=True, null=True)),
("finished_at", models.DateTimeField(blank=True, null=True)),
("problem", models.TextField(blank=True)),
("action", models.CharField(max_length=24)),
("target", models.CharField(blank=True, max_length=20)),
("plan", models.CharField(blank=True, max_length=64)),
("result", models.JSONField(default=dict)),
(
"actor",
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
to=settings.AUTH_USER_MODEL,
),
),
(
"source",
models.OneToOneField(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
to="hosting.operatoroperation",
),
),
],
options={
"abstract": False,
},
),
]
@@ -0,0 +1,17 @@
# Generated by Django 5.2.19 on 2026-11-23 21:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0063_operator_operations"),
]
operations = [
migrations.AddField(
model_name="accountbackupjob",
name="export_customer_id",
field=models.PositiveBigIntegerField(blank=True, null=True),
),
]
@@ -0,0 +1,62 @@
# Generated by Django 5.2.19 on 2026-11-23 21:20
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0064_customer_backup_exports"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="MailQueueOperation",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"requested_at",
models.DateTimeField(default=django.utils.timezone.now),
),
(
"last_dispatched_at",
models.DateTimeField(blank=True, null=True),
),
("started_at", models.DateTimeField(blank=True, null=True)),
("finished_at", models.DateTimeField(blank=True, null=True)),
("problem", models.TextField(blank=True)),
("queue_id", models.CharField(max_length=32)),
("arrival", models.PositiveBigIntegerField()),
("action", models.CharField(max_length=8)),
(
"actor",
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
to=settings.AUTH_USER_MODEL,
),
),
(
"domain",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="hosting.hostingmaildomain",
),
),
],
options={
"abstract": False,
},
),
]
@@ -0,0 +1,22 @@
# Generated by Django 5.2.19 on 2026-11-23 21:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0065_mail_queue_operations"),
]
operations = [
migrations.AddField(
model_name="componentrestorejob",
name="requested_customer_id",
field=models.PositiveBigIntegerField(blank=True, null=True),
),
migrations.AddField(
model_name="websiterestorejob",
name="requested_customer_id",
field=models.PositiveBigIntegerField(blank=True, null=True),
),
]
+76
View File
@@ -672,6 +672,21 @@ class HostingDnsZone(models.Model):
)
class DomainServicePolicy(models.Model):
account = models.ForeignKey(HostingAccount, on_delete=models.CASCADE)
domain = DomainNameField(max_length=253)
dns_managed = models.BooleanField(default=True)
mail_managed = models.BooleanField(default=True)
class Meta:
constraints = [
models.UniqueConstraint(
fields=("account", "domain"),
name="hosting_unique_domain_service_policy",
)
]
class WebsiteUsage(models.Model):
account = models.ForeignKey(
HostingAccount, on_delete=models.CASCADE, related_name="website_usage"
@@ -813,6 +828,29 @@ class ProvisioningJob(models.Model):
return "running" if self.started_at else "queued"
class OperatorOperation(ProvisioningJob):
actor = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True
)
action = models.CharField(max_length=24)
target = models.CharField(max_length=20, blank=True)
plan = models.CharField(max_length=64, blank=True)
source = models.OneToOneField(
"self", on_delete=models.SET_NULL, null=True, blank=True
)
result = models.JSONField(default=dict)
class MailQueueOperation(ProvisioningJob):
domain = models.ForeignKey(HostingMailDomain, on_delete=models.CASCADE)
actor = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True
)
queue_id = models.CharField(max_length=32)
arrival = models.PositiveBigIntegerField()
action = models.CharField(max_length=8)
class AccountRetirement(models.Model):
class Policy(models.TextChoices):
HOLD = "hold", "Keep names reserved"
@@ -1098,6 +1136,7 @@ class AccountBackupJob(ProvisioningJob):
)
manifest = models.JSONField()
remote_mail = models.BooleanField(default=False)
export_customer_id = models.PositiveBigIntegerField(null=True, blank=True)
scheduled_for = models.DateTimeField(null=True, blank=True)
archive_bytes = models.PositiveBigIntegerField(null=True, blank=True)
retention_protected = models.BooleanField(default=False)
@@ -1193,6 +1232,9 @@ class WebsiteRestoreJob(ProvisioningJob):
filename = models.CharField(max_length=MAX_RESTORE_PATH_BYTES, blank=True)
replace = models.BooleanField(default=False)
operator_username = models.CharField(max_length=150)
requested_customer_id = models.PositiveBigIntegerField(
null=True, blank=True
)
class Meta:
indexes = [models.Index(fields=("finished_at", "requested_at"))]
@@ -1213,6 +1255,9 @@ class ComponentRestoreJob(ProvisioningJob):
resource = models.CharField(max_length=254)
remote_mail = models.BooleanField(default=False)
operator_username = models.CharField(max_length=150)
requested_customer_id = models.PositiveBigIntegerField(
null=True, blank=True
)
class Meta:
indexes = [models.Index(fields=("finished_at", "requested_at"))]
@@ -1364,6 +1409,37 @@ class PanelRecoveryCode(models.Model):
]
class PanelTheme(models.Model):
name = models.CharField(max_length=80, unique=True)
colors = models.JSONField()
def __str__(self):
return self.name
class UserTheme(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE
)
theme = models.ForeignKey(
PanelTheme, on_delete=models.SET_NULL, null=True, blank=True
)
class PanelAnnouncement(models.Model):
class Audience(models.TextChoices):
ALL = "all", "All users"
MANAGERS = "managers", "Managers"
author = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True
)
audience = models.CharField(max_length=8, choices=Audience.choices)
subject = models.CharField(max_length=140)
body = models.TextField(max_length=4000)
published_at = models.DateTimeField(auto_now_add=True)
class PanelAccountSecurity(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE
+166
View File
@@ -0,0 +1,166 @@
from datetime import timedelta
from pathlib import Path
from django import forms
from django.contrib import messages
from django.db import transaction
from django.shortcuts import redirect
from django.utils import timezone
from django.views.generic import FormView, TemplateView
from coulobre.operator_node import SERVICES, SOCKET, OperatorRequest
from .account_administration import OperatorAuthorization
from .models import OperatorOperation
from .tasks import run_operator_operation
from .update_views import inspect_linked_nodes
TOOL_ACTIONS = {
"packages": (
"Server package updates",
("package-preview", "package-upgrade"),
),
"services": ("System services", ("reload", "restart")),
"database": ("Database monitor", ("database-report",)),
}
ACTION_LABELS = {
"package-preview": "Review available updates",
"package-upgrade": "Apply reviewed updates",
"reload": "Reload",
"restart": "Restart",
"database-report": "Collect MariaDB status",
}
class OperatorToolForm(forms.Form):
action = forms.ChoiceField()
preview_id = forms.IntegerField(required=False, widget=forms.HiddenInput)
target = forms.ChoiceField(
required=False,
choices=[
("", "Select a service"),
*[(key, label) for key, label in SERVICES.items()],
],
)
confirm = forms.BooleanField(
required=False, label="I reviewed the change and want to apply it"
)
def __init__(self, *args, actions, preview, **kwargs):
super().__init__(*args, **kwargs)
self.preview = preview
self.initial["preview_id"] = preview.pk if preview else None
self.fields["action"].choices = [
(action, ACTION_LABELS[action]) for action in actions
]
if "reload" not in actions:
self.fields.pop("target")
if actions == ("database-report",):
self.fields.pop("confirm")
def clean(self):
data = super().clean()
if self.errors:
return data
action = data["action"]
if action in {"reload", "restart", "package-upgrade"} and not data.get(
"confirm"
):
self.add_error(
"confirm", "Confirm this change before applying it."
)
plan = ""
if action == "package-upgrade":
if (
self.preview is None
or data.get("preview_id") != self.preview.pk
):
raise forms.ValidationError(
"Collect and review a current package update preview."
)
plan = self.preview.result.get("fingerprint", "")
try:
self.spec = OperatorRequest(action, data.get("target", ""), plan)
except ValueError as error:
raise forms.ValidationError(str(error)) from error
return data
class OperatorToolsView(OperatorAuthorization, FormView):
form_class = OperatorToolForm
template_name = "hosting/operator_tools.html"
page = "services"
def preview(self):
return (
OperatorOperation.objects.filter(
action="package-preview",
actor=self.request.user,
problem="",
finished_at__gte=timezone.now() - timedelta(minutes=15),
)
.order_by("-pk")
.first()
)
def get_form_kwargs(self):
return super().get_form_kwargs() | {
"actions": TOOL_ACTIONS[self.page][1],
"preview": self.preview() if self.page == "packages" else None,
}
def get_context_data(self, **kwargs):
title, actions = TOOL_ACTIONS[self.page]
return super().get_context_data(
title=title,
page=self.page,
available=Path(SOCKET).is_socket(),
jobs=OperatorOperation.objects.filter(action__in=actions).order_by(
"-pk"
)[:20],
**kwargs,
)
@transaction.atomic
def form_valid(self, form):
if not Path(SOCKET).is_socket():
form.add_error(
None,
"Enable the local operator service before requesting "
"an operation.",
)
return self.form_invalid(form)
spec = form.spec
if form.preview is not None and spec.action == "package-upgrade":
OperatorOperation.objects.select_for_update().get(
pk=form.preview.pk
)
recent = OperatorOperation.objects.filter(
source=form.preview
).exists()
if recent:
form.add_error(
None,
"Collect a new preview before starting another "
"package update.",
)
return self.form_invalid(form)
job = OperatorOperation.objects.create(
actor=self.request.user,
action=spec.action,
target=spec.target,
plan=spec.plan,
source=form.preview if spec.action == "package-upgrade" else None,
)
transaction.on_commit(lambda: run_operator_operation.delay(job.pk))
messages.success(self.request, "Host operation queued.")
return redirect(self.request.path)
class ConnectedNodesView(OperatorAuthorization, TemplateView):
template_name = "hosting/connected_nodes.html"
def get_context_data(self, **kwargs):
return super().get_context_data(
topology=inspect_linked_nodes(), **kwargs
)
+289
View File
@@ -0,0 +1,289 @@
import re
from django import forms
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import PermissionDenied, ValidationError
from django.http import HttpResponse
from django.shortcuts import redirect
from django.urls import reverse_lazy
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_safe
from django.views.generic import FormView, TemplateView
from .access import reseller_for_user
from .account_administration import OperatorAuthorization
from .models import PanelAnnouncement, PanelTheme, UserTheme
COLOR_TOKENS = frozenset(
[
"page",
"surface",
"ink",
"muted",
"line",
"sidebar",
"sidebar-text",
"accent",
"accent-hover",
"focus",
"sidebar-gradient",
"control-line",
"control-hover",
"table-heading",
"table-heading-text",
"notice-bg",
"notice-line",
"button-text",
"code-bg",
"code-text",
]
)
THEME_BLOCK = re.compile(
r'\s*(:root(?:\[data-appearance="dark"\])?)\s*\{([^{}]+)\}'
)
THEME_COLOR = re.compile(r"\s*--([a-z-]+)\s*:\s*(#[0-9a-fA-F]{3,8})\s*;\s*")
def color_tokens(source):
blocks = {}
offset = 0
while source[offset:].strip():
block = THEME_BLOCK.match(source, offset)
if block is None or block[1] in blocks:
raise ValidationError(
"Use one :root block and an optional dark :root block."
)
offset = block.end()
tokens = {}
values = block[2]
position = 0
while values[position:].strip():
color = THEME_COLOR.match(values, position)
if (
color is None
or color[1] not in COLOR_TOKENS
or len(color[2]) not in {4, 5, 7, 9}
or color[1] in tokens
):
raise ValidationError(
"Use supported color variables with hexadecimal values."
)
tokens[color[1]] = color[2]
position = color.end()
if not tokens:
raise ValidationError(
"Add at least one color variable to each block."
)
blocks[block[1]] = tokens
if ":root" not in blocks:
raise ValidationError("Provide a :root block for the default colors.")
return blocks
def render_colors(blocks):
return "\n".join(
f"{selector} {{ "
+ " ".join(f"--{name}: {value};" for name, value in tokens.items())
+ " }"
for selector, tokens in blocks.items()
)
class ThemeUploadForm(forms.ModelForm):
stylesheet = forms.FileField(
label="Theme stylesheet",
help_text="Upload a CSS file with Coulobre color variables.",
)
class Meta:
model = PanelTheme
fields = ["name", "stylesheet"]
def clean_stylesheet(self):
uploaded = self.cleaned_data["stylesheet"]
if uploaded.size > 32768:
raise ValidationError("Theme stylesheets can be at most 32 KiB.")
try:
return color_tokens(uploaded.read().decode("utf-8"))
except UnicodeError as error:
raise ValidationError("Use a UTF-8 stylesheet.") from error
THEME_PREVIEW = "coulobre_theme_preview"
class ThemeManagementView(OperatorAuthorization, FormView):
form_class = ThemeUploadForm
template_name = "hosting/panel_content.html"
extra_context = {
"title": "Themes",
"submit_label": "Preview theme",
"upload": True,
}
success_url = reverse_lazy("panel:theme_management")
def get_context_data(self, **kwargs):
return super().get_context_data(
themes=PanelTheme.objects.order_by("name"), **kwargs
)
def form_valid(self, form):
self.request.session[THEME_PREVIEW] = {
"name": form.cleaned_data["name"],
"colors": form.cleaned_data["stylesheet"],
}
return self.render_to_response(
self.get_context_data(
form=self.form_class(),
theme_preview=form.cleaned_data["name"],
)
)
def post(self, request, *args, **kwargs):
if request.POST.get("action") != "install":
return super().post(request, *args, **kwargs)
preview = request.session.pop(THEME_PREVIEW, None)
if preview is None:
messages.error(request, "Preview a theme before adding it.")
else:
_, created = PanelTheme.objects.get_or_create(
name=preview["name"], defaults={"colors": preview["colors"]}
)
if created:
messages.success(
request, "Theme added. Users can select it in My account."
)
else:
messages.error(
request, "A theme with this name already exists."
)
return redirect(self.success_url)
@require_safe
@never_cache
def preview_stylesheet(request):
if (
not request.user.is_superuser
or not request.user.is_verified()
or getattr(request, "impersonation", None)
):
raise PermissionDenied
preview = request.session.get(THEME_PREVIEW)
return HttpResponse(
render_colors(preview["colors"]) if preview else "",
content_type="text/css; charset=utf-8",
headers={"X-Content-Type-Options": "nosniff"},
)
class ThemeSelectionForm(forms.Form):
theme = forms.ModelChoiceField(
queryset=PanelTheme.objects.all(),
required=False,
empty_label="Installation default",
)
class ThemeSelectionView(LoginRequiredMixin, FormView):
form_class = ThemeSelectionForm
template_name = "hosting/panel_content.html"
extra_context = {"title": "Choose a theme", "submit_label": "Apply theme"}
success_url = reverse_lazy("panel:account_security")
def get_initial(self):
return {
"theme": UserTheme.objects.filter(user=self.request.user)
.values_list("theme_id", flat=True)
.first()
}
def form_valid(self, form):
UserTheme.objects.update_or_create(
user=self.request.user,
defaults={"theme": form.cleaned_data["theme"]},
)
return super().form_valid(form)
@require_safe
@never_cache
def user_stylesheet(request):
colors = None
if request.user.is_authenticated and not getattr(
request, "impersonation", None
):
colors = (
UserTheme.objects.filter(user=request.user)
.values_list("theme__colors", flat=True)
.first()
)
return HttpResponse(
render_colors(colors) if colors else "",
content_type="text/css; charset=utf-8",
headers={"X-Content-Type-Options": "nosniff"},
)
class AnnouncementForm(forms.ModelForm):
class Meta:
model = PanelAnnouncement
fields = ["audience", "subject", "body"]
widgets = {"body": forms.Textarea(attrs={"rows": 6})}
class AnnouncementView(OperatorAuthorization, FormView):
form_class = AnnouncementForm
template_name = "hosting/panel_content.html"
extra_context = {
"title": "Message users",
"submit_label": "Publish announcement",
"preview_required": True,
}
success_url = reverse_lazy("panel:announcements")
def form_valid(self, form):
if self.request.POST.get("action") != "publish":
return self.render_to_response(
self.get_context_data(form=form, preview=form.cleaned_data)
)
if (
self.request.session.pop("announcement_preview", None)
!= form.cleaned_data
):
form.add_error(None, "Review a preview of this message first.")
return self.form_invalid(form)
announcement = form.save(commit=False)
announcement.author = self.request.user
announcement.save()
messages.success(self.request, "Announcement published.")
return super().form_valid(form)
def get_context_data(self, **kwargs):
if kwargs.get("preview"):
self.request.session["announcement_preview"] = kwargs["preview"]
return super().get_context_data(**kwargs)
def panel_announcements(request):
if not request.user.is_authenticated or getattr(
request, "impersonation", None
):
return {}
audience = [PanelAnnouncement.Audience.ALL]
if reseller_for_user(request.user) is not None:
audience.append(PanelAnnouncement.Audience.MANAGERS)
announcements = PanelAnnouncement.objects.filter(
audience__in=audience
).order_by("-published_at")[:3]
return {
"panel_announcements": announcements,
"has_user_theme": UserTheme.objects.filter(
user=request.user, theme__isnull=False
).exists(),
}
class DirectAdminGuideView(OperatorAuthorization, TemplateView):
template_name = "hosting/directadmin_guide.html"
+20 -2
View File
@@ -110,8 +110,10 @@ def plan_php_versions(account):
@transaction.atomic
def queue_site_php_settings(account_id, php_settings, *, use_plan=False):
account = lock_hosting_account(account_id, customer_id=None)
def queue_site_php_settings(
account_id, php_settings, *, use_plan=False, customer_id=None
):
account = lock_hosting_account(account_id, customer_id=customer_id)
require_open_account(account)
if not site_is_active(account):
raise ValidationError(
@@ -119,6 +121,22 @@ def queue_site_php_settings(account_id, php_settings, *, use_plan=False):
)
if use_plan:
php_settings = plan_php_settings(account)
elif customer_id is not None:
require_active_services(account)
limits = plan_php_settings(account).manifest()
values = php_settings.manifest()
for key, limit in limits.items():
value = values[key]
if value is not None and (limit is None or value > limit):
raise ValidationError(
"Keep PHP limits within the account's hosting plan."
)
if value is None:
values[key] = limit
try:
php_settings = PhpPoolSettings.from_manifest(values)
except PhpPoolSettingsError as error:
raise ValidationError(str(error)) from error
changes = {
"domain": account.primary_domain,
+1 -1
View File
@@ -45,7 +45,7 @@ class ResellerPolicyForm(forms.ModelForm):
help_texts = {
"account_limit": "Enter 0 to manage existing accounts only.",
"hosting_plans": (
"Plans available when a reseller creates an account."
"Plans available when a manager creates an account."
),
}
@@ -4,6 +4,7 @@ from django.db.models import F
from coulobre.mail_node import MailboxSpec
from .domain_policies import require_managed
from .models import (
DatabaseProvisioning,
HostingAccount,
@@ -60,6 +61,7 @@ def create_mailbox_request(
):
account = lock_hosting_account(account_id, customer_id)
require_open_account(account)
require_managed(account, account.primary_domain, "mail_managed")
try:
spec = MailboxSpec(account.primary_domain, local_part)
except ValueError as error:
@@ -106,6 +108,7 @@ def queue_mailbox_provisioning(mailbox):
account = lock_hosting_account(
mailbox.mail_domain.account_id, customer_id=None
)
require_managed(account, mailbox.mail_domain.domain, "mail_managed")
require_active_services(account)
return MailboxProvisioning.objects.queue(mailbox=mailbox)
+101 -3
View File
@@ -46,6 +46,7 @@ from .models import (
ComponentRestoreJob,
DatabaseProvisioning,
DnsPublication,
HostingAccount,
HostingMailDomain,
IndependentWebsite,
MailboxProvisioning,
@@ -97,6 +98,7 @@ from .offsite_backups import (
)
from .password_reset import send_customer_reset_email
from .php_settings import plan_php_versions
from .resource_requests import lock_hosting_account
from .service_changes import apply_service_change
from .sftp import site_is_active
from .sign_in_limits import current_window
@@ -836,9 +838,17 @@ def apply_account_backup(job):
raise ValueError(
"Enable local mailbox backups before trying again."
)
if (
job.export_customer_id is not None
and job.export_customer_id != job.account.customer_id
):
raise ValueError("The hosting account's customer assignment changed.")
size = create_local_account_backup(
AccountBackupRequest(
job.backup_id, backup, remote_mail=job.remote_mail
job.backup_id,
backup,
remote_mail=job.remote_mail,
publish_to_customer=job.export_customer_id is not None,
)
)
return {"archive_bytes": size}
@@ -899,7 +909,28 @@ def restore_website(job_id):
)
def with_customer_restore_scope(job, apply):
customer_id = job.requested_customer_id
if customer_id is None:
return apply(job)
with transaction.atomic():
try:
account = lock_hosting_account(job.backup.account_id, customer_id)
except HostingAccount.DoesNotExist:
raise ValueError(
"The hosting account assignment changed."
) from None
if account.retired_at is not None:
raise ValueError("The hosting account is retired.")
job.backup.account = account
return apply(job)
def apply_website_restore(job):
return with_customer_restore_scope(job, restore_website_target)
def restore_website_target(job):
account = job.backup.account
site = (
WebSite.from_manifest(job.site_manifest)
@@ -938,6 +969,10 @@ def restore_backup_component(job_id):
def apply_component_restore(job):
return with_customer_restore_scope(job, restore_component_target)
def restore_component_target(job):
backup = job.backup
resources = available_restore_resources(
backup, job.kind, current_restore_resources(backup.account, job.kind)
@@ -1081,7 +1116,7 @@ def refresh_mail_queue(domain_id, requested_at):
return
try:
report = apply_on_local_node(
MailQueueRequest(domain.domain),
MailQueueRequest(domain.domain, detailed=True),
"/run/coulobre-mail-apply.sock",
"mail node",
"queue summary",
@@ -1097,7 +1132,11 @@ def refresh_mail_queue(domain_id, requested_at):
or type(report["partial"]) is not bool
):
raise ValueError
snapshot = {"counts": counts, "partial": report["partial"]}
snapshot = {
"counts": counts,
"partial": report["partial"],
"entries": report.get("entries", []),
}
except (KeyError, TypeError, ValueError, OSError):
snapshot = {"error": "Could not read the queue from the mail node."}
HostingMailDomain.objects.filter(
@@ -1222,3 +1261,62 @@ def collect_mailbox_usage(mailbox_id, requested_at):
except (KeyError, OSError, ValueError):
used = None
mailboxes.update(usage_bytes=used, usage_observed_at=timezone.now())
@shared_task(queue="coulobre-operator-actions")
def run_operator_operation(job_id):
from coulobre.operator_node import SOCKET, OperatorRequest
from .models import OperatorOperation
from .node_client import apply_on_local_node
def apply(job):
spec = OperatorRequest(job.action, job.target, job.plan)
result = apply_on_local_node(
spec, SOCKET, "operator service", "host operation", timeout=32 * 60
)
for key in (*spec.manifest(), "state", "problem"):
result.pop(key, None)
return {"result": result}
run_provisioning_job(
OperatorOperation.objects.all(),
job_id,
apply,
"The operator service did not report a result. "
"Check the service journal.",
lease=timedelta(minutes=35),
)
@shared_task(queue="coulobre-mailbox-provisioning")
def run_mail_queue_operation(job_id):
from coulobre.mail_queue import MailQueueAction
from .models import MailQueueOperation
from .node_client import apply_on_local_node
def apply(job):
if (
not settings.LOCAL_MAILBOX_PROVISIONING
or job.domain.account.retired_at is not None
):
raise ValueError("The mail domain is no longer available.")
request = MailQueueAction(
job.domain.domain, job.queue_id, job.arrival, job.action
)
apply_on_local_node(
request,
"/run/coulobre-mail-apply.sock",
"mail node",
"queue action",
timeout=60,
)
run_provisioning_job(
MailQueueOperation.objects.select_related("domain__account"),
job_id,
apply,
"The mail node did not confirm the queue action.",
lease=timedelta(minutes=3),
)
@@ -66,7 +66,7 @@
<section class="surface editor-surface" aria-labelledby="retirement-policy-heading">
<header class="section-heading"><h2 id="retirement-policy-heading">Retention and name release</h2></header>
<form class="editor" method="post">
<p>Suspend managed services before retirement. Retirement removes customer and reseller access to this account and stops its backup schedule.</p>
<p>Suspend managed services before retirement. Retirement removes customer and manager access to this account and stops its backup schedule.</p>
<p><strong>Keep names reserved</strong> preserves the suspended resources, DNS, and incoming mail.</p>
<p><strong>Release names and retain data</strong> removes hosting configuration, certificates, keys, delivery, and DNS. Website files and mail are moved to node archives. Databases stay locked under their original identifiers.</p>
<p>Type the primary domain to confirm this preview.</p>
@@ -13,6 +13,7 @@
{% if not email_available %}<p class="section-text muted">Email changes require configured panel email delivery.</p>{% endif %}
<div class="section-text form-actions">
<a class="button secondary" href="{% url 'panel:account_password' %}">Change password</a>
<a class="button secondary" href="{% url 'panel:theme_selection' %}">Choose theme</a>
{% if email_available %}<a class="button secondary" href="{% url 'panel:account_email' %}">Change email address</a>{% endif %}
<a class="button secondary" href="{% url 'panel:account_authenticator' %}">{% if factor_enabled %}Change{% else %}Set up{% endif %} authenticator app</a>
{% if factor_enabled %}<a class="button secondary" href="{% url 'panel:account_recovery_codes' %}">Generate recovery codes</a>{% endif %}
@@ -7,6 +7,8 @@
<link rel="icon" type="image/svg+xml" href="{% static 'hosting/coulobre-mark.svg' %}">
<link rel="stylesheet" href="{% static 'hosting/panel.css' %}">
{% if custom_panel_theme %}<link rel="stylesheet" href="{% url 'panel:theme_stylesheet' %}">{% endif %}
{% if has_user_theme %}<link rel="stylesheet" href="{% url 'panel:user_stylesheet' %}">{% endif %}
{% block extra_styles %}{% endblock %}
<script src="{% static 'hosting/panel-appearance.js' %}"></script>
</head>
<body>
@@ -79,6 +81,7 @@
</form>
</section>
{% endif %}
{% for announcement in panel_announcements %}<section class="notice"><strong>{{ announcement.subject }}</strong>{{ announcement.body|linebreaks }}</section>{% endfor %}
{% block content %}{% endblock %}
</main>
</div>
@@ -0,0 +1,13 @@
{% extends "hosting/base.html" %}
{% block title %}Connected nodes · Coulobre Panel{% endblock %}
{% block content %}
<header class="page-heading"><h1>Connected nodes</h1><a class="button secondary" href="{% url 'panel:service_health' %}">Service health</a></header>
{% if topology.problem %}<p class="notice">{{ topology.problem }}</p>{% endif %}
<section class="surface" aria-label="Mail and DNS receivers">
<div class="table-scroll"><table>
<thead><tr><th scope="col">Role</th><th scope="col">Host</th><th scope="col">Release</th><th scope="col">State</th></tr></thead>
<tbody>{% for node in topology.nodes %}<tr><th scope="row">{{ node.role|upper }}</th><td>{{ node.host }}</td><td>{{ node.release|default:"Unknown" }}</td><td>{{ node.state|capfirst }}</td></tr>
{% empty %}<tr><td colspan="4">No linked mail or DNS receivers reported.</td></tr>{% endfor %}</tbody>
</table></div>
</section>
{% endblock %}
@@ -1,19 +1,35 @@
{% extends "hosting/base.html" %}
{% block title %}Backup &amp; Restore · Coulobre Panel{% endblock %}
{% block title %}Backup &amp; Restore · Coulobre Panel <section class="surface" aria-labelledby="restore-history">
<header class="section-heading"><h2 id="restore-history">Recent restores</h2></header>
<ul class="workspace-list">
{% for restore in restores %}<li>{{ restore.requested_at|date:"j M Y H:i" }} · {{ restore.kind|default:"Website"|capfirst }} · {{ restore.state|capfirst }}</li>
{% empty %}<li>No restores yet.</li>{% endfor %}
</ul>
</section>
{% endblock %}
{% block content %}
<header class="page-heading"><div><h1>Backup &amp; Restore</h1><p>{{ account.primary_domain }}</p></div></header>
{% for message in messages %}<p class="notice" role="status">{{ message }}</p>{% endfor %}
{% if may_create %}
<section class="surface editor-surface" aria-labelledby="backup-create">
<h2 id="backup-create">Create a backup</h2>
<h2 id="backup-create">Create a backup</h2><p>Download the latest completed customer backup over SFTP at <code>/backups/latest.zip</code>.</p>
<form class="editor" method="post">{% csrf_token %}{{ form.as_div }}<button class="button primary" type="submit">Create backup</button></form>
</section>
{% endif %}
{% else %}<p class="notice">Customer backups require an active website, SFTP and the local backup service.</p>{% endif %}
<section class="surface" aria-labelledby="backup-history">
<header class="section-heading"><h2 id="backup-history">Recent backups</h2></header>
<ul class="workspace-list">
{% for backup in backups %}<li>{{ backup.requested_at|date:"j M Y H:i" }} · {% if not backup.finished_at %}Queued{% elif backup.problem %}Failed{% else %}Ready{% endif %}</li>
{% for backup, kinds in backups %}<li>{{ backup.requested_at|date:"j M Y H:i" }} · {{ backup.state|capfirst }}
{% for kind in kinds %}<a class="button secondary" href="{% url 'panel:customer_restore' account.pk backup.pk kind %}">Restore {{ kind }}</a>{% endfor %}
</li>
{% empty %}<li>No backups yet.</li>{% endfor %}
</ul>
</section>
<section class="surface" aria-labelledby="restore-history">
<header class="section-heading"><h2 id="restore-history">Recent restores</h2></header>
<ul class="workspace-list">
{% for restore in restores %}<li>{{ restore.requested_at|date:"j M Y H:i" }} · {{ restore.kind|default:"Website"|capfirst }} · {{ restore.state|capfirst }}</li>
{% empty %}<li>No restores yet.</li>{% endfor %}
</ul>
</section>
{% endblock %}
@@ -0,0 +1,25 @@
{% extends "hosting/base.html" %}
{% block title %}Restore {{ kind }} · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{% url 'panel:customer_backups' account.pk %}">← Backup &amp; Restore</a>
<header class="page-heading"><div><h1>Restore {{ kind }}</h1><p>{{ account.primary_domain }} · Backup from {{ backup.requested_at|date:"j M Y H:i" }} UTC</p></div></header>
<section class="surface editor-surface">
{% if kind == 'website' %}<p>An entire website needs an empty document root. A single file needs an existing parent directory.</p>
{% elif kind == 'database' %}<p>Choose an empty database and keep its applications disconnected during the restore.</p>
{% else %}<p>Choose an unused mailbox and pause delivery and client access during the restore.</p>{% endif %}
<form method="post" class="editor">
{% csrf_token %}{{ form.as_div }}
{% if preview %}
<section aria-label="Restore preview">
<h2>Review destination</h2>
<p>{% if kind == "website" %}{{ target.domain }}{% elif kind == "database" %}{{ target.name }}{% else %}{{ target.address }}{% endif %}</p>
{% if preview.filename %}<p><code>{{ preview.filename }}</code>{% if preview.replace %} · Replace the current file{% endif %}</p>{% endif %}
</section>
{% endif %}
<div class="form-actions">
<button class="button secondary" name="action" value="preview" type="submit">Preview restore</button>
{% if preview %}<button class="button primary" name="action" value="restore" type="submit">Queue restore</button>{% endif %}
</div>
</form>
</section>
{% endblock %}
@@ -0,0 +1,9 @@
{% extends "hosting/base.html" %}
{% block title %}DirectAdmin import · Coulobre Panel{% endblock %}
{% block content %}
<header class="page-heading"><h1>DirectAdmin import</h1></header>
<section class="surface editor-surface">
<p>Use a DirectAdmin account archive. Inspect it and review the planned account, website, database, mail and DNS changes before importing.</p>
<a class="button secondary" href="https://code.hosting.hippogrief.nl/hippogrief/coulobre/src/branch/main/docs/development.md#inspect-a-directadmin-backup">Open the import guide</a>
</section>
{% endblock %}
@@ -0,0 +1,55 @@
{% extends "hosting/base.html" %}
{% block title %}{{ title }} · Coulobre Panel{% endblock %}
{% block content %}
<header class="page-heading">
<div><h1>{{ title }}</h1><p class="heading-meta">{{ account.primary_domain }}</p></div>
{% if page == 'domains' and can_add_site %}<a class="button primary" href="{% url 'panel:independent_website_create' account.pk %}">Add domain</a>{% endif %}
</header>
{% for message in messages %}<p class="notice" role="status">{{ message }}</p>{% endfor %}
<section class="surface">
<form method="get" class="toolbar form-actions">
<label for="domain">Domain</label>
<select id="domain" name="domain">
{% for choice in domains %}<option value="{{ choice }}"{% if choice == domain %} selected{% endif %}>{{ choice }}</option>{% endfor %}
</select>
<button class="button secondary" type="submit">Select domain</button>
</form>
</section>
{% if page == 'domains' %}
<section class="surface editor-surface" aria-label="Domain services">
<form method="post" class="editor">{% csrf_token %}{{ form.as_div }}<button class="button primary" type="submit">Save service preferences</button></form>
</section>
{% elif page == 'dns' %}
{% if zone %}
<section class="surface" aria-label="DNS records">
<header class="section-heading"><h2>DNS records</h2>{% if may_edit_dns %}<a class="button primary" href="{% url 'panel:dns_zone_edit' zone.pk %}">Edit zone</a>{% endif %}</header>
<div class="table-scroll"><table><thead><tr><th scope="col">Name</th><th scope="col">Type</th><th scope="col">Value</th></tr></thead><tbody>
{% for record in records %}<tr><td>{{ record.name }}</td><td>{{ record.type }}</td><td><code>{{ record.value }}</code></td></tr>{% endfor %}
</tbody></table></div>
</section>
{% else %}<p class="empty">This domain has no saved Coulobre DNS zone.</p>{% endif %}
{% if not policy.dns_managed %}<p class="notice">Make DNS changes at the domain's authoritative DNS provider.</p>{% endif %}
{% elif page == 'php' or page == 'files' %}
<section class="surface section-heading" aria-label="{{ title }}">
{% if primary %}
{% if page == 'php' %}<a class="button secondary" href="{% url 'panel:site_php_version' account.pk %}">Select PHP version</a>
<a class="button secondary" href="{% url 'panel:site_php_settings' account.pk %}">Edit PHP limits</a>
{% else %}<a class="button primary" href="{% url 'panel:website_files' account.pk %}">Browse files</a>{% endif %}
{% elif website %}
{% if page == 'php' %}<a class="button secondary" href="{% url 'panel:independent_website_operation' account.pk website.pk 'php' %}">Select PHP version</a>
{% else %}<a class="button primary" href="{% url 'panel:independent_website_files' account.pk website.pk %}">Browse files</a>{% endif %}
{% else %}<p class="empty">Select an active website for this action.</p>{% endif %}
</section>
{% elif mail_domain and policy.mail_managed %}
<section class="surface" aria-label="{{ title }}">
{% if page == 'forwarders' %}
<header class="section-heading"><h2>Forwarders and catch-all</h2><a class="button primary" href="{% url 'panel:mail_routing' mail_domain.pk %}">Manage forwarders</a></header>
{% else %}
<ul class="workspace-list">
{% for mailbox in mail_domain.mailboxes.all %}<li><a href="{% url 'panel:mail_vacation' mailbox.pk %}">{{ mailbox.spec.address }}</a></li>
{% empty %}<li>No mailboxes for this domain.</li>{% endfor %}
</ul>
{% endif %}
</section>
{% else %}<p class="empty">This domain has no managed email accounts.</p>{% endif %}
{% endblock %}
@@ -2,7 +2,19 @@
{% block title %}Configure features · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{% url 'panel:installation' %}">← About Coulobre</a>
<header class="page-heading"><h1>Configure features</h1></header>
<header class="page-heading"><h1>{% if settings_tabs %}Operator Settings{% else %}Configure features{% endif %}</h1></header>
{% if settings_tabs %}
<nav class="account-navigation" aria-label="Operator settings">
{% for key, label in settings_tabs %}<a href="{% url 'panel:operator_settings' key %}"{% if selected_section == key %} aria-current="page"{% endif %}>{{ label }}</a>{% endfor %}
</nav>
{% endif %}
{% for message in messages %}<p class="notice" role="status">{{ message }}</p>{% endfor %}
{% if selected_section == 'general' %}
<section class="surface section-heading">
<h2>Installation</h2>
<a class="button secondary" href="{% url 'panel:installation' %}">About Coulobre</a>
</section>
{% else %}
<div class="surface editor-surface">
<p>Choose which configured features the panel can use for new requests. Existing sites, mailboxes, scheduled tasks and backups keep running.</p>
<form class="editor" method="post">
@@ -24,4 +36,5 @@
</div>
</form>
</div>
{% endif %}
{% endblock %}
@@ -22,4 +22,20 @@
</dl>
{% endif %}
</section>
{% if mail_domain.queue_report.entries and request.user.is_superuser and request.user.is_verified %}
<section class="surface" aria-label="Queue entries"><ul class="workspace-list">
{% for entry in mail_domain.queue_report.entries %}<li>
<form method="post" class="form-actions" action="{% url 'panel:mail_queue_action' mail_domain.pk %}">{% csrf_token %}
<code>{{ entry.queue_id }}</code> {{ entry.queue|capfirst }}
<input type="hidden" name="queue_id" value="{{ entry.queue_id }}"><input type="hidden" name="arrival" value="{{ entry.arrival }}">
{% if entry.queue == 'deferred' %}<button class="button secondary" name="action" value="flush">Flush</button>{% endif %}
{% if entry.queue == 'hold' %}<button class="button secondary" name="action" value="release">Release</button>
{% elif entry.queue == 'active' or entry.queue == 'deferred' %}<button class="button secondary" name="action" value="hold">Hold</button>{% endif %}
</form>
</li>{% endfor %}
</ul></section>
{% endif %}
{% if operations %}<section class="surface" aria-label="Queue actions"><ul class="workspace-list">
{% for job in operations %}<li>{{ job.action|capfirst }} {{ job.queue_id }} · {{ job.state|capfirst }}{% if job.problem %} · {{ job.problem }}{% endif %}</li>{% endfor %}
</ul></section>{% endif %}
{% endblock %}
@@ -0,0 +1,8 @@
{% extends "hosting/base.html" %}
{% block content %}
<header class="page-heading"><h1>Mail Queue</h1></header>
<section class="surface"><ul class="workspace-list">
{% for domain in domains %}<li><a href="{% url 'panel:mail_queue' domain.pk %}">{{ domain }}</a></li>
{% empty %}<li>No managed email domains.</li>{% endfor %}
</ul>{% include "hosting/pagination.html" %}</section>
{% endblock %}
@@ -0,0 +1,29 @@
{% extends "hosting/base.html" %}
{% block title %}{{ title }} · Coulobre Panel{% endblock %}
{% block content %}
<header class="page-heading"><h1>{{ title }}</h1></header>
<div class="form-actions">
{% if page == 'packages' %}<a href="{% url 'panel:updates' %}">Coulobre updates</a>
{% elif page == 'services' %}<a href="{% url 'panel:service_health' %}">Service health</a>{% endif %}
</div>
{% for message in messages %}<p class="notice" role="status">{{ message }}</p>{% endfor %}
<section class="surface editor-surface">
{% if available %}<form method="post" class="editor">{% csrf_token %}{{ form.as_div }}<button class="button primary" type="submit">Queue operation</button></form>
{% else %}<p>Enable the operator service on the host to run these operations.</p>{% endif %}
</section>
<section class="surface" aria-label="Operation history">
<header class="section-heading"><h2>Operation history</h2></header>
{% for job in jobs %}
<details class="section-text"><summary>{{ job.requested_at|date:"j M Y H:i" }} · {{ job.action }}{% if job.target %} · {{ job.target }}{% endif %} · {{ job.state|capfirst }}</summary>
{% if job.problem %}<p>{{ job.problem }}</p>{% endif %}
{% if job.action == 'package-preview' and job.result.fingerprint %}
<p>{{ job.result.count }} package{{ job.result.count|pluralize }} ready to update.</p>
<ul>{% for package in job.result.packages %}<li><code>{{ package }}</code></li>{% endfor %}</ul>
{% elif job.action == 'database-report' and job.result.version %}
<p>MariaDB {{ job.result.version }} · Slow query logging {{ job.result.slow_logging|yesno:"enabled,disabled" }}</p>
<dl>{% for key, value in job.result.counters.items %}<dt>{{ key }}</dt><dd>{{ value }}</dd>{% endfor %}</dl>
{% endif %}
</details>
{% empty %}<p class="empty">No operations yet.</p>{% endfor %}
</section>
{% endblock %}
@@ -0,0 +1,31 @@
{% extends "hosting/base.html" %}
{% block title %}{{ title }} · Coulobre Panel{% endblock %}
{% block extra_styles %}{% if theme_preview %}<link rel="stylesheet" href="{% url 'panel:preview_stylesheet' %}">{% endif %}{% endblock %}
{% block content %}
<header class="page-heading"><h1>{{ title }}</h1></header>
{% for message in messages %}<p class="notice" role="status">{{ message }}</p>{% endfor %}
{% if theme_preview %}
<section class="surface editor-surface">
<h2>Previewing {{ theme_preview }}</h2>
<form method="post" class="form-actions">
{% csrf_token %}<button class="button primary" type="submit" name="action" value="install">Add theme</button>
<a class="button secondary" href="{% url 'panel:theme_management' %}">Close preview</a>
</form>
</section>
{% endif %}
{% if preview %}<section class="surface editor-surface" aria-label="Announcement preview"><h2>{{ preview.subject }}</h2>{{ preview.body|linebreaks }}</section>{% endif %}
<section class="surface editor-surface">
<form method="post" class="editor"{% if upload %} enctype="multipart/form-data"{% endif %}>
{% csrf_token %}{{ form.as_div }}
<div class="form-actions">
{% if preview_required %}<button class="button secondary" name="action" value="preview" type="submit">Preview</button>{% endif %}
{% if not preview_required or preview %}<button class="button primary" name="action" value="publish" type="submit">{{ submit_label }}</button>{% endif %}
</div>
</form>
</section>
{% if themes %}
<section class="surface" aria-label="Installed themes">
<ul class="workspace-list">{% for theme in themes %}<li>{{ theme.name }}</li>{% endfor %}</ul>
</section>
{% endif %}
{% endblock %}
@@ -1,16 +1,29 @@
{% extends "hosting/base.html" %}
{% block title %}{{ title }} · Coulobre Panel{% endblock %}
{% block content %}
<header class="page-heading"><h1>{{ title }}</h1></header>
<header class="page-heading"><div><h1>{{ title }}</h1>{% if section == 'statistics' %}<p class="heading-meta">Traffic for {{ month }}. Usage is based on available measurements.</p>{% endif %}</div></header>
<section class="surface" aria-label="Hosting accounts">
<ul class="workspace-list">
{% for account in accounts %}
<li>
{% if target %}<a href="{% url target account.pk %}">{{ account.primary_domain }}</a>
{% else %}{{ account.primary_domain }}{% endif %}
</li>
{% empty %}<li>No hosting accounts are available.</li>{% endfor %}
</ul>
{% if not target %}<p class="section-text muted">This service needs setup.</p>{% endif %}
{% if section == 'statistics' %}
<div class="table-scroll"><table>
<thead><tr><th scope="col">Hosting account</th><th scope="col">Disk use</th><th scope="col">Traffic</th><th scope="col">Domains</th><th scope="col">Databases</th><th scope="col">Mailboxes</th></tr></thead>
<tbody>{% for account, storage, traffic in rows %}
<tr><th scope="row"><a href="{{ account.get_absolute_url }}">{{ account.primary_domain }}</a></th><td>{% if storage is not None %}{{ storage|filesizeformat }}{% else %}Unavailable{% endif %}</td><td>{% if traffic is not None %}{{ traffic|filesizeformat }}{% else %}Unavailable{% endif %}</td><td>{{ account.domain_count|default:"1" }}</td><td>{{ account.database_count }}</td><td>{{ account.mailbox_count }}</td></tr>
{% empty %}<tr><td colspan="6">No hosting accounts are available.</td></tr>{% endfor %}</tbody>
</table></div>
{% elif section == 'tasks' %}
<div class="table-scroll"><table>
<thead><tr><th scope="col">Domain</th><th scope="col">Task</th><th scope="col">Status</th><th scope="col">Next run (UTC)</th></tr></thead>
<tbody>{% for job in tasks %}
<tr><td>{{ job.domain }}</td><th scope="row">{% if target %}<a href="{% url target job.account_id %}">{{ job.name }}</a>{% else %}{{ job.name }}{% endif %}</th><td>{{ job.enabled|yesno:"Enabled,Paused" }}</td><td>{{ job.next_run_at|date:"j M Y H:i"|default:"—" }}</td></tr>
{% empty %}<tr><td colspan="4">No scheduled tasks for these accounts.</td></tr>{% endfor %}</tbody>
</table></div>
{% else %}
<ul class="workspace-list">
{% for account, storage, traffic in rows %}<li>{% if target %}<a href="{% url target account.pk %}">{{ account.primary_domain }}</a>{% else %}{{ account.primary_domain }}{% endif %}</li>
{% empty %}<li>No hosting accounts are available.</li>{% endfor %}
</ul>
{% if not target %}<p class="section-text muted">Website logs need a configured collector.</p>{% endif %}
{% endif %}
{% include "hosting/pagination.html" %}
</section>
{% endblock %}
@@ -4,7 +4,7 @@
{% block content %}
<header class="page-heading">
<div><h1>Updates</h1><p class="heading-meta">Installed version {{ installed_version|default:"unknown" }}</p></div>
<a class="button secondary" href="{% url 'panel:updates' %}?refresh=1">Refresh status</a>
<div class="form-actions"><a class="button secondary" href="{% url 'panel:server_updates' %}">Server packages</a><a class="button secondary" href="{% url 'panel:updates' %}?refresh=1">Refresh status</a></div>
</header>
{% for message in messages %}<p class="notice" role="status">{{ message }}</p>{% endfor %}
{% if form.errors %}<div class="notice">{{ form.errors }}</div>{% endif %}
@@ -6,14 +6,21 @@
<form method="post" class="editor">
{% csrf_token %}
{{ form.as_div }}
{% if invitation_preview %}
<details>
{% if welcome_preview %}
<details open>
<summary>Welcome email preview</summary>
<p>The message includes an invitation link for choosing a password and setup details for the new hosting account. Your welcome text appears before the setup details.</p>
<pre>{{ welcome_preview }}</pre>
</details>
{% endif %}
{% if moving %}
<section aria-label="Transfer preview">
<h2>Move to {{ destination }}</h2>
<ul>{% for item in moving %}<li>{{ item.primary_domain }} · {{ item.hosting_plan }} · from {{ item.reseller|default:"Unassigned" }}</li>{% endfor %}</ul>
</section>
{% endif %}
<div class="form-actions">
<button class="button primary" type="submit">{{ submit_label }}</button>
{% if invitation_preview or move_preview_enabled %}<button class="button secondary" type="submit" name="action" value="preview">Preview</button>{% endif %}
{% if not move_preview_enabled or moving %}<button class="button primary" type="submit" name="action" value="move">{{ submit_label }}</button>{% endif %}
<a class="button secondary" href="{% url 'panel:accounts' %}">Cancel</a>
</div>
</form>
@@ -0,0 +1,73 @@
from unittest.mock import patch
from uuid import uuid4
from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from coulobre.account_backup import AccountBackup
from coulobre.web_node import WebSite
from .models import (
AccountBackupJob,
ComponentRestoreJob,
Customer,
HostingAccount,
HostingDatabase,
)
from .tasks import restore_backup_component
@override_settings(LOCAL_ACCOUNT_BACKUPS=True, LOCAL_DATABASE_RESTORE=True)
class CustomerRestoreTests(TestCase):
def test_restore_requires_its_customers_backup_and_current_assignment(
self,
):
users = get_user_model().objects
customer = Customer.objects.create(user=users.create_user("customer"))
other = Customer.objects.create(user=users.create_user("other"))
account = HostingAccount.objects.create(
name="Shop", primary_domain="shop.example.test", customer=customer
)
database = HostingDatabase.objects.create(
account=account, suffix="cms"
)
archive = AccountBackup(
WebSite(account.pk, account.primary_domain), (database.spec,)
)
backup = AccountBackupJob.objects.create(
account=account,
manifest=archive.manifest(),
finished_at=timezone.now(),
export_customer_id=customer.pk,
)
url = reverse(
"panel:customer_restore", args=[account.pk, backup.pk, "database"]
)
self.client.force_login(other.user)
self.assertEqual(self.client.get(url).status_code, 404)
self.client.force_login(customer.user)
data = {"restore_id": str(uuid4()), "resource": database.suffix}
self.assertContains(
self.client.post(url, data | {"action": "restore"}),
"Review the destination before restoring.",
)
self.assertContains(
self.client.post(url, data | {"action": "preview"}),
database.spec.name,
)
self.assertFalse(ComponentRestoreJob.objects.exists())
self.assertRedirects(
self.client.post(url, data | {"action": "restore"}),
reverse("panel:customer_backups", args=[account.pk]),
)
job = ComponentRestoreJob.objects.get()
HostingAccount.objects.filter(pk=account.pk).update(customer=other)
with patch(
"coulobre.hosting.tasks.restore_local_component"
) as restore:
restore_backup_component(job.pk)
restore.assert_not_called()
job.refresh_from_db()
self.assertEqual(job.state, "failed")
@@ -0,0 +1,91 @@
import json
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import SimpleTestCase, TestCase
from django.urls import reverse
from django_otp.plugins.otp_totp.models import TOTPDevice
from coulobre.mail_queue import MailQueueAction, change_queue_entry
from coulobre.operator_node import OperatorRequest, packages
from .models import PanelTheme
class OperatorRequestTests(SimpleTestCase):
def test_unknown_services_and_changed_package_plans_are_rejected(self):
with self.assertRaises(ValueError):
OperatorRequest("restart", "ssh.service")
with (
patch("coulobre.operator_node.locked_root_directory"),
patch(
"coulobre.operator_node.apt_plan",
return_value={"fingerprint": "0" * 64},
),
patch("coulobre.operator_node.command") as command,
self.assertRaisesMessage(ValueError, "The package plan changed"),
):
packages(OperatorRequest("package-upgrade", plan="f" * 64))
command.assert_not_called()
def test_mail_action_requires_entire_recipient_scope_and_fresh_arrival(
self,
):
message = {
"queue_id": "Ab12345",
"queue_name": "deferred",
"arrival_time": 1710000000,
"recipients": [
{"address": "alice@example.test"},
{"address": "bob@different.test"},
],
}
request = MailQueueAction(
"example.test", message["queue_id"], 1710000000, "flush"
)
with (
patch(
"coulobre.mail_queue.read_queue",
side_effect=lambda consume: consume([json.dumps(message)]),
),
patch("coulobre.mail_queue.subprocess.run") as command,
):
with self.assertRaises(ValueError):
change_queue_entry(request)
message["recipients"].pop()
message["arrival_time"] += 1
with self.assertRaises(ValueError):
change_queue_entry(request)
command.assert_not_called()
class ThemePreviewTests(TestCase):
def test_theme_preview_uses_validated_css_and_requires_confirmation(self):
operator = get_user_model().objects.create_superuser("operator")
self.client.force_login(operator)
session = self.client.session
device = TOTPDevice.objects.create(user=operator, name="test")
session["otp_device_id"] = device.persistent_id
session.save()
url = reverse("panel:theme_management")
hostile = SimpleUploadedFile(
"custom.css", b":root { --accent: url(https://example.test); }"
)
response = self.client.post(
url, {"name": "Test theme", "stylesheet": hostile}
)
self.assertContains(response, "hexadecimal values")
stylesheet = SimpleUploadedFile(
"custom.css", b":root { --accent: #123456; }"
)
response = self.client.post(
url, {"name": "Test theme", "stylesheet": stylesheet}
)
self.assertContains(response, "Previewing Test theme")
self.assertFalse(PanelTheme.objects.exists())
self.assertContains(
self.client.get(reverse("panel:preview_stylesheet")), "#123456"
)
self.assertRedirects(self.client.post(url, {"action": "install"}), url)
self.assertEqual(PanelTheme.objects.get().name, "Test theme")
+57 -3
View File
@@ -60,17 +60,19 @@ class WorkspaceTests(TestCase):
dns = reverse("panel:customer_workspace", args=["dns"])
self.assertRedirects(
self.client.get(dns, {"account": second.pk}),
second.get_absolute_url() + "#domains-dns",
reverse("panel:domain_workspace", args=[second.pk, "dns"]),
)
self.assertRedirects(
self.client.get(dns), second.get_absolute_url() + "#domains-dns"
self.client.get(dns),
reverse("panel:domain_workspace", args=[second.pk, "dns"]),
)
self.assertEqual(
self.client.get(dns, {"account": foreign.pk}).status_code, 404
)
HostingAccount.objects.filter(pk=second.pk).update(customer=None)
self.assertRedirects(
self.client.get(dns), first.get_absolute_url() + "#domains-dns"
self.client.get(dns),
reverse("panel:domain_workspace", args=[first.pk, "dns"]),
)
def test_manager_creates_login_and_hosting_under_its_own_policy(self):
@@ -120,3 +122,55 @@ class WorkspaceTests(TestCase):
self.assertFalse(
get_user_model().objects.filter(username="overflow").exists()
)
def test_transfer_preserves_every_active_account_in_the_customer_scope(
self,
):
users = get_user_model().objects
operator = users.create_superuser("operator")
manager = Reseller.objects.create(user=users.create_user("source"))
destination = Reseller.objects.create(
user=users.create_user("destination"), account_limit=2
)
customer = Customer.objects.create(
user=users.create_user("customer"), reseller=manager
)
plan = HostingPlan.objects.create(name="Small")
destination.hosting_plans.add(plan)
accounts = [
HostingAccount.objects.create(
name=label,
primary_domain=f"{label}.example.test",
customer=customer,
reseller=manager,
hosting_plan=plan,
)
for label in ("first", "second")
]
from django_otp.plugins.otp_totp.models import TOTPDevice
device = TOTPDevice.objects.create(user=operator, name="test")
self.client.force_login(operator)
session = self.client.session
session["otp_device_id"] = device.persistent_id
session.save()
url = reverse("panel:move_accounts")
data = {"account": accounts[0].pk, "manager": destination.pk}
self.assertContains(
self.client.post(url, data | {"action": "move", "confirm": "on"}),
"Preview and confirm",
)
preview = self.client.post(url, data | {"action": "preview"})
for account in accounts:
self.assertContains(preview, account.primary_domain)
response = self.client.post(
url, data | {"action": "move", "confirm": "on"}
)
self.assertRedirects(response, accounts[0].get_absolute_url())
customer.refresh_from_db()
self.assertEqual(customer.reseller_id, destination.pk)
self.assertEqual(destination.hostingaccount_set.count(), 2)
self.client.force_login(manager.user)
self.assertEqual(
self.client.get(accounts[0].get_absolute_url()).status_code, 404
)
+65 -2
View File
@@ -21,9 +21,10 @@ from .account_security import (
)
from .backup_restores import RestoreKind
from .credential_views import DatabaseCredentialView, MailboxCredentialView
from .customer_backup_views import CustomerBackupView
from .customer_backup_views import CustomerBackupView, CustomerRestoreView
from .dns_defaults_views import DnsDefaultsView
from .dns_replica_views import DnsReplicaView
from .domain_services import domain_workspace
from .health_views import ServiceHealthView
from .independent_website_views import (
IndependentWebsiteCreate,
@@ -34,7 +35,16 @@ from .installation_views import FeatureConfigurationView, InstallationView
from .invitations import AcceptInvitation, ManageInvitation
from .mail_dns_views import MailDnsCheckView, RequestMailDnsSetup
from .mail_policy_views import MailRoutingEditor, MailVacationEditor
from .mail_queue_views import MailQueueView
from .mail_queue_views import MailQueueIndex, MailQueueView, mail_queue_action
from .operator_tools import ConnectedNodesView, OperatorToolsView
from .panel_content import (
AnnouncementView,
DirectAdminGuideView,
ThemeManagementView,
ThemeSelectionView,
preview_stylesheet,
user_stylesheet,
)
from .panel_roles import AssignPanelRoleView, switch_panel_role
from .password_reset import (
CustomerPasswordResetView,
@@ -75,6 +85,49 @@ from .workspaces import customer_workspace, system_workspace
app_name = "panel"
urlpatterns = [
path("mail-queue/", MailQueueIndex.as_view(), name="mail_queue_index"),
path(
"mail-domains/<int:pk>/queue/change/",
mail_queue_action,
name="mail_queue_action",
),
path(
"system/nodes/", ConnectedNodesView.as_view(), name="connected_nodes"
),
path(
"service-health/actions/",
OperatorToolsView.as_view(page="services"),
name="operator_service_actions",
),
path(
"updates/server-packages/",
OperatorToolsView.as_view(page="packages"),
name="server_updates",
),
path(
"server/database/",
OperatorToolsView.as_view(page="database"),
name="database_monitor",
),
path("themes/", ThemeManagementView.as_view(), name="theme_management"),
path(
"my-account/theme/",
ThemeSelectionView.as_view(),
name="theme_selection",
),
path("themes/preview.css", preview_stylesheet, name="preview_stylesheet"),
path("user-theme.css", user_stylesheet, name="user_stylesheet"),
path("announcements/", AnnouncementView.as_view(), name="announcements"),
path(
"imports/directadmin/",
DirectAdminGuideView.as_view(),
name="directadmin_guide",
),
path(
"accounts/<int:pk>/domains/<slug:page>/",
domain_workspace,
name="domain_workspace",
),
path(
"hosting/<slug:page>/", customer_workspace, name="customer_workspace"
),
@@ -99,6 +152,11 @@ urlpatterns = [
CustomerBackupView.as_view(),
name="customer_backups",
),
path(
"hosting/<int:pk>/backups/<int:backup_pk>/restore/<slug:kind>/",
CustomerRestoreView.as_view(),
name="customer_restore",
),
path("panel-theme.css", themes.stylesheet, name="theme_stylesheet"),
path("updates/", UpdateView.as_view(), name="updates"),
path("dns-template/", DnsDefaultsView.as_view(), name="dns_defaults"),
@@ -127,6 +185,11 @@ urlpatterns = [
FeatureConfigurationView.as_view(),
name="feature_configuration",
),
path(
"settings/<slug:section>/",
FeatureConfigurationView.as_view(),
name="operator_settings",
),
path("account/role/", switch_panel_role, name="switch_panel_role"),
path(
"logins/assign-role/",
+20 -9
View File
@@ -77,6 +77,7 @@ from .dns_forms import (
zone_record_rows,
)
from .dns_publication import queue_dns_publication
from .domain_policies import require_managed
from .health_views import STALE_AFTER
from .impersonation import (
CUSTOMER_WRITE_PERMISSIONS,
@@ -1058,9 +1059,7 @@ class SiteStorageLimitEdit(
return redirect(self.account)
class SitePhpSettingsEdit(
OperatorOnlyMixin, PermissionRequiredMixin, FormView
):
class SitePhpSettingsEdit(PermissionRequiredMixin, FormView):
permission_required = CHANGE_SITE_PHP_SETTINGS
form_class = SitePhpSettingsForm
template_name = "hosting/site_php_settings_form.html"
@@ -1070,14 +1069,21 @@ class SitePhpSettingsEdit(
raise Http404
return super().dispatch(request, *args, **kwargs)
def has_permission(self):
user = self.request.user
return customer_for_user(user) is not None or (
reseller_for_user(user) is None and super().has_permission()
)
@cached_property
def account(self):
return get_object_or_404(
HostingAccount.objects.select_related(
"hosting_plan", "php_settings_job"
),
pk=self.kwargs["pk"],
)
accounts = HostingAccount.objects.select_related(
"hosting_plan", "php_settings_job"
).filter(retired_at__isnull=True)
customer = customer_for_user(self.request.user)
if customer is not None:
accounts = accounts.filter(customer=customer)
return get_object_or_404(accounts, pk=self.kwargs["pk"])
def get_initial(self):
job = getattr(self.account, "php_settings_job", None)
@@ -1099,6 +1105,9 @@ class SitePhpSettingsEdit(
self.account.pk,
None if use_plan else settings_from_form(form.cleaned_data),
use_plan=use_plan,
customer_id=self.account.customer_id
if customer_for_user(self.request.user) is not None
else None,
)
except HostingAccount.DoesNotExist:
raise Http404 from None
@@ -2210,6 +2219,7 @@ class DnsZoneCreate(OperatorOnlyMixin, DnsZoneEditor):
self.account.pk, customer_id=None
)
require_open_account(account)
require_managed(account, account.primary_domain, "dns_managed")
zone = HostingDnsZone.objects.create(
account=account,
domain=account.primary_domain,
@@ -2332,6 +2342,7 @@ class DnsZoneEdit(DnsZoneEditor):
self.account.pk, customer_id=None
)
require_open_account(account)
require_managed(account, self.zone.domain, "dns_managed")
self.check_managed_mail_records(values)
zones = HostingDnsZone.objects.filter(
pk=self.zone.pk, serial=serial
+78 -5
View File
@@ -1,14 +1,17 @@
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.core.paginator import Paginator
from django.db.models import Count
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.utils import timezone
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_safe
from .access import customer_for_user, reseller_for_user
from .installation_features import panel_feature_allowed
from .models import HostingAccount
from .models import HostingAccount, WebsiteScheduledJob
CUSTOMER_ACCOUNT = "coulobre_active_hosting_account"
@@ -87,6 +90,8 @@ def customer_workspace(request, page):
return redirect("panel:accounts")
if page == "overview":
return redirect(account)
if page in {"domains", "dns", "php", "files", "forwarders", "replies"}:
return redirect("panel:domain_workspace", pk=account.pk, page=page)
_, destination, fragment = pages[page]
return redirect(
reverse(
@@ -117,12 +122,60 @@ def system_workspace(request, page):
or reseller_for_user(request.user) is not None
or request.user.has_perm("hosting.view_websiteusage")
)
counts = {
"domain_count": Count("website_domains", distinct=True),
"database_count": Count("databases", distinct=True),
"mailbox_count": Count("mail_domains__mailboxes", distinct=True),
}
pagination = Paginator(
accounts.annotate(**counts).prefetch_related("website_usage"), 25
)
page_obj = pagination.get_page(request.GET.get("page"))
month = timezone.now().strftime("%Y-%m")
rows = []
for account in page_obj.object_list:
snapshots = [
row.report
for row in account.website_usage.all()
if row.observed_at
]
storage = [
row["storage_bytes"]
for row in snapshots
if row.get("storage_bytes") is not None
]
traffic = [
row["traffic_bytes"]
for row in snapshots
if row.get("month") == month
and row.get("traffic_bytes") is not None
]
rows.append(
(
account,
sum(storage) if storage else None,
sum(traffic) if traffic else None,
)
)
tasks = ()
task_accounts = set(account.pk for account, _, _ in rows)
if page == "tasks":
tasks = (
WebsiteScheduledJob.objects.filter(account_id__in=task_accounts)
.select_related("account")
.order_by("domain", "name")[:250]
)
return render(
request,
"hosting/system_workspace.html",
{
"title": title,
"accounts": accounts,
"section": page,
"rows": rows,
"tasks": tasks,
"month": month,
"page_obj": page_obj,
"is_paginated": pagination.num_pages > 1,
"target": f"panel:{target}" if may_open else None,
},
)
@@ -185,7 +238,7 @@ def groups_for(request, *, customer, manager):
("view_hostingaccount", "accounts", "Hosting accounts"),
("view_customer", "all_users", "Show All Users"),
("view_reseller", "resellers", "Managers"),
("add_reseller", "reseller_create", "Add New Reseller"),
("add_reseller", "reseller_create", "Add Manager"),
("view_hostingplan", "hosting_plans", "Hosting plans"),
):
if user.has_perm(f"hosting.{permission}"):
@@ -193,22 +246,42 @@ def groups_for(request, *, customer, manager):
server, admin_tools = [], []
if user.has_perm("hosting.view_webprovisioningplan"):
server.append(link("plans", "Web provisioning"))
if user.has_perm("hosting.view_hostingmaildomain") and user.has_perm(
"hosting.view_hostingaccount"
):
admin_tools.append(link("mail_queue_index", "Mail Queue"))
if user.has_perm("hosting.view_servicehealth"):
admin_tools.append(link("service_health", "System Services"))
if user.is_superuser:
accounts.extend(
(
link("operator_create", "Add New Operator"),
link("reseller_profiles", "Reseller Packages"),
link("reseller_profiles", "Manager Packages"),
link("move_accounts", "Move Users"),
)
)
server.extend(
(
link("feature_configuration", "Operator Settings"),
link("operator_settings", "Operator Settings", "general"),
link("dns_defaults", "DNS Settings"),
)
)
if user.is_superuser:
admin_tools.extend(
(
link("theme_management", "Themes"),
link("announcements", "Message"),
link("directadmin_guide", "Import"),
)
)
if user.is_superuser:
server.append(link("connected_nodes", "Connected Nodes"))
admin_tools.extend(
(
link("operator_service_actions", "Service actions"),
link("database_monitor", "DB Monitor"),
)
)
groups = [
("Account Manager", accounts),
("Server Manager", server),
+18 -3
View File
@@ -167,10 +167,18 @@ class MailboxSigningRequest:
def parse_mailbox_request(data):
from .mail_policy import OPERATIONS, parse_mail_policy
from .mail_queue import MailQueueRequest
from .mail_queue import MailQueueAction, MailQueueRequest
if isinstance(data, dict) and data.get("operation") == "inspect_queue":
if isinstance(data, dict) and data.get("operation") in {
"inspect_queue",
"inspect_queue_entries",
}:
return MailQueueRequest.from_manifest(data)
if (
isinstance(data, dict)
and data.get("operation") == "change_queue_entry"
):
return MailQueueAction.from_manifest(data)
if isinstance(data, dict) and data.get("operation") in OPERATIONS:
return parse_mail_policy(data)
return parse_retirement(
@@ -203,10 +211,17 @@ def mailbox_request_identity(spec):
def apply_mailbox_request(request):
from .mail_policy import MailRouting, MailVacation
from .mail_queue import MailQueueRequest, inspect_queue
from .mail_queue import (
MailQueueAction,
MailQueueRequest,
change_queue_entry,
inspect_queue,
)
if isinstance(request, MailQueueRequest):
return inspect_queue(request)
if isinstance(request, MailQueueAction):
return change_queue_entry(request)
if isinstance(request, MailboxUsageRequest):
return inspect_mailbox_usage(request.mailbox)
if isinstance(request, MailRouting):
+142 -6
View File
@@ -1,35 +1,118 @@
import json
import re
import subprocess
from dataclasses import dataclass
from .domain_names import canonical_domain
MAX_QUEUE_ROWS = 20000
QUEUE_ID = re.compile(r"[A-Za-z0-9]{5,32}")
QUEUE_ACTIONS = {
"flush": ("/usr/sbin/postqueue", "-i"),
"hold": ("/usr/sbin/postsuper", "-h"),
"release": ("/usr/sbin/postsuper", "-H"),
}
QUEUE_NAMES = ("active", "deferred", "hold", "incoming", "maildrop")
@dataclass(frozen=True)
class MailQueueRequest:
domain: str
detailed: bool = False
def __post_init__(self):
object.__setattr__(self, "domain", canonical_domain(self.domain))
def manifest(self):
return {"operation": "inspect_queue", "domain": self.domain}
operation = (
"inspect_queue_entries" if self.detailed else "inspect_queue"
)
return {"operation": operation, "domain": self.domain}
@classmethod
def from_manifest(cls, data):
if data.keys() != {"operation", "domain"}:
raise ValueError("Expected a mail queue request.")
return cls(data["domain"])
return cls(
data["domain"], data["operation"] == "inspect_queue_entries"
)
def summarize_queue(lines, domain):
@dataclass(frozen=True)
class MailQueueAction:
domain: str
queue_id: str
arrival: int
action: str
def __post_init__(self):
object.__setattr__(self, "domain", canonical_domain(self.domain))
if not isinstance(self.queue_id, str) or not QUEUE_ID.fullmatch(
self.queue_id
):
raise ValueError("Choose a valid mail queue entry.")
if (
self.action not in QUEUE_ACTIONS
or type(self.arrival) is not int
or not 0 < self.arrival < 2**53
):
raise ValueError("Choose an available queue action.")
def manifest(self):
return {
"operation": "change_queue_entry",
"domain": self.domain,
"queue_id": self.queue_id,
"arrival": self.arrival,
"action": self.action,
}
@classmethod
def from_manifest(cls, data):
if data.keys() != {
"operation",
"domain",
"queue_id",
"arrival",
"action",
}:
raise ValueError("Expected a mail queue action.")
return cls(
data["domain"], data["queue_id"], data["arrival"], data["action"]
)
def visible_entry(message, domain):
recipients = [
item["address"].rpartition("@")[2].lower()
for item in message["recipients"]
]
queue_id = message.get("queue_id", "")
arrival = message.get("arrival_time")
if not recipients or any(item != domain for item in recipients):
return None
if (
not QUEUE_ID.fullmatch(queue_id)
or type(arrival) is not int
or not 0 < arrival < 2**53
):
return None
return {
"queue_id": queue_id,
"arrival": arrival,
"queue": message["queue_name"],
}
def summarize_queue(lines, domain, *, detailed=False):
counts = dict.fromkeys(QUEUE_NAMES, 0)
report = {"counts": counts, "partial": False}
if detailed:
report["entries"] = []
for index, line in enumerate(lines):
if index == MAX_QUEUE_ROWS:
return {"counts": counts, "partial": True}
report["partial"] = True
return report
if len(line) > 1024 * 1024:
raise ValueError("Postfix returned an oversized queue entry.")
message = json.loads(line)
@@ -43,10 +126,22 @@ def summarize_queue(lines, domain):
for address in addresses
):
counts[queue] += 1
return {"counts": counts, "partial": False}
if detailed and len(report["entries"]) < 100:
entry = visible_entry(message, domain)
if entry:
report["entries"].append(entry)
return report
def inspect_queue(request):
return read_queue(
lambda lines: summarize_queue(
lines, request.domain, detailed=request.detailed
)
)
def read_queue(consume):
with subprocess.Popen(
["/usr/sbin/postqueue", "-j"],
stdin=subprocess.DEVNULL,
@@ -56,7 +151,7 @@ def inspect_queue(request):
) as process:
try:
lines = iter(lambda: process.stdout.readline(1024 * 1024 + 1), b"")
result = summarize_queue(lines, request.domain)
result = consume(lines)
if not result["partial"] and process.wait(timeout=5):
raise ValueError("Postfix could not read the mail queue.")
return result
@@ -67,3 +162,44 @@ def inspect_queue(request):
finally:
if process.poll() is None:
process.kill()
def change_queue_entry(request):
def find_entry(lines):
for index, line in enumerate(lines):
if index == MAX_QUEUE_ROWS or len(line) > 1024 * 1024:
break
message = json.loads(line)
if message.get("queue_id") == request.queue_id:
return {
"entry": visible_entry(message, request.domain),
"partial": True,
}
return {"entry": None, "partial": True}
entry = read_queue(find_entry)["entry"]
if entry is None or entry["arrival"] != request.arrival:
raise ValueError("The queue entry changed or is outside this domain.")
expected = {
"flush": ("deferred",),
"hold": ("active", "deferred"),
"release": ("hold",),
}
if entry["queue"] not in expected[request.action]:
raise ValueError(
"This action is unavailable for the entry's current queue."
)
try:
subprocess.run(
[*QUEUE_ACTIONS[request.action], request.queue_id],
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=True,
timeout=25,
env={"PATH": "/usr/sbin:/usr/bin", "LC_ALL": "C"},
)
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as error:
raise ValueError(
"Postfix could not complete the queue action."
) from error
+180
View File
@@ -0,0 +1,180 @@
import hashlib
import os
import re
import subprocess
from dataclasses import dataclass
from pathlib import Path
from .node_files import locked_root_directory
from .node_requests import serve_apply_request
SOCKET = "/run/coulobre-operator-apply.sock"
STATE = Path("/var/lib/coulobre/operator")
SERVICES = {
"apache": "apache2.service",
"dns": "named.service",
"smtp": "postfix.service",
"imap": "dovecot.service",
"spam": "rspamd.service",
}
ACTIONS = (
"package-preview",
"package-upgrade",
"reload",
"restart",
"database-report",
)
APT = "/usr/bin/apt-get"
@dataclass(frozen=True)
class OperatorRequest:
action: str
target: str = ""
plan: str = ""
def __post_init__(self):
if self.action not in ACTIONS:
raise ValueError("Choose a supported operator action.")
if self.action in {"reload", "restart"}:
if self.target not in SERVICES:
raise ValueError("Choose a managed service.")
elif self.target:
raise ValueError("This operation does not use a service target.")
if self.action == "package-upgrade":
if not re.fullmatch(r"[a-f0-9]{64}", self.plan):
raise ValueError("Review the package plan before applying it.")
elif self.plan:
raise ValueError("This operation does not use a package plan.")
@classmethod
def from_manifest(cls, payload):
if (
not isinstance(payload, dict)
or payload.keys() != {"version", "action", "target", "plan"}
or type(payload["version"]) is not int
or payload["version"] != 1
or any(
not isinstance(payload[key], str)
for key in ("action", "target", "plan")
)
):
raise ValueError("Expected an operator request.")
return cls(payload["action"], payload["target"], payload["plan"])
def manifest(self):
return {
"version": 1,
"action": self.action,
"target": self.target,
"plan": self.plan,
}
def command(*args, timeout=90):
try:
result = subprocess.run(
args,
stdin=subprocess.DEVNULL,
capture_output=True,
timeout=timeout,
check=False,
env={
"PATH": "/usr/sbin:/usr/bin",
"LC_ALL": "C",
"DEBIAN_FRONTEND": "noninteractive",
},
)
except subprocess.TimeoutExpired:
raise ValueError(
"The host operation timed out. Review the service journal."
) from None
if result.returncode:
raise ValueError(
"The host operation failed. Review the service journal."
)
return result.stdout.decode("utf-8", errors="replace")
def apt_plan():
output = command(APT, "--simulate", "--no-remove", "upgrade")
lines = [line for line in output.splitlines() if line.startswith("Inst ")]
digest = hashlib.sha256("\n".join(lines).encode()).hexdigest()
return {
"fingerprint": digest,
"packages": [line[:240] for line in lines[:90]],
"count": len(lines),
}
def packages(request):
with locked_root_directory(STATE):
if request.action == "package-preview":
command(APT, "update", timeout=180)
return apt_plan()
plan = apt_plan()
if request.plan != plan["fingerprint"]:
raise ValueError(
"The package plan changed. Collect and review a new preview."
)
if plan["count"]:
command(
APT,
"-o",
"Dpkg::Options::=--force-confold",
"--yes",
"--no-remove",
"upgrade",
timeout=1500,
)
report = apt_plan()
return {"upgrades_remaining": report["count"]}
def database_report():
query = (
"SELECT @@version, @@slow_query_log; SHOW GLOBAL STATUS WHERE "
"Variable_name IN ('Threads_connected','Slow_queries','Uptime');"
)
output = command(
"/usr/bin/mariadb",
"--batch",
"--skip-column-names",
"--protocol=socket",
"--execute",
query,
)
rows = [row.split("\t") for row in output.splitlines()]
if not rows or any(len(row) != 2 for row in rows):
raise ValueError("MariaDB returned an invalid status report.")
version, slow_log = rows[0]
counters = {key: value for key, value in rows[1:] if value.isdecimal()}
return {
"version": version[:80],
"slow_logging": slow_log == "1",
"counters": counters,
}
def apply_request(request):
if os.geteuid() != 0:
raise ValueError("Run operator actions as root on the host.")
if request.action.startswith("package-"):
if os.environ.get("COULOBRE_SERVER_PACKAGE_UPDATES") != "1":
raise ValueError(
"Enable server package updates in the host configuration."
)
return packages(request)
if request.action == "database-report":
return database_report()
with locked_root_directory(STATE):
service = SERVICES[request.target]
command("/usr/bin/systemctl", request.action, service)
command("/usr/bin/systemctl", "is-active", "--quiet", service)
return {"active": True}
def main():
return serve_apply_request(
1, OperatorRequest.from_manifest, apply_request, include_result=True
)
+1
View File
@@ -111,6 +111,7 @@ TEMPLATES = [
"django.contrib.messages.context_processors.messages",
"coulobre.hosting.access.panel_access",
"coulobre.hosting.themes.panel_appearance",
"coulobre.hosting.panel_content.panel_announcements",
],
},
},