Complete operator and customer workflows for Coulobre 0.12

This commit is contained in:
parkel committed 2026-11-23 23:27:02 +01:00
1 parent 4b60663821
commit 5bddcd5512
72 files changed
+2674 -215

No files matched your search

+16 -2
View File
@@ -50,18 +50,31 @@ def can_manage_hosting(user, permissions):
)
def owns_customer_operations(user, account):
customer = customer_for_user(user)
if customer is not None:
return account.customer_id == customer.pk
return not is_tenant(user) and account.customer_id is None
def panel_access(request):
customer = customer_for_user(request.user) is not None
reseller = not customer and reseller_for_user(request.user) is not None
from .workspaces import CUSTOMER_ACCOUNT, groups_for, workspace_accounts
from .workspaces import (
CUSTOMER_ACCOUNT,
active_navigation,
groups_for,
workspace_accounts,
)
operator = request.user.is_authenticated and not (customer or reseller)
groups = groups_for(request, customer=customer, manager=reseller)
active_link = active_navigation(request, customer=customer)
current = next(
(
label
for label, links in groups
if any(url == request.path for url, _ in links)
if any(url == active_link for url, _ in links)
),
"",
)
@@ -82,6 +95,7 @@ def panel_access(request):
"is_operator": operator,
"navigation_groups": groups,
"open_workspace_group": current,
"active_navigation_link": active_link,
"workspace_accounts": available if len(available) > 1 else [],
"workspace_selected": selected,
}
@@ -19,6 +19,7 @@ from django.views.generic import FormView, ListView
from coulobre.domain_names import canonical_domain
from .access import OperatorOnlyMixin, reseller_for_user
from .account_metrics import customer_metrics
from .account_setup import setup_new_account
from .dns_defaults import zone_defaults
from .installation_features import (
@@ -262,6 +263,22 @@ class AllUsersView(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
.order_by("username")
)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
profiles = [
getattr(user, "hosting_customer", None)
for user in context["logins"]
]
measurements = customer_metrics(
[profile.pk for profile in profiles if profile],
operator=self.request.user,
)
context["login_rows"] = [
(login, measurements.get(profile.pk) if profile else None)
for login, profile in zip(context["logins"], profiles, strict=True)
]
return context
class OperatorAuthorization(UserPassesTestMixin):
def test_func(self):
+92
View File
@@ -0,0 +1,92 @@
from collections import defaultdict
from django.db.models import Count
from django.utils import timezone
from .models import (
HostingAccount,
HostingDatabase,
HostingMailbox,
WebsiteDomain,
WebsiteUsage,
)
def account_metrics(accounts, *, databases=True, mailboxes=True):
accounts = list(accounts)
metrics = {
account.pk: {
"domains": 1,
"databases": 0 if databases else None,
"mailboxes": 0 if mailboxes else None,
"storage": None,
"traffic": None,
}
for account in accounts
}
if not metrics:
return metrics
counts = (
(WebsiteDomain, "account_id", "domains", True),
(HostingDatabase, "account_id", "databases", databases),
(HostingMailbox, "mail_domain__account_id", "mailboxes", mailboxes),
)
for model, field, key, enabled in counts:
if enabled:
for row in (
model.objects.filter(**{f"{field}__in": metrics})
.values(field)
.annotate(total=Count("pk"))
.order_by()
):
metrics[row[field]][key] = row["total"]
month = timezone.now().strftime("%Y-%m")
for item in WebsiteUsage.objects.filter(
account_id__in=metrics, observed_at__isnull=False
).values("account_id", "report"):
report = item["report"]
result = metrics[item["account_id"]]
if type(report.get("storage_bytes")) is int:
result["storage"] = (result["storage"] or 0) + report[
"storage_bytes"
]
if (
report.get("month") == month
and type(report.get("traffic_bytes")) is int
):
result["traffic"] = (result["traffic"] or 0) + report[
"traffic_bytes"
]
return metrics
def customer_metrics(customers, *, manager=None, operator=None):
accounts = HostingAccount.objects.filter(
retired_at__isnull=True,
customer_id__in=customers,
)
if manager:
accounts = accounts.filter(reseller=manager)
if operator and not operator.has_perm("hosting.view_hostingaccount"):
return {}
accounts = list(accounts.only("id", "customer_id"))
measurements = account_metrics(
accounts,
databases=not operator
or operator.has_perm("hosting.view_hostingdatabase"),
mailboxes=not operator
or operator.has_perm("hosting.view_hostingmailbox"),
)
rows = defaultdict(list)
for account in accounts:
rows[account.customer_id].append(measurements[account.pk])
result = {}
for customer, values in rows.items():
totals = {}
for key in ("domains", "databases", "mailboxes", "storage", "traffic"):
numbers = [
value[key] for value in values if value[key] is not None
]
totals[key] = sum(numbers) if numbers else None
result[customer] = totals
return result
+2 -1
View File
@@ -79,10 +79,11 @@ class HostingPlanAdmin(admin.ModelAdmin):
@admin.register(Reseller)
class ResellerAdmin(admin.ModelAdmin):
list_display = ("user", "account_limit", "manage_resources")
list_display = ("user", "account_limit")
list_select_related = ("user",)
search_fields = ("user__username",)
filter_horizontal = ("hosting_plans",)
exclude = ("manage_resources",)
def get_exclude(self, request, obj=None):
excluded = list(super().get_exclude(request, obj) or ())
+79 -12
View File
@@ -1,5 +1,7 @@
from datetime import timedelta
from pathlib import Path
from django import forms
from django.conf import settings
from django.core.exceptions import PermissionDenied, ValidationError
from django.core.paginator import Paginator
@@ -10,9 +12,10 @@ from django.urls import reverse
from django.utils import timezone
from django.views.decorators.cache import never_cache
from django.views.decorators.debug import sensitive_variables
from django.views.decorators.http import require_http_methods, require_safe
from django.views.decorators.http import require_http_methods
from coulobre.domain_names import canonical_domain
from coulobre.operator_node import SOCKET
from coulobre.web_certificates import ACTIONS
from coulobre.web_node import WebSite
@@ -20,11 +23,31 @@ from .access import customer_for_user
from .certificate_uploads import CertificateUploadForm, seal_upload
from .independent_websites import active_websites
from .installation_features import panel_feature_allowed
from .models import HostingAccount, WebsiteCertificateJob
from .models import HostingAccount, OperatorOperation, WebsiteCertificateJob
from .resource_requests import lock_hosting_account, require_active_services
from .sftp import site_is_active
class AcmePreferencesForm(forms.Form):
email = forms.EmailField(
required=False,
label="ACME registration contact",
max_length=254,
help_text="Leave blank to use the web node's existing registration.",
)
wildcard = forms.BooleanField(
required=False,
label="Include a wildcard name",
help_text="Use the web node's configured DNS-01 hooks.",
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields[
"wildcard"
].disabled = not settings.WEBSITE_WILDCARD_CERTIFICATES
def account_certificate_sites(account):
sites = [
website.spec
@@ -37,7 +60,14 @@ def account_certificate_sites(account):
@transaction.atomic
def queue_certificate(
account, site, actor, action, customer_id, *, encrypted_upload=""
account,
site,
actor,
action,
customer_id,
*,
encrypted_upload="",
acme=None,
):
account = lock_hosting_account(account.pk, customer_id)
require_active_services(account)
@@ -46,13 +76,10 @@ def queue_certificate(
recent = account.certificate_jobs.filter(site=site.manifest())
if recent.filter(finished_at__isnull=True).exists():
raise ValidationError("Wait for the current certificate operation.")
if (
action == "reissue"
and recent.filter(
action=action,
requested_at__gte=timezone.now() - timedelta(hours=12),
).exists()
):
if (action == "reissue" or acme) and recent.filter(
action__in=("reissue", "issue"),
requested_at__gte=timezone.now() - timedelta(hours=12),
).exists():
raise ValidationError(
"Wait 12 hours before requesting another reissue."
)
@@ -63,6 +90,7 @@ def queue_certificate(
requested_customer_id=customer_id,
action=action,
encrypted_upload=encrypted_upload,
acme=acme or {},
)
@@ -100,7 +128,17 @@ def customer_certificates(request, pk):
request.POST if is_upload else None,
request.FILES if is_upload else None,
)
if request.method == "POST" and (not is_upload or upload_form.is_valid()):
is_acme = (
request.method == "POST"
and tab == "acme"
and request.POST.get("action") in {"issue", "reissue"}
)
acme_form = AcmePreferencesForm(request.POST if is_acme else None)
if (
request.method == "POST"
and (not is_upload or upload_form.is_valid())
and (not is_acme or acme_form.is_valid())
):
if not site or not enabled:
raise Http404
action = request.POST.get("action")
@@ -119,6 +157,7 @@ def customer_certificates(request, pk):
action,
customer.pk,
encrypted_upload=encrypted_upload,
acme=acme_form.cleaned_data if is_acme else None,
)
except HostingAccount.DoesNotExist:
raise Http404 from None
@@ -151,6 +190,7 @@ def customer_certificates(request, pk):
"tab": tab,
"certificate": certificate,
"upload_form": upload_form,
"acme_form": acme_form,
"history": history,
"enabled": enabled,
"problem": problem,
@@ -160,13 +200,35 @@ def customer_certificates(request, pk):
@never_cache
@require_safe
@require_http_methods(("GET", "HEAD", "POST"))
def operator_certificates(request):
if not (request.user.is_superuser and request.user.is_verified()):
raise PermissionDenied
mode = request.GET.get("tab", "websites")
if mode not in {"websites", "server"}:
raise Http404
latest = OperatorOperation.objects.filter(action="server-tls").order_by(
"-pk"
)
if request.method == "POST":
if mode != "server" or not Path(SOCKET).is_socket():
raise Http404
from .tasks import run_operator_operation
with transaction.atomic():
type(request.user).objects.select_for_update().get(
pk=request.user.pk
)
if not latest.filter(finished_at__isnull=True).exists():
job = OperatorOperation.objects.create(
actor=request.user, action="server-tls"
)
transaction.on_commit(
lambda: run_operator_operation.delay(job.pk)
)
return redirect(
reverse("panel:operator_certificates", query={"tab": "server"})
)
accounts = HostingAccount.objects.filter(retired_at__isnull=True).order_by(
"primary_domain"
)
@@ -196,6 +258,11 @@ def operator_certificates(request):
"page_obj": page_obj,
"is_paginated": page_obj.has_other_pages,
"panel_origin": settings.PASSWORD_RESET_ORIGIN,
"tls_job": latest.first(),
"tls_available": Path(SOCKET).is_socket(),
"tls_result": latest.filter(
finished_at__isnull=False, problem=""
).first(),
"imap_host": settings.MAIL_IMAP_HOST,
"submission_host": settings.MAIL_SUBMISSION_HOST,
},
+1 -1
View File
@@ -201,7 +201,7 @@ class DnsZoneForm(forms.Form):
)
delegate_dns = forms.BooleanField(
label="Delegate record editing",
help_text="Allow the customer and assigned reseller to edit records.",
help_text="Allow customers to edit this Coulobre-managed zone.",
required=False,
)
+106
View File
@@ -0,0 +1,106 @@
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.http import Http404
from django.shortcuts import redirect
from django.urls import reverse
from django.views.generic import FormView
from .account_administration import OperatorAuthorization
from .domain_policies import policy_for
from .domain_services import (
DomainServicesForm,
allowed_domains,
save_domain_policy,
)
from .models import HostingAccount
from .update_views import inspect_linked_nodes
class OperatorDomainServicesForm(DomainServicesForm):
account = forms.ModelChoiceField(
queryset=HostingAccount.objects.filter(
retired_at__isnull=True
).order_by("primary_domain")
)
domain = forms.CharField(max_length=253)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.order_fields(["account", "domain", "dns_managed", "mail_managed"])
def clean(self):
data = super().clean()
account = data.get("account")
domain = data.get("domain")
if account and domain:
from coulobre.domain_names import canonical_domain
try:
domain = canonical_domain(domain)
except ValueError as error:
self.add_error("domain", str(error))
else:
if domain not in allowed_domains(account):
self.add_error(
"domain",
"Choose a domain assigned to the hosting account.",
)
data["domain"] = domain
return data
class DnsTopologyView(OperatorAuthorization, FormView):
form_class = OperatorDomainServicesForm
template_name = "hosting/dns_topology.html"
def get_initial(self):
selected = self.request.GET.get("account")
domain = self.request.GET.get("domain")
if selected is None or domain is None:
return {}
if (
not selected.isascii()
or not selected.isdecimal()
or len(selected) > 18
):
raise Http404
account = HostingAccount.objects.filter(
pk=int(selected), retired_at__isnull=True
).first()
if account is None or domain not in allowed_domains(account):
raise Http404
policy = policy_for(account, domain)
return {
"account": account.pk,
"domain": domain,
"dns_managed": policy.dns_managed,
"mail_managed": policy.mail_managed,
}
def get_context_data(self, **kwargs):
return super().get_context_data(
topology=inspect_linked_nodes(),
local_dns=settings.LOCAL_DNS_PUBLISHING,
local_mail=settings.LOCAL_MAILBOX_PROVISIONING,
**kwargs,
)
def form_valid(self, form):
data = form.cleaned_data
account = data["account"]
domain = data["domain"]
choices = {key: data[key] for key in ("dns_managed", "mail_managed")}
try:
save_domain_policy(account.pk, domain, None, choices)
except HostingAccount.DoesNotExist:
raise Http404 from None
except ValidationError as error:
form.add_error(None, error)
return self.form_invalid(form)
return redirect(
reverse(
"panel:dns_topology",
query={"account": account.pk, "domain": domain},
)
)
+52 -2
View File
@@ -11,6 +11,8 @@ from django.views.decorators.http import require_http_methods
from coulobre.domain_names import canonical_domain
from .access import customer_for_user
from .account_setup import website_records
from .dns_defaults import zone_defaults
from .dns_forms import zone_record_rows
from .domain_policies import policy_for
from .independent_websites import account_websites
@@ -60,6 +62,8 @@ def allowed_domains(account):
"domain", flat=True
)
)
domains.update(account.mail_domains.values_list("domain", flat=True))
domains.update(account.dns_zones.values_list("domain", flat=True))
return sorted(domains)
@@ -69,6 +73,19 @@ def save_domain_policy(account_id, domain, customer_id, choices):
require_open_account(account)
if domain not in allowed_domains(account):
raise Http404
previous = policy_for(account, domain)
if (
previous.mail_managed
and not choices["mail_managed"]
and account.mail_domains.filter(
domain=domain,
mailboxes__provisioning__finished_at__isnull=False,
mailboxes__provisioning__problem="",
).exists()
):
raise ValidationError(
"Move the managed mailboxes before switching to external email."
)
DomainServicePolicy.objects.update_or_create(
account=account, domain=domain, defaults=choices
)
@@ -77,7 +94,16 @@ def save_domain_policy(account_id, domain, customer_id, 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"}:
if page not in {
"domains",
"dns",
"php",
"files",
"email",
"forwarders",
"replies",
"spam",
}:
raise Http404
customer = customer_for_user(request.user)
if customer is None:
@@ -141,7 +167,7 @@ def domain_workspace(request, pk, page):
)
mail_domain = (
account.mail_domains.filter(domain=domain).first()
if page in {"forwarders", "replies"}
if page in {"dns", "email", "forwarders", "replies", "spam"}
else None
)
titles = {
@@ -149,9 +175,15 @@ def domain_workspace(request, pk, page):
"dns": "DNS Editor",
"php": "PHP Settings",
"files": "File Manager",
"email": "Email Accounts",
"spam": "Spam protection",
"forwarders": "Forwarders",
"replies": "Automatic replies",
}
from .mail_policies import mail_policy_available
from .roundcube import roundcube_available
defaults = zone_defaults() if page == "dns" else None
return render(
request,
"hosting/domain_workspace.html",
@@ -165,7 +197,25 @@ def domain_workspace(request, pk, page):
"policy": policy,
"zone": zone,
"records": zone_record_rows(zone.spec) if zone else (),
"external_website_records": website_records(
domain,
www=defaults.include_www,
wildcard=defaults.include_wildcard,
addresses=defaults.addresses,
)
if page == "dns" and not policy.dns_managed
else (),
"zone_defaults": defaults,
"mail_domain": mail_domain,
"mail_enabled": panel_feature_allowed(
"LOCAL_MAILBOX_PROVISIONING"
),
"can_edit_routing": mail_policy_available("routing"),
"can_edit_mailbox": mail_policy_available("vacation"),
"roundcube_enabled": roundcube_available(request),
"mailboxes": mail_domain.mailboxes.select_related("provisioning")
if mail_domain
else (),
"website": website,
"primary": primary,
"can_add_site": panel_feature_allowed("LOCAL_WEB_ACTIVATION"),
@@ -21,6 +21,11 @@ from .independent_websites import (
)
from .installation_features import panel_feature_allowed
from .models import HostingAccount, IndependentWebsite, WebsiteDomain
from .php_settings import (
SitePhpSettingsForm,
plan_php_settings,
settings_from_form,
)
class WebsiteCreateForm(forms.Form):
@@ -136,8 +141,9 @@ class IndependentWebsiteOperation(IndependentWebsiteEditor):
operation = Operation(self.kwargs["operation"])
except ValueError:
raise Http404 from None
if operation == Operation.HTTPS and not panel_feature_allowed(
"LOCAL_WEB_HTTPS"
if operation == Operation.SETTINGS or (
operation == Operation.HTTPS
and not panel_feature_allowed("LOCAL_WEB_HTTPS")
):
raise Http404
return operation
@@ -187,6 +193,52 @@ class IndependentWebsiteOperation(IndependentWebsiteEditor):
return redirect(self.account)
class IndependentWebsitePhpSettings(IndependentWebsiteEditor):
form_class = SitePhpSettingsForm
template_name = "hosting/site_php_settings_form.html"
@cached_property
def website(self):
return get_object_or_404(
account_websites(self.account),
pk=self.kwargs["site_pk"],
activated=True,
retired_at__isnull=True,
)
def get_initial(self):
return (
self.website.applied_php_settings
or plan_php_settings(self.account).manifest()
)
def get_context_data(self, **kwargs):
return super().get_context_data(
site_domain=self.website.reservation.domain,
plan_settings=plan_php_settings(self.account),
**kwargs,
)
def form_valid(self, form):
try:
queue_website_operation(
self.account.pk,
self.website.pk,
Operation.SETTINGS,
"",
self.request.user,
php_settings=None
if form.cleaned_data["use_plan"]
else settings_from_form(form.cleaned_data),
)
except (HostingAccount.DoesNotExist, IndependentWebsite.DoesNotExist):
raise Http404 from None
except ValidationError as error:
form.add_error(None, error)
return self.form_invalid(form)
return redirect(self.account)
class IndependentWebsiteManifest(
OperatorOnlyMixin, PermissionRequiredMixin, View
):
+43 -3
View File
@@ -16,8 +16,10 @@ from .node_client import (
apply_on_local_node,
enable_local_https,
set_local_site_storage_limit,
update_local_php_settings,
update_local_php_version,
)
from .php_settings import limit_customer_php_settings, plan_php_settings
from .resource_requests import lock_hosting_account, require_active_services
Operation = IndependentWebsite.Operation
@@ -54,7 +56,7 @@ def website_actions(website):
return (Operation.ACTIVATE, Operation.RETIRE)
if website.suspended:
return (Operation.RESUME, Operation.RETIRE)
actions = (Operation.PHP, Operation.SUSPEND)
actions = (Operation.PHP, Operation.SETTINGS, Operation.SUSPEND)
if panel_feature_allowed("LOCAL_WEB_HTTPS") and not website.https_enabled:
actions += (Operation.HTTPS,)
return actions
@@ -101,7 +103,15 @@ def create_website(account_id, domain, version, actor):
@transaction.atomic
def queue_website_operation(account_id, site_id, operation, version, actor):
def queue_website_operation(
account_id,
site_id,
operation,
version,
actor,
*,
php_settings=None,
):
account = lock_hosting_account(account_id, customer_id=None)
check_actor(account, actor)
require_active_services(account)
@@ -127,9 +137,19 @@ def queue_website_operation(account_id, site_id, operation, version, actor):
).exists()
):
raise ValidationError("Wait for the backup or restore to finish.")
customer = customer_for_user(actor)
if operation == Operation.SETTINGS:
if php_settings is None:
php_settings = plan_php_settings(account)
elif customer is not None:
php_settings = limit_customer_php_settings(account, php_settings)
IndependentWebsite.objects.requeue(
IndependentWebsite.objects.filter(pk=website.pk),
operation=operation,
requested_customer_id=customer.pk if customer else None,
requested_php_settings=php_settings.manifest()
if php_settings
else None,
requested_php_version=(
version
if operation in (Operation.ACTIVATE, Operation.PHP)
@@ -143,6 +163,10 @@ def apply_website_operation(website):
site = website.spec
operation = website.operation
account = website.reservation.account
if website.requested_customer_id is not None and (
account.customer_id != website.requested_customer_id
):
raise ValueError("The hosting account's customer assignment changed.")
try:
require_active_services(account)
except ValidationError as error:
@@ -156,7 +180,7 @@ def apply_website_operation(website):
raise ValueError(" ".join(error.messages)) from None
if operation == Operation.ACTIVATE:
plan = account.hosting_plan
_, version = activate_local_site(
options, version = activate_local_site(
site,
plan.get_php_settings() if plan else PhpPoolSettings(),
(requested,) if requested else allowed_versions(account),
@@ -167,10 +191,26 @@ def apply_website_operation(website):
return {
"activated": True,
"php_version": version,
"applied_php_settings": options.manifest()
if isinstance(options, PhpPoolSettings)
else None,
"storage_limit_mib": limit,
}
if operation == Operation.PHP:
return {"php_version": update_local_php_version(site, requested)}
if operation == Operation.SETTINGS:
requested_settings = PhpPoolSettings.from_manifest(
website.requested_php_settings
)
if website.requested_customer_id is not None:
try:
requested_settings = limit_customer_php_settings(
account, requested_settings
)
except ValidationError as error:
raise ValueError(" ".join(error.messages)) from None
applied = update_local_php_settings(site, requested_settings)
return {"applied_php_settings": applied.manifest()}
if operation == Operation.HTTPS:
if not settings.LOCAL_WEB_HTTPS:
raise ValueError("Enable the website HTTPS worker first.")
+7
View File
@@ -5,6 +5,7 @@ from django.db import transaction
from coulobre.mail_policy import MailRouting, parse_mail_policy
from .access import is_tenant, manages_account
from .domain_policies import require_managed
from .models import HostingMailDomain
from .node_client import apply_on_local_node
from .resource_requests import lock_hosting_account, require_active_services
@@ -24,6 +25,12 @@ def policy_account(resource):
def validate_policy(resource, spec, account):
require_active_services(account)
domain = (
resource.domain
if isinstance(resource, HostingMailDomain)
else resource.mail_domain.domain
)
require_managed(account, domain, "mail_managed")
if isinstance(spec, MailRouting):
validate_routing(resource, spec, account.hosting_plan)
else:
+62 -4
View File
@@ -1,8 +1,9 @@
from dataclasses import replace
from datetime import UTC
from django import forms
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.exceptions import ValidationError
from django.core.exceptions import PermissionDenied, ValidationError
from django.http import Http404
from django.shortcuts import redirect
from django.utils import timezone
@@ -19,7 +20,12 @@ from coulobre.mail_policy import (
parse_mail_policy,
)
from .access import TenantScopeMixin, can_manage_hosting, reseller_for_user
from .access import (
TenantScopeMixin,
can_manage_hosting,
owns_customer_operations,
reseller_for_user,
)
from .mail_policies import (
mail_policy_available,
policy_account,
@@ -57,9 +63,10 @@ def mail_policy_enabled(request, kind):
class MailPolicyForm(forms.Form):
revision = forms.CharField(required=False, widget=forms.HiddenInput)
def __init__(self, *args, resource, **kwargs):
def __init__(self, *args, resource, policy=None, **kwargs):
super().__init__(*args, **kwargs)
self.resource = resource
self.policy = policy
def clean(self):
cleaned = super().clean()
@@ -162,10 +169,38 @@ class MailVacationForm(MailPolicyForm):
return MailVacation(
self.resource.spec,
repeat_days=cleaned.get("repeat_days") or DEFAULT_REPEAT_DAYS,
move_spam=self.policy.move_spam if self.policy else False,
junk_senders=self.policy.junk_senders if self.policy else (),
**values,
)
class MailSpamForm(MailPolicyForm):
move_spam = forms.BooleanField(
required=False, label="Move messages tagged as spam to Junk"
)
junk_senders = forms.CharField(
required=False,
max_length=5500,
label="Senders to move to Junk",
help_text="Enter up to 20 full sender addresses, one per line.",
widget=forms.Textarea(attrs={"rows": 5}),
)
def make_spec(self, cleaned):
policy = self.policy or MailVacation(self.resource.spec, enabled=False)
senders = tuple(
line.strip()
for line in cleaned["junk_senders"].splitlines()
if line.strip()
)
return replace(
policy,
move_spam=cleaned["move_spam"],
junk_senders=senders,
)
@method_decorator(never_cache, name="dispatch")
class MailPolicyEditor(
TenantScopeMixin, PermissionRequiredMixin, SingleObjectMixin, FormView
@@ -195,10 +230,19 @@ class MailPolicyEditor(
if not mail_policy_available(self.kind):
raise Http404
self.object = self.get_object()
if not owns_customer_operations(
self.request.user, policy_account(self.object)
):
raise PermissionDenied
self.job = getattr(self.object, self.kind, None)
def get_form_kwargs(self):
return super().get_form_kwargs() | {"resource": self.object}
return super().get_form_kwargs() | {
"resource": self.object,
"policy": parse_mail_policy(self.job.manifest)
if self.job
else None,
}
def get_initial(self):
initial = {"revision": policy_revision(self.job)}
@@ -277,3 +321,17 @@ class MailVacationEditor(MailPolicyEditor):
kind = "vacation"
target = "mailbox"
title = "Automatic replies"
class MailSpamEditor(MailVacationEditor):
form_class = MailSpamForm
title = "Spam protection"
extra_context = {"spam_editor": True}
def get_initial(self):
initial = super().get_initial()
if self.job:
spec = parse_mail_policy(self.job.manifest)
initial["move_spam"] = spec.move_spam
initial["junk_senders"] = "\n".join(spec.junk_senders)
return initial
@@ -0,0 +1,82 @@
# Generated by Django 5.2.19 on 2026-11-23 22:08
import uuid
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", "0073_folder_sftp_login"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="SystemBackupSchedule",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("enabled", models.BooleanField(default=False)),
("time", models.TimeField(null=True)),
("next_run_at", models.DateTimeField(null=True)),
],
),
migrations.CreateModel(
name="SystemBackupJob",
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)),
(
"identifier",
models.UUIDField(
default=uuid.uuid4, editable=False, unique=True
),
),
(
"scheduled_for",
models.DateTimeField(null=True, unique=True),
),
("report", models.JSONField(default=dict)),
(
"actor",
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
to=settings.AUTH_USER_MODEL,
),
),
],
options={
"abstract": False,
},
),
]
@@ -0,0 +1,44 @@
# Generated by Django 5.2.19 on 2026-11-23 22:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0074_system_backups"),
]
operations = [
migrations.AddField(
model_name="independentwebsite",
name="applied_php_settings",
field=models.JSONField(blank=True, null=True),
),
migrations.AddField(
model_name="independentwebsite",
name="requested_customer_id",
field=models.PositiveBigIntegerField(blank=True, null=True),
),
migrations.AddField(
model_name="independentwebsite",
name="requested_php_settings",
field=models.JSONField(blank=True, null=True),
),
migrations.AlterField(
model_name="independentwebsite",
name="operation",
field=models.CharField(
choices=[
("activate", "Provision website"),
("php", "Change PHP series"),
("settings", "Change PHP settings"),
("https", "Enable HTTPS"),
("suspend", "Suspend website"),
("resume", "Resume website"),
("retire", "Retire website"),
],
default="activate",
max_length=8,
),
),
]
@@ -0,0 +1,17 @@
# Generated by Django 5.2.19 on 2026-11-23 22:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0075_independent_php_settings"),
]
operations = [
migrations.AddField(
model_name="operatoroperation",
name="parameters",
field=models.JSONField(default=dict),
),
]
@@ -0,0 +1,17 @@
# Generated by Django 5.2.19 on 2026-11-23 22:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0076_http_template_changes"),
]
operations = [
migrations.AddField(
model_name="websitecertificatejob",
name="acme",
field=models.JSONField(default=dict),
),
]
@@ -0,0 +1,57 @@
# Generated by Django 5.2.19 on 2026-11-23 22:24
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0077_acme_preferences"),
]
operations = [
migrations.AlterModelOptions(
name="reseller",
options={
"verbose_name": "manager",
"verbose_name_plural": "managers",
},
),
migrations.AlterModelOptions(
name="resellerprofile",
options={
"ordering": ("name",),
"verbose_name": "manager profile",
"verbose_name_plural": "manager profiles",
},
),
migrations.AlterField(
model_name="hostingaccount",
name="reseller",
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.PROTECT,
to="hosting.reseller",
verbose_name="manager",
),
),
migrations.AlterField(
model_name="resellerauditevent",
name="action",
field=models.CharField(
choices=[
("create", "Created manager"),
("update", "Updated manager"),
("assign", "Assigned hosting account"),
("unassign", "Unassigned hosting account"),
("plan", "Changed hosting account plan"),
("cust_add", "Created customer login"),
("cust_lnk", "Linked customer login"),
("request", "Requested hosting resource"),
("deploy", "Queued resource provisioning"),
],
max_length=8,
),
),
]
+38 -3
View File
@@ -64,6 +64,10 @@ class Reseller(models.Model):
)
hosting_plans = models.ManyToManyField("HostingPlan", blank=True)
class Meta:
verbose_name = "manager"
verbose_name_plural = "managers"
def __str__(self):
return self.user.get_username()
@@ -85,6 +89,8 @@ class ResellerProfile(models.Model):
class Meta:
ordering = ("name",)
verbose_name = "manager profile"
verbose_name_plural = "manager profiles"
def __str__(self):
return self.name
@@ -99,8 +105,8 @@ class ResellerProfile(models.Model):
class ResellerAuditEvent(models.Model):
class Action(models.TextChoices):
CREATE = "create", "Created reseller"
UPDATE = "update", "Updated reseller"
CREATE = "create", "Created manager"
UPDATE = "update", "Updated manager"
ASSIGN = "assign", "Assigned hosting account"
UNASSIGN = "unassign", "Unassigned hosting account"
PLAN = "plan", "Changed hosting account plan"
@@ -432,7 +438,11 @@ class HostingAccount(models.Model):
HostingPlan, on_delete=models.PROTECT, null=True, blank=True
)
reseller = models.ForeignKey(
Reseller, on_delete=models.PROTECT, null=True, blank=True
Reseller,
on_delete=models.PROTECT,
null=True,
blank=True,
verbose_name="manager",
)
customer = models.ForeignKey(
Customer, on_delete=models.PROTECT, null=True, blank=True
@@ -886,6 +896,23 @@ class DatabaseLogin(ProvisioningJob):
return DatabaseLoginSpec(self.database.spec, self.pk)
class SystemBackupJob(ProvisioningJob):
identifier = models.UUIDField(
default=uuid.uuid4, unique=True, editable=False
)
actor = models.ForeignKey(
settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL
)
scheduled_for = models.DateTimeField(unique=True, null=True)
report = models.JSONField(default=dict)
class SystemBackupSchedule(models.Model):
enabled = models.BooleanField(default=False)
time = models.TimeField(null=True)
next_run_at = models.DateTimeField(null=True)
class OperatorOperation(ProvisioningJob):
actor = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True
@@ -896,6 +923,7 @@ class OperatorOperation(ProvisioningJob):
source = models.OneToOneField(
"self", on_delete=models.SET_NULL, null=True, blank=True
)
parameters = models.JSONField(default=dict)
result = models.JSONField(default=dict)
@@ -1091,6 +1119,7 @@ class WebsiteCertificateJob(ProvisioningJob):
null=True,
)
requested_customer_id = models.PositiveBigIntegerField(null=True)
acme = models.JSONField(default=dict)
encrypted_upload = models.TextField(blank=True, default="")
certificate = models.JSONField(default=dict)
@@ -1147,6 +1176,7 @@ class IndependentWebsite(ProvisioningJob):
class Operation(models.TextChoices):
ACTIVATE = "activate", "Provision website"
PHP = "php", "Change PHP series"
SETTINGS = "settings", "Change PHP settings"
HTTPS = "https", "Enable HTTPS"
SUSPEND = "suspend", "Suspend website"
RESUME = "resume", "Resume website"
@@ -1165,6 +1195,11 @@ class IndependentWebsite(ProvisioningJob):
requested_php_version = models.CharField(max_length=5, blank=True)
php_version = models.CharField(max_length=5, blank=True)
storage_limit_mib = models.PositiveIntegerField(null=True, blank=True)
requested_php_settings = models.JSONField(null=True, blank=True)
applied_php_settings = models.JSONField(null=True, blank=True)
requested_customer_id = models.PositiveBigIntegerField(
null=True, blank=True
)
retirement_id = models.UUIDField(default=uuid.uuid4, editable=False)
class Meta:
+175
View File
@@ -0,0 +1,175 @@
from django import forms
from django.contrib import messages
from django.contrib.admin.models import CHANGE, LogEntry
from django.core.exceptions import ValidationError
from django.core.paginator import Paginator
from django.db import transaction
from django.db.models import OuterRef, Subquery
from django.http import Http404
from django.shortcuts import redirect
from django.urls import reverse
from django.views.generic import FormView
from .account_administration import OperatorAuthorization
from .account_backups import (
mail_backups_enabled,
queue_account_backup,
save_backup_schedule,
)
from .installation_features import panel_feature_allowed
from .models import (
AccountBackupJob,
AccountBackupSchedule,
HostingAccount,
Reseller,
)
from .resource_requests import lock_hosting_account
class GroupBackupForm(forms.Form):
manager = forms.ModelChoiceField(
queryset=Reseller.objects.select_related("user")
)
action = forms.ChoiceField(
choices=[
("run", "Run backups now"),
("schedule", "Set a daily schedule"),
]
)
include_mailboxes = forms.BooleanField(required=False)
time = forms.TimeField(
required=False,
label="Daily time (UTC)",
input_formats=["%H:%M"],
widget=forms.TimeInput(format="%H:%M", attrs={"type": "time"}),
)
confirmed = forms.BooleanField(
label="Apply to every active hosting account assigned to this manager"
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["include_mailboxes"].disabled = not mail_backups_enabled()
def clean(self):
data = super().clean()
if data.get("action") == "schedule" and not data.get("time"):
self.add_error("time", "Choose a daily start time.")
return data
class OperatorBackupsView(OperatorAuthorization, FormView):
form_class = GroupBackupForm
template_name = "hosting/operator_backups.html"
def selected_manager(self):
return self.request.GET.get("manager", "")
def accounts(self):
scope = HostingAccount.objects.filter(retired_at__isnull=True)
manager = self.selected_manager()
if manager:
if (
not manager.isascii()
or not manager.isdecimal()
or len(manager) > 18
):
raise Http404
scope = scope.filter(reseller_id=int(manager))
return scope
def get_initial(self):
return {"manager": self.selected_manager()}
def get_context_data(self, **kwargs):
latest = AccountBackupJob.objects.filter(
account_id=OuterRef("pk")
).order_by("-pk")
accounts = (
self.accounts()
.select_related("reseller__user", "backup_schedule")
.annotate(
last_backup=Subquery(latest.values("requested_at")[:1]),
last_completed=Subquery(latest.values("finished_at")[:1]),
last_problem=Subquery(latest.values("problem")[:1]),
)
.order_by("primary_domain")
)
page = Paginator(accounts, 30).get_page(self.request.GET.get("page"))
return super().get_context_data(
accounts=page.object_list,
page_obj=page,
is_paginated=page.has_other_pages(),
managers=Reseller.objects.select_related("user").order_by(
"user__username"
),
selected_manager=self.selected_manager(),
enabled=panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS"),
**kwargs,
)
def form_valid(self, form):
if not panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS"):
raise Http404
data = form.cleaned_data
manager = data["manager"]
accounts = (
HostingAccount.objects.filter(
reseller=manager, retired_at__isnull=True
)
.order_by("pk")
.values_list("pk", flat=True)
)
successes = skipped = 0
for pk in list(accounts):
try:
if apply_group_backup(pk, manager.pk, data):
successes += 1
else:
skipped += 1
except (HostingAccount.DoesNotExist, ValidationError):
skipped += 1
LogEntry.objects.log_actions(
self.request.user.pk,
[manager],
CHANGE,
f"Backup {data['action']}: {successes} accepted, "
f"{skipped} skipped.",
)
messages.success(
self.request,
f"{successes} accounts accepted. {skipped} skipped.",
)
return redirect(
reverse("panel:operator_backups", query={"manager": manager.pk})
)
@transaction.atomic
def apply_group_backup(account_id, manager_id, data):
account = lock_hosting_account(account_id, customer_id=None)
if account.reseller_id != manager_id or account.retired_at is not None:
return False
if data["action"] == "run":
return (
queue_account_backup(
account.pk, include_mailboxes=data["include_mailboxes"]
)
is not None
)
existing = getattr(account, "backup_schedule", None)
save_backup_schedule(
account.pk,
can_manage_mail=True,
schedule_fields={
"enabled": True,
"frequency": AccountBackupSchedule.Frequency.DAILY,
"weekday": None,
"time": data["time"],
"include_mailboxes": data["include_mailboxes"],
"offsite_destination": existing.offsite_destination
if existing
else "",
},
)
return True
+100
View File
@@ -164,3 +164,103 @@ class ConnectedNodesView(OperatorAuthorization, TemplateView):
return super().get_context_data(
topology=inspect_linked_nodes(), **kwargs
)
class HttpDefaultsForm(forms.Form):
def __init__(self, *args, target, **kwargs):
from coulobre.http_defaults import CONTROLS
super().__init__(*args, **kwargs)
self.target = target
for key, (label, minimum, maximum, default) in CONTROLS[
target
].items():
self.fields[key] = forms.IntegerField(
label=label,
min_value=minimum,
max_value=maximum,
initial=default,
)
def clean(self):
from coulobre.http_defaults import HttpDefaultsRequest
values = super().clean()
if not self.errors:
try:
self.requested = HttpDefaultsRequest(self.target, values)
except ValueError as error:
raise forms.ValidationError(str(error)) from error
return values
class HttpDefaultsView(OperatorAuthorization, FormView):
form_class = HttpDefaultsForm
template_name = "hosting/http_defaults.html"
def target(self):
from django.http import Http404
target = self.kwargs["target"]
if target not in ("apache", "php"):
raise Http404
return target
def history(self):
return OperatorOperation.objects.filter(
action="http-defaults", target=self.target()
).order_by("-pk")
def get_initial(self):
latest = (
self.history()
.filter(finished_at__isnull=False, problem="")
.first()
)
return latest.parameters if latest else {}
def get_form_kwargs(self):
return super().get_form_kwargs() | {"target": self.target()}
def get_context_data(self, **kwargs):
return super().get_context_data(
target=self.target(),
available=Path(SOCKET).is_socket(),
jobs=self.history()[:10],
**kwargs,
)
def form_valid(self, form):
spec = form.requested
manifest = spec.manifest()
if self.request.POST.get("action") != "apply":
self.request.session["http_template_preview"] = manifest
return self.render_to_response(
self.get_context_data(
form=form,
preview=spec.render(),
)
)
if not Path(SOCKET).is_socket():
form.add_error(None, "Start the local operator worker.")
return self.form_invalid(form)
if self.request.session.pop("http_template_preview", None) != manifest:
form.add_error(
None, "Review the exact template before applying it."
)
return self.form_invalid(form)
with transaction.atomic():
locked = type(self.request.user).objects.select_for_update()
locked.get(pk=self.request.user.pk)
if self.history().filter(finished_at__isnull=True).exists():
form.add_error(None, "Wait for the current template change.")
return self.form_invalid(form)
job = OperatorOperation.objects.create(
actor=self.request.user,
action="http-defaults",
target=self.target(),
parameters=spec.values,
)
transaction.on_commit(lambda: run_operator_operation.delay(job.pk))
messages.success(self.request, "HTTP template change queued.")
return redirect(self.request.path)
+18 -14
View File
@@ -109,6 +109,23 @@ def plan_php_versions(account):
return plan.allowed_php_versions() if plan is not None else ()
def limit_customer_php_settings(account, requested):
limits = plan_php_settings(account).manifest()
values = requested.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:
return PhpPoolSettings.from_manifest(values)
except PhpPoolSettingsError as error:
raise ValidationError(str(error)) from error
@transaction.atomic
def queue_site_php_settings(
account_id, php_settings, *, use_plan=False, customer_id=None
@@ -123,20 +140,7 @@ def queue_site_php_settings(
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
php_settings = limit_customer_php_settings(account, php_settings)
changes = {
"domain": account.primary_domain,
+2 -2
View File
@@ -98,7 +98,7 @@ def update_reseller(reseller_id, policy, actor):
if "is_active" in policy and user.is_active != policy["is_active"]:
if not may_manage_sign_in(user):
raise ValidationError(
"This login can no longer be managed as a reseller."
"This login can no longer be managed as a manager."
)
user.is_active = policy["is_active"]
user.save(update_fields=["is_active"])
@@ -121,7 +121,7 @@ def create_reseller_account(access, account):
reseller = lock_resellers(candidates).first()
if reseller is None or not reseller.user.is_active:
raise ValidationError(
{NON_FIELD_ERRORS: "Your reseller access has changed."}
{NON_FIELD_ERRORS: "Your manager access has changed."}
)
if reseller.hostingaccount_set.count() >= reseller.account_limit:
raise ValidationError(
@@ -69,3 +69,26 @@ def save_customer_link(account, reseller, customer, action):
{"customer": str(customer)},
account_domain=account.primary_domain,
)
@transaction.atomic
def claim_customer_hosting(access, account_id):
account, manager = lock_reseller_account(access, account_id)
require_unassigned_customer(account)
customer, created = Customer.objects.get_or_create(
user_id=manager.user_id, defaults={"reseller": manager}
)
if customer.reseller_id not in {None, manager.pk}:
raise ValidationError(
"Your customer profile belongs to another manager."
)
if customer.reseller_id is None:
customer.reseller = manager
customer.save(update_fields=["reseller"])
save_customer_link(
account,
manager,
customer,
Action.CUSTOMER_CREATE if created else Action.CUSTOMER_LINK,
)
return account
@@ -1,19 +1,28 @@
from django import forms
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.exceptions import ValidationError
from django.db import IntegrityError
from django.contrib.auth.mixins import (
PermissionRequiredMixin,
UserPassesTestMixin,
)
from django.core.exceptions import PermissionDenied, ValidationError
from django.db import IntegrityError, transaction
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect
from django.utils.functional import cached_property
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_POST
from django.views.generic import FormView
from .access import reseller_for_user
from .invitations import InviteLoginForm, queue_invitation
from .models import HostingAccount
from .models import HostingAccount, HostingPlan
from .reseller_accounts import save_operator_account
from .reseller_onboarding import (
claim_customer_hosting,
create_reseller_customer,
link_reseller_customer,
lock_reseller_account,
scoped_customers,
)
@@ -103,3 +112,76 @@ class ResellerCustomerLink(ResellerCustomerEditor):
form.add_error(None, error)
return self.form_invalid(form)
return redirect(account)
@require_POST
@never_cache
def claim_own_customer_hosting(request, pk):
manager = reseller_for_user(request.user)
if manager is None:
raise PermissionDenied
try:
account = claim_customer_hosting(manager, pk)
except HostingAccount.DoesNotExist:
raise Http404 from None
except ValidationError as error:
messages.error(request, " ".join(error.messages))
return redirect("panel:account", pk=pk)
messages.success(
request, "This hosting account is now in your Customer workspace."
)
return redirect(account)
class ManagerHostingPlanForm(forms.Form):
plan = forms.ModelChoiceField(queryset=HostingPlan.objects.none())
def __init__(self, *args, manager, **kwargs):
super().__init__(*args, **kwargs)
self.fields["plan"].queryset = manager.hosting_plans.order_by("name")
class ManagerHostingPlanView(UserPassesTestMixin, FormView):
form_class = ManagerHostingPlanForm
template_name = "hosting/workspace_form.html"
extra_context = {
"title": "Assign hosting plan",
"submit_label": "Assign plan",
}
def test_func(self):
self.manager = reseller_for_user(self.request.user)
return self.manager is not None
@cached_property
def account(self):
return get_object_or_404(
self.manager.hostingaccount_set.filter(retired_at__isnull=True),
pk=self.kwargs["pk"],
)
def get_form_kwargs(self):
return super().get_form_kwargs() | {"manager": self.manager}
def get_initial(self):
return {"plan": self.account.hosting_plan_id}
@transaction.atomic
def form_valid(self, form):
try:
account, manager = lock_reseller_account(
self.manager, self.account.pk
)
except HostingAccount.DoesNotExist:
raise Http404 from None
chosen = form.cleaned_data["plan"]
if not manager.hosting_plans.filter(pk=chosen.pk).exists():
form.add_error("plan", "This plan is no longer available.")
return self.form_invalid(form)
account.hosting_plan = chosen
save_operator_account(
account,
self.request.user.get_username(),
changed_fields=["hosting_plan"],
)
return redirect(account)
+1 -1
View File
@@ -19,7 +19,7 @@ class ResellerProfileForm(forms.ModelForm):
class Meta:
model = ResellerProfile
fields = ("name", "account_limit", "hosting_plans", "manage_resources")
fields = ("name", "account_limit", "hosting_plans")
help_texts = {
"account_limit": "Enter 0 to manage existing accounts only.",
}
+2 -10
View File
@@ -32,16 +32,8 @@ class ResellerPolicyForm(forms.ModelForm):
class Meta:
model = Reseller
fields = (
"is_active",
"account_limit",
"hosting_plans",
"manage_resources",
)
labels = {
"hosting_plans": "Allowed hosting plans",
"manage_resources": "Manage databases and mailboxes",
}
fields = ("is_active", "account_limit", "hosting_plans")
labels = {"hosting_plans": "Allowed hosting plans"}
help_texts = {
"account_limit": "Enter 0 to manage existing accounts only.",
"hosting_plans": (
+16 -3
View File
@@ -57,13 +57,26 @@ def create_database_request(
@transaction.atomic
def create_mailbox_request(
account_id, local_part, *, customer_id=None, auto_provision=False
account_id,
local_part,
*,
customer_id=None,
auto_provision=False,
mail_domain_name=None,
):
account = lock_hosting_account(account_id, customer_id)
require_open_account(account)
require_managed(account, account.primary_domain, "mail_managed")
domain = mail_domain_name or account.primary_domain
if domain != account.primary_domain:
from .domain_services import allowed_domains
if domain not in allowed_domains(account):
raise ValidationError(
"This mail domain is outside the hosting account."
)
require_managed(account, domain, "mail_managed")
try:
spec = MailboxSpec(account.primary_domain, local_part)
spec = MailboxSpec(domain, local_part)
except ValueError as error:
raise ValidationError({"local_part": str(error)}) from error
+123
View File
@@ -0,0 +1,123 @@
from datetime import UTC, datetime, timedelta
from pathlib import Path
from django import forms
from django.conf import settings
from django.contrib import messages
from django.contrib.admin.models import CHANGE, LogEntry
from django.db import transaction
from django.http import Http404
from django.shortcuts import redirect
from django.utils import timezone
from django.views.generic import FormView
from coulobre.operator_node import SOCKET
from .account_administration import OperatorAuthorization
from .models import SystemBackupJob, SystemBackupSchedule
class SystemBackupScheduleForm(forms.Form):
enabled = forms.BooleanField(required=False, label="Run daily")
time = forms.TimeField(
required=False,
label="Daily start time (UTC)",
input_formats=["%H:%M"],
widget=forms.TimeInput(format="%H:%M", attrs={"type": "time"}),
)
def clean(self):
data = super().clean()
if data.get("enabled") and not data.get("time"):
self.add_error("time", "Choose the daily start time.")
return data
def next_system_backup(time, now):
candidate = datetime.combine(now.astimezone(UTC).date(), time, tzinfo=UTC)
return candidate if candidate > now else candidate + timedelta(days=1)
@transaction.atomic
def queue_scheduled_system_backup(now):
schedule = (
SystemBackupSchedule.objects.select_for_update().filter(pk=1).first()
)
if (
schedule is None
or not schedule.enabled
or schedule.time is None
or schedule.next_run_at is None
or schedule.next_run_at > now
):
return
if not SystemBackupJob.objects.filter(finished_at__isnull=True).exists():
SystemBackupJob.objects.get_or_create(
scheduled_for=schedule.next_run_at
)
schedule.next_run_at = next_system_backup(schedule.time, now)
schedule.save(update_fields=["next_run_at"])
class SystemBackupView(OperatorAuthorization, FormView):
form_class = SystemBackupScheduleForm
template_name = "hosting/system_backup.html"
def available(self):
return settings.SYSTEM_BACKUPS and Path(SOCKET).is_socket()
def get_initial(self):
schedule = SystemBackupSchedule.objects.filter(pk=1).first()
return (
{"enabled": schedule.enabled, "time": schedule.time}
if schedule
else {}
)
def get_context_data(self, **kwargs):
return super().get_context_data(
available=self.available(),
jobs=SystemBackupJob.objects.select_related("actor").order_by(
"-pk"
)[:30],
**kwargs,
)
@transaction.atomic
def post(self, request, *args, **kwargs):
if not self.available():
raise Http404
if request.POST.get("action") != "create":
return super().post(request, *args, **kwargs)
if request.POST.get("confirm") != "yes":
messages.error(
request, "Confirm that you want to create the backup."
)
return redirect("panel:system_backup")
SystemBackupSchedule.objects.get_or_create(pk=1)
SystemBackupSchedule.objects.select_for_update().get(pk=1)
if SystemBackupJob.objects.filter(finished_at__isnull=True).exists():
messages.error(request, "Wait for the current backup.")
else:
SystemBackupJob.objects.create(actor=request.user)
messages.success(request, "System backup queued.")
return redirect("panel:system_backup")
def form_valid(self, form):
data = form.cleaned_data
defaults = data | {
"next_run_at": next_system_backup(data["time"], timezone.now())
if data["enabled"]
else None,
}
schedule, _ = SystemBackupSchedule.objects.update_or_create(
pk=1, defaults=defaults
)
LogEntry.objects.log_actions(
self.request.user.pk,
[schedule],
CHANGE,
"Changed system backup schedule.",
)
messages.success(self.request, "System backup schedule saved.")
return redirect("panel:system_backup")
+53 -1
View File
@@ -62,6 +62,7 @@ from .models import (
SiteSFTP,
SiteStorageLimit,
SiteStorageUsage,
SystemBackupJob,
WebActivation,
WebHTTPS,
WebProvisioningPlan,
@@ -1312,13 +1313,18 @@ def collect_mailbox_usage(mailbox_id, requested_at):
@shared_task(queue="coulobre-operator-actions")
def run_operator_operation(job_id):
from coulobre.http_defaults import HttpDefaultsRequest
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)
spec = (
HttpDefaultsRequest(job.target, job.parameters)
if job.action == "http-defaults"
else OperatorRequest(job.action, job.target, job.plan)
)
result = apply_on_local_node(
spec, SOCKET, "operator service", "host operation", timeout=32 * 60
)
@@ -1465,6 +1471,7 @@ def apply_certificate_job(job_id):
site,
job.action,
*(open_upload(job) if job.action == "upload" else ()),
**job.acme,
)
reply = apply_on_local_node(
spec,
@@ -1623,3 +1630,48 @@ def apply_folder_sftp_job(job_id):
FolderSftpLogin.objects.filter(
pk=job_id, action="remove", problem="", finished_at__isnull=False
).delete()
@shared_task
def dispatch_system_backups():
from .system_backup_views import queue_scheduled_system_backup
if settings.SYSTEM_BACKUPS:
queue_scheduled_system_backup(timezone.now())
dispatch_provisioning_jobs(
SystemBackupJob,
run_system_backup,
"coulobre-operator-actions",
lease=timedelta(minutes=35),
)
@shared_task(
queue="coulobre-operator-actions",
acks_late=True,
reject_on_worker_lost=True,
)
def run_system_backup(job_id):
from coulobre.operator_node import SOCKET, OperatorRequest
from .node_client import apply_on_local_node
def apply(job):
reply = apply_on_local_node(
OperatorRequest("system-backup", target=str(job.identifier)),
SOCKET,
"operator service",
"system backup",
timeout=32 * 60,
)
fields = ("archive", "bytes", "sha256", "created_at")
return {"report": {key: reply[key] for key in fields if key in reply}}
if settings.SYSTEM_BACKUPS:
run_provisioning_job(
SystemBackupJob.objects.all(),
job_id,
apply,
"The operator service did not confirm the system backup.",
lease=timedelta(minutes=35),
)
@@ -14,7 +14,8 @@
</header>
<dl class="details surface">
{% if is_tenant or perms.hosting.view_hostingplan %}
<div><dt>Hosting plan</dt><dd>{% if account.hosting_plan %}{{ account.hosting_plan.name }}{% else %}Unassigned{% endif %}</dd></div>
<div><dt>Hosting plan</dt><dd>{% if account.hosting_plan %}{{ account.hosting_plan.name }}{% else %}Unassigned{% endif %}
{% if is_reseller %}<a class="record-link" href="{% url 'panel:manager_assign_plan' account.pk %}">Assign plan</a>{% endif %}</dd></div>
{% endif %}
{% if is_operator and perms.hosting.view_reseller %}
<div><dt>Manager</dt><dd>{{ account.reseller|default_if_none:"Unassigned" }}</dd></div>
@@ -30,6 +31,9 @@
{% else %}Assigned{% endif %}
{% else %}
<a class="record-link" href="{% url 'panel:reseller_customer_create' account.pk %}">Add customer login</a>
<form method="post" class="inline-form" action="{% url 'panel:claim_customer_hosting' account.pk %}">{% csrf_token %}
<button class="button secondary" type="submit">Use my customer workspace</button>
</form>
{% if reseller_customer_link %}
<a class="record-link" href="{% url 'panel:reseller_customer_link' account.pk %}">Link existing customer</a>
{% endif %}
@@ -140,7 +144,7 @@
{% endif %}
{% endif %}
</div>
{% if is_customer or is_operator and perms.hosting.add_hostingdatabase %}
{% if own_customer_operations and is_customer or own_customer_operations and is_operator and perms.hosting.add_hostingdatabase %}
<a class="button primary" href="{% url 'panel:database_create' account.pk %}">{% if automatic_database_provisioning %}Add{% else %}Request{% endif %} database</a>
{% endif %}
</header>
@@ -305,7 +309,7 @@
{% endif %}
{% endif %}
</div>
{% if is_customer or is_operator and perms.hosting.add_hostingmailbox %}
{% if own_customer_operations and is_customer or own_customer_operations and is_operator and perms.hosting.add_hostingmailbox %}
<a class="button primary" href="{% url 'panel:mailbox_create' account.pk %}">{% if automatic_mailbox_provisioning %}Add{% else %}Request{% endif %} mailbox</a>
{% endif %}
</header>
@@ -0,0 +1,5 @@
<td>{% if usage and usage.storage is not None %}{{ usage.storage|filesizeformat }}{% else %}Unavailable{% endif %}</td>
<td>{% if usage and usage.traffic is not None %}{{ usage.traffic|filesizeformat }}{% else %}Unavailable{% endif %}</td>
<td>{% if usage %}{{ usage.domains|default_if_none:"Unavailable" }}{% else %}Unavailable{% endif %}</td>
<td>{% if usage %}{{ usage.databases|default_if_none:"Unavailable" }}{% else %}Unavailable{% endif %}</td>
<td>{% if usage %}{{ usage.mailboxes|default_if_none:"Unavailable" }}{% else %}Unavailable{% endif %}</td>
@@ -9,11 +9,11 @@
</form>
<div class="table-scroll">
<table>
<thead><tr><th scope="col">User</th><th scope="col">Workspace</th><th scope="col">Manager</th><th scope="col">Hosting accounts</th><th scope="col">Added</th></tr></thead>
<thead><tr><th scope="col">User</th><th scope="col">Workspace</th><th scope="col">Manager</th><th scope="col">Hosting accounts</th><th scope="col">Disk</th><th scope="col">Monthly traffic</th><th scope="col">Domains</th><th scope="col">Databases</th><th scope="col">Mailboxes</th><th scope="col">Added</th></tr></thead>
<tbody>
{% for login in logins %}
<tr><th scope="row">{{ login.get_username }}</th><td>{% if login.is_superuser %}Operator{% elif login.hosting_reseller %}Manager{% else %}Customer{% endif %}</td><td>{{ login.hosting_customer.reseller|default:"Unassigned" }}</td><td>{{ login.account_count }}</td><td>{{ login.date_joined|date:"j M Y" }}</td></tr>
{% empty %}<tr><td colspan="5">No logins found.</td></tr>{% endfor %}
{% for login, usage in login_rows %}
<tr><th scope="row">{{ login.get_username }}</th><td>{% if login.is_superuser %}Operator{% elif login.hosting_reseller %}Manager{% else %}Customer{% endif %}</td><td>{{ login.hosting_customer.reseller|default:"Unassigned" }}</td><td>{{ login.account_count }}</td>{% include "hosting/account_metrics_cells.html" %}<td>{{ login.date_joined|date:"j M Y" }}</td></tr>
{% empty %}<tr><td colspan="10">No logins found.</td></tr>{% endfor %}
</tbody>
</table>
</div>
@@ -50,7 +50,11 @@
<section class="surface editor-surface" aria-label="ACME settings">
<dl><dt>Challenge method</dt><dd>HTTP-01</dd><dt>Renewal</dt><dd>Managed by Certbot on the web node</dd></dl>
<p>The website's DNS must resolve to this node and HTTP port 80 must be reachable for validation.</p>
<p>Wildcard certificates require DNS-01 support on the server.</p>
{% if enabled %}
<form method="post" class="editor">{% csrf_token %}{{ acme_form.as_div }}
<button class="button primary" type="submit" name="action" value="{% if certificate.certificate.installed %}reissue{% else %}issue{% endif %}">Request ACME certificate</button>
</form>
{% endif %}
</section>
{% else %}
<section class="surface">
@@ -1,9 +1,9 @@
{% extends "hosting/base.html" %}
{% block title %}{% if is_reseller %}My customers{% else %}Customers{% endif %} · Coulobre Panel{% endblock %}
{% block title %}{% if is_reseller %}My users{% else %}Customers{% endif %} · Coulobre Panel{% endblock %}
{% block content %}
<header class="page-heading">
<div>
<h1>{% if is_reseller %}My customers{% else %}Customers{% endif %}</h1>
<h1>{% if is_reseller %}My users{% else %}Customers{% endif %}</h1>
<p class="heading-meta">Manage the logins people use to access their assigned hosting.</p>
</div>
{% if is_operator and perms.hosting.add_customer %}
@@ -29,6 +29,7 @@
<tr>
<th scope="col">Username</th>
<th scope="col">Sign-in status</th>
{% if is_reseller %}<th scope="col">Disk</th><th scope="col">Monthly traffic</th><th scope="col">Domains</th><th scope="col">Databases</th><th scope="col">Mailboxes</th><th scope="col">Added</th>{% endif %}
{% if is_operator and perms.hosting.change_customer or can_impersonate or is_reseller %}<th scope="col">Actions</th>{% endif %}
</tr>
</thead>
@@ -47,6 +48,7 @@
{% else %}<span class="status active">Active</span>
{% endif %}
</td>
{% if is_reseller %}{% include "hosting/account_metrics_cells.html" with usage=customer.workspace_metrics %}<td>{{ customer.user.date_joined|date:"j M Y" }}</td>{% endif %}
{% if is_operator and perms.hosting.change_customer or can_impersonate or is_reseller %}
<td>
<div class="table-actions">
@@ -1,6 +1,10 @@
{% extends "hosting/base.html" %}
{% block title %}DNS zone template · Coulobre Panel{% endblock %}
{% block content %}
<nav class="account-navigation" aria-label="DNS settings">
<a href="{% url 'panel:dns_defaults' %}" aria-current="page">Zone template</a>
<a href="{% url 'panel:dns_topology' %}">Local and remote</a>
</nav>
<header class="page-heading">
<div><h1>DNS zone template</h1><p class="heading-meta">These settings apply when you create a managed DNS zone.</p></div>
</header>
@@ -0,0 +1,20 @@
{% extends "hosting/base.html" %}
{% block title %}DNS Settings · Coulobre Panel{% endblock %}
{% block content %}
<header class="page-heading"><h1>DNS Settings</h1></header>
<nav class="account-navigation" aria-label="DNS settings">
<a href="{% url 'panel:dns_defaults' %}">Zone template</a>
<a href="{% url 'panel:dns_topology' %}" aria-current="page">Local and remote</a>
</nav>
<section class="surface"><header class="section-heading"><h2>Service routing</h2><a href="{% url 'panel:connected_nodes' %}">Connected nodes</a></header>
<ul class="workspace-list">
{% for node in topology.nodes %}<li>{{ node.role|upper }} · {{ node.host }} · {{ node.state|default:"Unavailable"|capfirst }}</li>{% endfor %}
<li>DNS socket configured · {{ local_dns|yesno:"Yes,No" }}</li>
<li>Mail socket configured · {{ local_mail|yesno:"Yes,No" }}</li>
</ul>
{% if topology.problem %}<p class="notice">{{ topology.problem }}</p>{% endif %}
</section>
<section class="surface editor-surface"><h2>Domain service ownership</h2>
<form method="post" class="editor">{% csrf_token %}{{ form.as_div }}<button class="button primary" type="submit">Save domain preferences</button></form>
</section>
{% endblock %}
@@ -22,13 +22,21 @@
{% 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>
<header class="section-heading"><div><h2>DNS records</h2>{% if zone.publication %}<p class="heading-meta">Publication {{ zone.publication.state }}</p>{% endif %}</div>{% 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 %}
{% if not policy.dns_managed %}
<section class="surface"><header class="section-heading"><h2>Records for your DNS provider</h2></header>
<p class="section-text">At your authoritative DNS provider, add or update the web records. Keep existing email records until your mail provider is ready.</p>
<ul class="workspace-list">{% for record in external_website_records %}<li><code>{{ record.name }} {{ record.record_type }} {{ record.address }}</code></li>{% empty %}<li>Ask your hosting provider for the website addresses.</li>{% endfor %}</ul>
{% if mail_domain and policy.mail_managed %}<p class="section-text"><a href="{% url 'panel:mail_dns_check' mail_domain.pk %}">Check MX, SPF, DKIM and DMARC records</a></p>{% endif %}
</section>
{% elif zone_defaults.nameservers %}
<section class="surface section-heading"><div><h2>Nameservers</h2><p class="heading-meta">{{ zone_defaults.nameservers|join:", " }}</p></div></section>
{% endif %}
{% elif page == 'php' or page == 'files' %}
<section class="surface section-heading" aria-label="{{ title }}">
{% if primary %}
@@ -37,19 +45,41 @@
{% 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>
<a class="button secondary" href="{% url 'panel:independent_php_settings' account.pk website.pk %}">Edit PHP limits</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 page == 'email' %}
{% if not policy.mail_managed %}
<p class="notice">This domain uses an external mail provider.</p>
{% else %}
<section class="surface"><header class="section-heading"><h2>Mailboxes on {{ domain }}</h2>
{% if mail_enabled %}<a class="button primary" href="{% url 'panel:mailbox_create' account.pk %}?domain={{ domain }}">Add mailbox</a>{% endif %}
</header>
<div class="table-scroll"><table>
<thead><tr><th scope="col">Email address</th><th scope="col">Quota</th><th scope="col">State</th><th scope="col">Actions</th></tr></thead>
<tbody>{% for mailbox in mailboxes %}<tr><th scope="row">{{ mailbox.spec.address }}</th><td>{{ mailbox.quota_mib|default_if_none:"Unlimited" }}{% if mailbox.quota_mib %} MiB{% endif %}</td><td>{{ mailbox.provisioning.state|default:"Requested"|capfirst }}</td>
<td>{% if mailbox.provisioning.state == 'configured' %}
<a href="{% url 'panel:mailbox_credentials' mailbox.pk %}">Credentials</a>
{% if roundcube_enabled %}<form class="inline-form" method="post" action="{% url 'panel:roundcube_launch' mailbox.pk %}">{% csrf_token %}<button class="button secondary" type="submit">Open webmail</button></form>{% endif %}
{% endif %}</td></tr>
{% empty %}<tr><td colspan="4">No mailboxes on this domain.</td></tr>{% endfor %}</tbody>
</table></div>
{% if mail_domain %}<p class="section-text"><a href="{% url 'panel:mail_dns_check' mail_domain.pk %}">Check email DNS</a></p>{% endif %}
</section>
{% endif %}
{% 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 %}
<header class="section-heading"><h2>Forwarders and catch-all</h2>{% if can_edit_routing %}<a class="button primary" href="{% url 'panel:mail_routing' mail_domain.pk %}">Manage forwarders</a>{% endif %}</header>
{% if not can_edit_routing %}<p class="section-text">Mail forwarding is unavailable on this installation.</p>{% endif %}
{% elif can_edit_mailbox %}
<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>
{% for mailbox in mailboxes %}<li>{% if page == 'spam' %}<a href="{% url 'panel:mail_spam' mailbox.pk %}">{{ mailbox.spec.address }}</a>
{% else %}<a href="{% url 'panel:mail_vacation' mailbox.pk %}">{{ mailbox.spec.address }}</a>{% endif %}</li>
{% empty %}<li>No mailboxes for this domain.</li>{% endfor %}
</ul>
{% endif %}
{% else %}<p class="section-text">Mailbox delivery rules are unavailable on this installation.</p>{% endif %}
</section>
{% else %}<p class="empty">This domain has no managed email accounts.</p>{% endif %}
{% endblock %}
@@ -0,0 +1,27 @@
{% extends "hosting/base.html" %}
{% block title %}HTTP Settings · Coulobre Panel{% endblock %}
{% block content %}
<header class="page-heading"><h1>HTTP Settings</h1></header>
{% for message in messages %}<p class="notice" role="status">{{ message }}</p>{% endfor %}
<nav class="account-navigation" aria-label="HTTP settings">
<a href="{% url 'panel:http_defaults' 'apache' %}"{% if target == 'apache' %} aria-current="page"{% endif %}>Apache</a>
<a href="{% url 'panel:http_defaults' 'php' %}"{% if target == 'php' %} aria-current="page"{% endif %}>PHP-FPM</a>
</nav>
<section class="surface editor-surface">
{% if target == 'apache' %}<p>Set server-wide Apache defaults. Review the effect on the panel and hosted sites before applying them.</p>
{% else %}<p>Set PHP defaults for installed PHP-FPM versions. Website-specific settings still apply.</p>{% endif %}
<form method="post" class="editor">
{% csrf_token %}{{ form.as_div }}
{% if preview %}<section aria-label="Template preview"><h2>Template preview</h2><pre>{{ preview }}</pre></section>{% endif %}
<div class="form-actions">
<button type="submit" class="button secondary" name="action" value="preview">Preview</button>
{% if preview and available %}<button type="submit" class="button primary" name="action" value="apply">Apply template</button>{% endif %}
</div>
</form>
{% if not available %}<p>Enable the operator worker to apply a template.</p>{% endif %}
</section>
<section class="surface"><header class="section-heading"><h2>Change history</h2></header>
<ul class="workspace-list">{% for job in jobs %}<li>{{ job.requested_at|date:"j M Y H:i" }} UTC · {{ job.state|capfirst }}{% if job.problem %}<p>{{ job.problem }}</p>{% endif %}</li>
{% empty %}<li>No template changes yet.</li>{% endfor %}</ul>
</section>
{% endblock %}
@@ -30,7 +30,8 @@
<a class="record-link" href="{% url 'panel:independent_website_files' account.pk website.pk %}">Files</a>
{% endif %}
{% for action in actions %}
<a class="record-link" href="{% url 'panel:independent_website_operation' account.pk website.pk action.value %}">{{ action.label }}</a>
{% if action.value == 'settings' %}<a class="record-link" href="{% url 'panel:independent_php_settings' account.pk website.pk %}">{{ action.label }}</a>
{% else %}<a class="record-link" href="{% url 'panel:independent_website_operation' account.pk website.pk action.value %}">{{ action.label }}</a>{% endif %}
{% endfor %}
{% if is_operator and perms.hosting.view_hostingaccount %}
<a class="record-link" href="{% url 'panel:independent_website_manifest' account.pk website.pk %}">Download manifest</a>
@@ -24,8 +24,10 @@
<h2>Last confirmed routes</h2>
{% include "hosting/mail_routes.html" with routes=applied %}
{% endif %}
{% if not routing %}
<p>Messages still arrive in this mailbox. The mail server suppresses repeat replies to the same sender for seven days.</p>
{% if spam_editor %}
<p>These rules apply at mailbox delivery. The mail node continues to enforce its server-wide filtering policy.</p>
{% elif not routing %}
<p>Leave the start and end times blank to reply whenever the settings are enabled.</p>
{% endif %}
<form method="post" class="editor">
{% csrf_token %}
@@ -5,7 +5,7 @@
<header class="page-heading">
<div>
<h1>{% if auto_provision %}Add{% else %}Request{% endif %} mailbox</h1>
<p class="heading-meta domain">{{ account.primary_domain }}</p>
<p class="heading-meta domain">{{ mail_domain_name|default:account.primary_domain }}</p>
</div>
</header>
<section class="surface editor-surface">
@@ -0,0 +1,34 @@
{% extends "hosting/base.html" %}
{% block title %}Account Backup &amp; Restore · Coulobre Panel{% endblock %}
{% block content %}
<header class="page-heading"><h1>Account Backup &amp; Restore</h1></header>
{% for message in messages %}<p class="notice" role="status">{{ message }}</p>{% endfor %}
<nav class="account-navigation" aria-label="Backup workflows">
<a href="{% url 'panel:operator_backups' %}" aria-current="page">Hosting accounts</a>
<a href="{% url 'panel:system_backup' %}">System Backup</a>
</nav>
<section class="surface">
<form method="get" class="toolbar form-actions">
<label for="manager">Manager</label><select id="manager" name="manager"><option value="">All hosting accounts</option>
{% for manager in managers %}<option value="{{ manager.pk }}"{% if manager.pk|stringformat:"s" == selected_manager %} selected{% endif %}>{{ manager }}</option>{% endfor %}
</select><button class="button secondary" type="submit">Filter accounts</button>
</form>
<div class="table-scroll"><table>
<thead><tr><th scope="col">Hosting account</th><th scope="col">Manager</th><th scope="col">Latest backup</th><th scope="col">Schedule</th><th scope="col">Actions</th></tr></thead>
<tbody>{% for account in accounts %}
<tr><th scope="row"><a href="{{ account.get_absolute_url }}">{{ account.primary_domain }}</a></th><td>{{ account.reseller|default:"Unassigned" }}</td>
<td>{% if account.last_backup %}{{ account.last_backup|date:"j M Y H:i" }} UTC · {% if account.last_problem %}Failed{% elif account.last_completed %}Completed{% else %}Queued{% endif %}{% else %}None{% endif %}</td>
<td>{% if account.backup_schedule.enabled %}{{ account.backup_schedule.get_frequency_display }} at {{ account.backup_schedule.time|time:"H:i" }} UTC{% else %}Disabled{% endif %}</td>
<td><a href="{% url 'panel:account_backup_archives' account.pk %}">Archives and restores</a>{% if enabled %} · <a href="{% url 'panel:account_backup_schedule' account.pk %}">Schedule</a>{% endif %}</td>
</tr>
{% empty %}<tr><td colspan="5">No accounts available.</td></tr>{% endfor %}</tbody>
</table></div>
{% include "hosting/pagination.html" %}
</section>
{% if enabled %}
<section class="surface editor-surface">
<h2>Back up a manager's hosting accounts</h2>
<form class="editor" method="post">{% csrf_token %}{{ form.as_div }}<button class="button primary" type="submit">Apply to hosting accounts</button></form>
</section>
{% endif %}
{% endblock %}
@@ -15,6 +15,18 @@
</dl>
<a href="{% url 'panel:service_health' %}">Service health</a>
</section>
<section class="surface">
<header class="section-heading"><div><h2>Local TLS checks</h2>{% if tls_job %}<p>{{ tls_job.state|capfirst }} · {{ tls_job.requested_at|date:"j M Y H:i" }} UTC</p>{% endif %}</div>
{% if tls_available %}<form method="post">{% csrf_token %}<button type="submit" class="button secondary"{% if tls_job and not tls_job.finished_at %} disabled{% endif %}>Check TLS</button></form>{% endif %}
</header>
{% if tls_job.problem %}<p class="notice">{{ tls_job.problem }}</p>{% endif %}
{% if tls_result %}<div class="table-scroll"><table>
<thead><tr><th scope="col">Endpoint</th><th scope="col">Certificate</th><th scope="col">Issuer</th><th scope="col">Expiry</th></tr></thead>
<tbody>{% for endpoint in tls_result.result.endpoints %}<tr><th scope="row">{{ endpoint.service }} · {{ endpoint.port }}</th>
<td>{% if endpoint.status == 'presented' %}{{ endpoint.name_matches|yesno:"Hostname matches,Hostname mismatch" }}{% else %}Unavailable on loopback{% endif %}</td>
<td>{{ endpoint.issuer|default:"Unavailable" }}</td><td>{{ endpoint.expires|default:"Unavailable" }}</td></tr>{% endfor %}</tbody>
</table></div>{% endif %}
</section>
{% else %}
<section class="surface"><div class="table-scroll"><table>
<thead><tr><th scope="col">Website</th><th scope="col">Account</th><th scope="col">Last known issuer</th><th scope="col">Expiry</th></tr></thead>
@@ -4,6 +4,9 @@
<a class="back-link" href="{% url 'panel:resellers' %}">← Managers</a>
<header class="page-heading">
<h1>{{ reseller }}</h1>
{% if perms.hosting.add_hostingaccount and perms.hosting.view_hostingaccount %}
<a class="button secondary" href="{% url 'panel:account_create' %}?manager={{ reseller.pk }}">Add hosting account</a>
{% endif %}
{% if perms.hosting.change_reseller %}
<a class="button secondary" href="{% url 'panel:manage_invitation' 'manager' reseller.pk %}">Contact and invitation</a>
<a class="button secondary" href="{% url 'panel:reseller_edit' reseller.pk %}">Edit manager</a>
@@ -11,7 +14,6 @@
</header>
<dl class="details surface">
<div><dt>Panel sign-in</dt><dd>{{ reseller.user.is_active|yesno:"Active,Suspended" }}</dd></div>
<div><dt>Database and mailbox management</dt><dd>{{ reseller.manage_resources|yesno:"Allowed,Operator only" }}</dd></div>
<div><dt>Accounts allocated</dt><dd>{{ account_count }} of {{ reseller.account_limit }}</dd></div>
{% if perms.hosting.view_hostingplan %}
<div>
@@ -5,12 +5,12 @@
<header class="page-heading">
<div>
<h1>Change PHP settings</h1>
<p class="heading-meta domain">{{ account.primary_domain }}</p>
<p class="heading-meta domain">{{ site_domain|default:account.primary_domain }}</p>
</div>
</header>
<section class="surface editor-surface">
<form method="post" class="editor">
<p>Blank fields use the web node defaults.</p>
<p>{% if is_customer %}Blank fields use the hosting plan defaults.{% else %}Blank fields use the web node defaults.{% endif %}</p>
{% csrf_token %}
{{ form.as_div }}
<div class="form-actions">
@@ -0,0 +1,30 @@
{% extends "hosting/base.html" %}
{% block title %}System Backup · Coulobre Panel{% endblock %}
{% block content %}
<header class="page-heading"><h1>System Backup</h1></header>
{% for message in messages %}<p class="notice" role="status">{{ message }}</p>{% endfor %}
{% if available %}
<section class="surface editor-surface">
<h2>Run a backup</h2>
<p>The archive contains local service configuration, MariaDB, and hosted files and mail. Retrieve it on the server using an administrator account.</p>
<form method="post" class="editor">{% csrf_token %}
<label><input type="checkbox" name="confirm" value="yes" required> Create a system recovery archive</label>
<button class="button primary" type="submit" name="action" value="create">Queue backup</button>
</form>
</section>
<section class="surface editor-surface">
<h2>Schedule</h2>
<form method="post" class="editor">{% csrf_token %}{{ form.as_div }}
<button class="button secondary" name="action" value="schedule" type="submit">Save schedule</button>
</form>
</section>
{% else %}<p class="notice">Enable system backups and the local operator worker on this server.</p>{% endif %}
<section class="surface"><header class="section-heading"><h2>Backup history</h2></header>
<ul class="workspace-list">{% for job in jobs %}
<li>{{ job.requested_at|date:"j M Y H:i" }} UTC · {{ job.actor|default:"Scheduled" }} · {{ job.state|capfirst }}
{% if job.problem %}<p>{{ job.problem }}</p>{% endif %}
{% if job.report.archive %}<p><code>{{ job.report.archive }}</code> · {{ job.report.bytes|filesizeformat }}</p>{% endif %}
</li>
{% empty %}<li>No system backups have been run.</li>{% endfor %}</ul>
</section>
{% endblock %}
@@ -6,8 +6,8 @@
{% 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>
<tbody>{% for account, usage in rows %}
<tr><th scope="row"><a href="{{ account.get_absolute_url }}">{{ account.primary_domain }}</a></th><td>{% if usage.storage is not None %}{{ usage.storage|filesizeformat }}{% else %}Unavailable{% endif %}</td><td>{% if usage.traffic is not None %}{{ usage.traffic|filesizeformat }}{% else %}Unavailable{% endif %}</td><td>{{ usage.domains }}</td><td>{{ usage.databases|default_if_none:"Unavailable" }}</td><td>{{ usage.mailboxes|default_if_none:"Unavailable" }}</td></tr>
{% empty %}<tr><td colspan="6">No hosting accounts are available.</td></tr>{% endfor %}</tbody>
</table></div>
{% elif section == 'tasks' %}
@@ -19,7 +19,7 @@
</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>
{% for account, usage 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 %}
@@ -2,7 +2,7 @@
<details class="sidebar-group"{% if title == open_workspace_group or not open_workspace_group and forloop.first %} open{% endif %}>
<summary>{{ title }}</summary>
{% for href, label in entries %}
<a href="{{ href }}"{% if request.path == href %} aria-current="page"{% endif %}>{{ label }}</a>
<a href="{{ href }}"{% if active_navigation_link == href %} aria-current="page"{% endif %}>{{ label }}</a>
{% endfor %}
</details>
{% endfor %}
@@ -106,6 +106,8 @@ class DatabaseProvisioningTests(TestCase):
)
self.client.force_login(requester)
url = reverse("panel:database_create", args=[self.account.pk])
self.assertEqual(self.client.get(url).status_code, 403)
HostingAccount.objects.filter(pk=self.account.pk).update(customer=None)
self.assertContains(self.client.get(url), "Request database")
self.assertRedirects(
self.client.post(url, {"suffix": "request"}), self.detail
+2 -2
View File
@@ -275,7 +275,7 @@ class ResellerAccountCreationTests(TestCase):
"hosting_plan": self.allowed.pk,
},
)
self.assertContains(response, "Your reseller access has changed.")
self.assertContains(response, "Your manager access has changed.")
self.assertEqual(self.reseller.hostingaccount_set.count(), 1)
def test_operator_can_configure_limit_and_allowed_plans(self):
@@ -352,7 +352,7 @@ class ResellerManagementTests(TestCase):
self.client.get(self.index, {"q": "new-"}), "0 of 4"
)
self.assertContains(
self.client.get(reseller.get_absolute_url()), "Created reseller"
self.client.get(reseller.get_absolute_url()), "Created manager"
)
audit = reseller.audit_events.get()
self.assertEqual(audit.actor_username, "operator")
@@ -269,6 +269,8 @@ class WebsiteFilePanelTests(TestCase):
self.staff.user_permissions.add(
Permission.objects.get(codename="manage_website_files")
)
self.assertEqual(self.client.get(self.primary_url).status_code, 403)
HostingAccount.objects.filter(pk=self.account.pk).update(customer=None)
with patch(
"coulobre.hosting.website_file_views.request_website_files",
return_value={"entries": [], "after": ""},
@@ -240,6 +240,8 @@ class WebsiteJobWorkflowTests(TestCase):
self.operator.user_permissions.add(
Permission.objects.get(codename="manage_website_jobs")
)
self.assertEqual(self.client.get(self.jobs_url).status_code, 403)
HostingAccount.objects.filter(pk=self.account.pk).update(customer=None)
self.assertEqual(self.client.get(self.jobs_url).status_code, 200)
with self.settings(WEBSITE_JOBS=False):
self.assertEqual(self.client.get(self.jobs_url).status_code, 404)
+44 -2
View File
@@ -31,6 +31,7 @@ from .database_login_views import (
)
from .dns_defaults_views import DnsDefaultsView
from .dns_replica_views import DnsReplicaView
from .dns_topology_views import DnsTopologyView
from .domain_services import domain_workspace
from .folder_sftp_views import folder_sftp_users
from .health_views import ServiceHealthView
@@ -38,14 +39,24 @@ from .independent_website_views import (
IndependentWebsiteCreate,
IndependentWebsiteManifest,
IndependentWebsiteOperation,
IndependentWebsitePhpSettings,
)
from .installation_views import FeatureConfigurationView, InstallationView
from .invitations import AcceptInvitation, ManageInvitation
from .mail_delivery_views import MailDeliveryView
from .mail_dns_views import MailDnsCheckView, RequestMailDnsSetup
from .mail_policy_views import MailRoutingEditor, MailVacationEditor
from .mail_policy_views import (
MailRoutingEditor,
MailSpamEditor,
MailVacationEditor,
)
from .mail_queue_views import MailQueueIndex, MailQueueView, mail_queue_action
from .operator_tools import ConnectedNodesView, OperatorToolsView
from .operator_backups import OperatorBackupsView
from .operator_tools import (
ConnectedNodesView,
HttpDefaultsView,
OperatorToolsView,
)
from .panel_content import (
AnnouncementView,
DirectAdminGuideView,
@@ -64,8 +75,10 @@ from .password_reset import (
from .phpmyadmin import PhpMyAdminLaunch, redeem_phpmyadmin
from .redirect_views import customer_redirects
from .reseller_onboarding_views import (
ManagerHostingPlanView,
ResellerCustomerCreate,
ResellerCustomerLink,
claim_own_customer_hosting,
)
from .reseller_profiles import (
ResellerProfileCreate,
@@ -86,6 +99,7 @@ from .sign_in import (
PanelLoginView,
VerifyFactorView,
)
from .system_backup_views import SystemBackupView
from .update_views import UpdateView
from .website_file_views import WebsiteFilesView
from .website_job_views import WebsiteJobEditor, WebsiteJobList
@@ -125,6 +139,31 @@ urlpatterns = [
folder_sftp_users,
name="folder_sftp_users",
),
path(
"accounts/<int:pk>/claim/",
claim_own_customer_hosting,
name="claim_customer_hosting",
),
path(
"accounts/<int:pk>/hosting-plan/",
ManagerHostingPlanView.as_view(),
name="manager_assign_plan",
),
path("backups/", OperatorBackupsView.as_view(), name="operator_backups"),
path("backups/system/", SystemBackupView.as_view(), name="system_backup"),
path(
"hosting/<int:pk>/sites/<int:site_pk>/php-settings/",
IndependentWebsitePhpSettings.as_view(),
name="independent_php_settings",
),
path(
"dns-settings/routing/", DnsTopologyView.as_view(), name="dns_topology"
),
path(
"http-settings/<slug:target>/",
HttpDefaultsView.as_view(),
name="http_defaults",
),
path("ssl/", operator_certificates, name="operator_certificates"),
path(
"hosting/<int:pk>/certificates/",
@@ -136,6 +175,9 @@ urlpatterns = [
customer_redirects,
name="customer_redirects",
),
path(
"mailboxes/<int:pk>/spam/", MailSpamEditor.as_view(), name="mail_spam"
),
path("mail-delivery/", MailDeliveryView.as_view(), name="mail_delivery"),
path("mail-queue/", MailQueueIndex.as_view(), name="mail_queue_index"),
path(
+74 -5
View File
@@ -41,6 +41,7 @@ from .access import (
customer_for_user,
is_tenant,
manages_account,
owns_customer_operations,
reseller_for_user,
)
from .account_backup_forms import (
@@ -57,6 +58,7 @@ from .account_backups import (
queue_account_backup,
save_backup_schedule,
)
from .account_metrics import customer_metrics
from .account_setup import default_dns_zone, setup_new_account, website_records
from .backup_restores import (
RestoreKind,
@@ -529,6 +531,14 @@ class AccountCreate(PermissionRequiredMixin, AccountEditor, CreateView):
and self.request.user.has_perm(VIEW_CUSTOMERS)
):
initial["customer"] = int(customer)
manager = self.request.GET.get("manager", "")
if (
manager.isascii()
and manager.isdecimal()
and len(manager) <= 18
and (self.request.user.has_perm(VIEW_RESELLERS))
):
initial["reseller"] = int(manager)
return initial
def form_valid(self, form):
@@ -608,6 +618,9 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
and user.has_perm(CHANGE_ACCOUNTS)
and bool(missing_account_setup(self.object, user))
)
context["own_customer_operations"] = owns_customer_operations(
user, self.object
)
context["show_website_usage"] = settings.WEBSITE_USAGE and (
tenant or user.has_perm("hosting.view_websiteusage")
)
@@ -628,6 +641,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
manage_files = (
not self.object.services_suspended
and can_manage_website_files(self.request)
and owns_customer_operations(user, self.object)
)
context["manage_website_files"] = manage_files
context["manage_website_jobs"] = can_manage_website_jobs(
@@ -812,6 +826,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
context["manage_sftp"] = (
settings.LOCAL_WEB_SFTP
and can_manage_sftp(user)
and owns_customer_operations(user, self.object)
and (site_active or hasattr(self.object, "sftp"))
)
if reseller is not None or (
@@ -1067,9 +1082,10 @@ class SitePhpSettingsEdit(PermissionRequiredMixin, FormView):
def has_permission(self):
user = self.request.user
return customer_for_user(user) is not None or (
allowed = customer_for_user(user) is not None or (
reseller_for_user(user) is None and super().has_permission()
)
return allowed and owns_customer_operations(user, self.account)
@cached_property
def account(self):
@@ -1123,7 +1139,9 @@ class SitePhpVersionEdit(PermissionRequiredMixin, FormView):
return super().dispatch(request, *args, **kwargs)
def has_permission(self):
return can_change_php_version(self.request)
return can_change_php_version(
self.request
) and owns_customer_operations(self.request.user, self.account)
@cached_property
def account(self):
@@ -1773,7 +1791,9 @@ class SiteSFTPKeys(PermissionRequiredMixin, FormView):
return super().dispatch(request, *args, **kwargs)
def has_permission(self):
return can_manage_sftp(self.request.user)
return can_manage_sftp(self.request.user) and owns_customer_operations(
self.request.user, self.account
)
@cached_property
def account(self):
@@ -1863,12 +1883,21 @@ class CustomerList(TenantScopeMixin, PermissionRequiredMixin, ListView):
return queryset
def get_context_data(self, **kwargs):
return super().get_context_data(
context = super().get_context_data(
search=self.search,
can_impersonate=can_impersonate_customer(self.request.user),
can_start_support=can_start_writable_support(self.request.user),
**kwargs,
)
manager = reseller_for_user(self.request.user)
if manager:
measurements = customer_metrics(
[customer.pk for customer in context["customers"]],
manager=manager,
)
for customer in context["customers"]:
customer.workspace_metrics = measurements.get(customer.pk)
return context
class CustomerCreate(OperatorOnlyMixin, PermissionRequiredMixin, FormView):
@@ -1985,7 +2014,10 @@ class ResourceRequestCreate(PermissionRequiredMixin, CreateView):
def has_permission(self):
if reseller_for_user(self.request.user) is not None:
return False
return self.customer is not None or super().has_permission()
allowed = self.customer is not None or super().has_permission()
return allowed and owns_customer_operations(
self.request.user, self.account
)
@cached_property
def account(self):
@@ -2395,6 +2427,43 @@ class MailboxCreate(ResourceRequestCreate):
provisioning_permissions = PROVISION_MAILBOX
create_resource = staticmethod(create_mailbox_request)
@cached_property
def mail_domain_name(self):
domain = self.request.GET.get("domain")
if domain is None:
return None
if self.customer is None or getattr(
self.request, "impersonation", None
):
raise Http404
from .domain_services import allowed_domains
if domain not in allowed_domains(self.account):
raise Http404
return domain
def get_context_data(self, **kwargs):
return super().get_context_data(
mail_domain_name=self.mail_domain_name, **kwargs
)
def create_request(self, account_id, **values):
return super().create_request(
account_id, mail_domain_name=self.mail_domain_name, **values
)
def form_valid(self, form):
response = super().form_valid(form)
if response.status_code == 302 and self.mail_domain_name is not None:
return redirect(
reverse(
"panel:domain_workspace",
args=[self.account.pk, "email"],
query={"domain": self.mail_domain_name},
)
)
return response
def get_form(self, form_class=None):
form = super().get_form(form_class)
form.fields["local_part"].help_text = INVALID_LOCAL_PART
+8 -2
View File
@@ -19,7 +19,11 @@ from coulobre.website_files import (
directory_parts,
)
from .access import TenantScopeMixin, can_manage_hosting
from .access import (
TenantScopeMixin,
can_manage_hosting,
owns_customer_operations,
)
from .independent_websites import active_websites
from .installation_features import panel_feature_allowed
from .models import HostingAccount
@@ -80,7 +84,9 @@ class WebsiteFilesView(
return super().dispatch(request, *args, **kwargs)
def has_permission(self):
return can_manage_website_files(self.request)
return can_manage_website_files(
self.request
) and owns_customer_operations(self.request.user, self.account)
@cached_property
def account(self):
+8 -2
View File
@@ -15,7 +15,11 @@ from django.views.generic.detail import SingleObjectMixin
from coulobre.website_job import MAX_JOB_COMMAND_LENGTH, validate_command
from .access import TenantScopeMixin, can_manage_hosting
from .access import (
TenantScopeMixin,
can_manage_hosting,
owns_customer_operations,
)
from .independent_websites import check_actor
from .installation_features import panel_feature_allowed
from .models import HostingAccount
@@ -109,7 +113,9 @@ class WebsiteJobAccountView(
return super().dispatch(request, *args, **kwargs)
def has_permission(self):
return can_manage_website_jobs(self.request)
return can_manage_website_jobs(
self.request
) and owns_customer_operations(self.request.user, self.account)
@cached_property
def account(self):
+93 -36
View File
@@ -1,7 +1,6 @@
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
@@ -10,6 +9,7 @@ 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 .account_metrics import account_metrics
from .installation_features import panel_feature_allowed
from .models import HostingAccount, WebsiteScheduledJob
@@ -28,6 +28,7 @@ CUSTOMER_PAGES = {
"email": ("Email Accounts", "account", "email"),
"forwarders": ("Forwarders", "account", "email"),
"replies": ("Automatic replies", "account", "email"),
"spam": ("Spam protection", "account", "email"),
"backups": ("Backup & Restore", "customer_backups", ""),
"tasks": ("Scheduled Tasks", "website_jobs", ""),
}
@@ -38,6 +39,66 @@ SYSTEM_PAGES = {
}
CUSTOMER_NAV_ROUTES = {
"customer_certificates": "certificates",
"customer_redirects": "redirects",
"folder_sftp_users": "sftp",
"sftp_keys": "sftp",
"customer_databases": "databases",
"database_logins": "databases",
"database_create": "databases",
"database_credentials": "databases",
"database_login_credentials": "databases",
"customer_backups": "backups",
"customer_restore": "backups",
"website_jobs": "tasks",
"website_job_create": "tasks",
"website_job_edit": "tasks",
"site_php_settings": "php",
"independent_php_settings": "php",
"website_files": "files",
"independent_website_files": "files",
"mailbox_create": "email",
"mailbox_credentials": "email",
"mail_routing": "forwarders",
"mail_vacation": "replies",
"mail_spam": "spam",
}
WORKSPACE_PARENT_ROUTES = {
"dns_topology": ("dns_defaults", ()),
"operator_settings": ("operator_settings", ("general",)),
"http_defaults": ("http_defaults", ("apache",)),
"server_updates": ("updates", ()),
"mail_queue": ("mail_queue_index", ()),
"reseller": ("resellers", ()),
"reseller_edit": ("resellers", ()),
"hosting_plan_create": ("hosting_plans", ()),
"hosting_plan_edit": ("hosting_plans", ()),
"manager_assign_plan": ("manager_packages", ()),
"account": ("accounts", ()),
}
def active_navigation(request, *, customer):
match = request.resolver_match
if match is None:
return request.path
name = match.url_name
if customer:
page = (
match.kwargs.get("page")
if name == "domain_workspace"
else CUSTOMER_NAV_ROUTES.get(name)
)
if page:
return reverse("panel:customer_workspace", args=[page])
if target := WORKSPACE_PARENT_ROUTES.get(name):
route, arguments = target
return reverse(f"panel:{route}", args=arguments)
return request.path
def workspace_accounts(user):
accounts = HostingAccount.objects.filter(retired_at__isnull=True)
customer = customer_for_user(user)
@@ -93,7 +154,16 @@ def customer_workspace(request, page):
return redirect("panel:accounts")
if page == "overview":
return redirect(account)
if page in {"domains", "dns", "php", "files", "forwarders", "replies"}:
if page in {
"domains",
"dns",
"php",
"files",
"email",
"forwarders",
"replies",
"spam",
}:
return redirect("panel:domain_workspace", pk=account.pk, page=page)
_, destination, fragment = pages[page]
return redirect(
@@ -125,43 +195,27 @@ 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
)
pagination = Paginator(accounts, 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,
)
operator = (
customer_for_user(request.user) is None
and reseller_for_user(request.user) is None
)
measures = (
account_metrics(
page_obj.object_list,
databases=not operator
or request.user.has_perm("hosting.view_hostingdatabase"),
mailboxes=not operator
or request.user.has_perm("hosting.view_hostingmailbox"),
)
if page == "statistics"
else {}
)
rows = [(account, measures.get(account.pk, {})) for account in page_obj]
tasks = ()
task_accounts = set(account.pk for account, _, _ in rows)
task_accounts = {account.pk for account, _ in rows}
if page == "tasks":
tasks = (
WebsiteScheduledJob.objects.filter(account_id__in=task_accounts)
@@ -223,7 +277,7 @@ def groups_for(request, *, customer, manager):
),
(
"Email Manager",
hosted("email", "forwarders", "replies")
hosted("email", "forwarders", "replies", "spam")
+ (
[link("mail_delivery", "Mail delivery")]
if panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING")
@@ -286,6 +340,7 @@ def groups_for(request, *, customer, manager):
(
link("operator_settings", "Operator Settings", "general"),
link("dns_defaults", "DNS Settings"),
link("http_defaults", "HTTP Settings", "apache"),
)
)
if user.is_superuser:
@@ -295,6 +350,8 @@ def groups_for(request, *, customer, manager):
link("announcements", "Message"),
link("directadmin_guide", "Import"),
link("operator_certificates", "SSL Overview"),
link("operator_backups", "Backup & Restore"),
link("system_backup", "System Backup"),
)
)
if user.is_superuser:
+150
View File
@@ -0,0 +1,150 @@
import os
from dataclasses import dataclass
from pathlib import Path
from .node_files import (
locked_root_directory,
read_root_file,
replace_configuration,
require_root_directory,
)
from .php_runtime import PhpRuntime, installed_php_versions
OPERATION = "http-defaults"
APACHE_DEFAULTS = Path(
"/etc/apache2/conf-enabled/coulobre-hosting-limits.conf"
)
HEADER = "# Managed by Coulobre Panel\n"
CONTROLS = {
"apache": {
"keep_alive": ("Keep-alive", 0, 1, 1),
"keep_alive_timeout": ("Keep-alive timeout (seconds)", 1, 30, 5),
"request_timeout": ("Request timeout (seconds)", 10, 300, 60),
"request_body_mib": ("Request body limit (MiB)", 64, 2048, 128),
},
"php": {
"memory_mib": ("Memory limit (MiB)", 32, 2048, 128),
"upload_mib": ("Upload limit (MiB)", 1, 512, 16),
"execution_seconds": ("Execution limit (seconds)", 15, 600, 30),
},
}
@dataclass(frozen=True)
class HttpDefaultsRequest:
target: str
values: dict
def __post_init__(self):
if not isinstance(self.target, str) or self.target not in CONTROLS:
raise ValueError("Choose Apache or PHP-FPM settings.")
controls = CONTROLS[self.target]
if (
not isinstance(self.values, dict)
or self.values.keys() != controls.keys()
):
raise ValueError("Provide all of the supported template settings.")
for key, (label, minimum, maximum, _) in controls.items():
value = self.values[key]
if type(value) is not int or not minimum <= value <= maximum:
raise ValueError(
f"{label} must be between {minimum} and {maximum}."
)
if (
self.target == "php"
and self.values["upload_mib"] >= self.values["memory_mib"]
):
raise ValueError(
"Set the upload limit below the PHP memory limit."
)
def manifest(self):
return {
"operation": OPERATION,
"target": self.target,
"values": self.values,
}
@classmethod
def from_manifest(cls, data):
if data.keys() != {"operation", "target", "values"}:
raise ValueError("Expected HTTP template settings.")
return cls(data["target"], data["values"])
def render(self):
data = self.values
if self.target == "apache":
enabled = "On" if data["keep_alive"] else "Off"
body_limit = data["request_body_mib"] * 1024 * 1024
return (
HEADER
+ f"KeepAlive {enabled}\n"
+ f"KeepAliveTimeout {data['keep_alive_timeout']}\n"
+ f"Timeout {data['request_timeout']}\n"
+ f"LimitRequestBody {body_limit}\n"
)
upload = data["upload_mib"]
return (
"; Managed by Coulobre Panel\n"
f"memory_limit = {data['memory_mib']}M\n"
f"upload_max_filesize = {upload}M\n"
f"post_max_size = {upload + 1}M\n"
f"max_execution_time = {data['execution_seconds']}\n"
)
def targets_for(request):
if request.target == "apache":
return [
(
APACHE_DEFAULTS,
("/usr/sbin/apache2ctl", "configtest"),
"apache2.service",
)
]
targets = []
for series in installed_php_versions():
php = PhpRuntime(series)
ini = php.pools.parent / "conf.d" / "98-coulobre-defaults.ini"
targets.append((ini, (php.binary, "--test"), f"{php.service}.service"))
if not targets:
raise ValueError("No managed PHP-FPM series is installed.")
return targets
def apply_http_defaults(request):
from .operator_node import STATE, command
if os.geteuid() != 0:
raise ValueError("Apply HTTP templates as root on the web server.")
with locked_root_directory(STATE):
originals = {}
targets = targets_for(request)
content = request.render()
for path, _, _ in targets:
require_root_directory(path.parent)
originals[path] = (
read_root_file(path) if os.path.lexists(path) else None
)
written = []
reload_attempts = []
try:
for path, _, _ in targets:
replace_configuration(path, content)
written.append(path)
for _, check, _ in targets:
command(*check)
for _, _, service in targets:
reload_attempts.append(service)
command("/usr/bin/systemctl", "reload", service)
command("/usr/bin/systemctl", "is-active", "--quiet", service)
except (OSError, ValueError, KeyboardInterrupt):
for path in reversed(written):
if originals[path] is None:
path.unlink(missing_ok=True)
else:
replace_configuration(path, originals[path])
for service in reload_attempts:
command("/usr/bin/systemctl", "reload", service)
raise
return {"services": [service for _, _, service in targets], "active": True}
+3
View File
@@ -55,6 +55,9 @@ MANAGED_UNITS = frozenset(
"coulobre-mail-credentials.socket",
"coulobre-mailbox-provisioner.service",
"coulobre-offsite-worker.service",
"coulobre-operator-apply.socket",
"coulobre-operator-worker.service",
"coulobre-folder-sftp.socket",
"coulobre-provisioner.service",
"coulobre-service-credentials.socket",
"coulobre-sftp-apply.socket",
+30 -2
View File
@@ -42,6 +42,34 @@ def vacation_script(spec):
)
def mailbox_delivery_script(spec):
if not spec.move_spam and not spec.junk_senders:
return vacation_script(spec)
required = ["fileinto", "mailbox", "envelope"]
tests = []
if spec.move_spam:
tests.append('header :is ["X-Spam", "X-Spam-Flag"] "YES"')
if spec.junk_senders:
senders = ", ".join(
sieve_string(sender) for sender in spec.junk_senders
)
tests.append(f'envelope :is "from" [{senders}]')
reply = ""
if spec.enabled:
required.append("vacation")
if spec.starts_at or spec.ends_at:
required.extend(("date", "relational"))
reply = vacation_script(spec).split("\n", maxsplit=1)[1]
extensions = ", ".join(sieve_string(item) for item in required)
return (
f"require [{extensions}];\n"
f"if anyof ({', '.join(tests)}) {{\n"
' fileinto :create "Junk";\n'
" stop;\n"
"}\n" + reply
)
def script_path(mailbox):
return VACATION_ROOT / mailbox.domain / f"{mailbox.local_part}.sieve"
@@ -66,7 +94,7 @@ def apply_vacation(spec):
or os.path.lexists(mail.retirement_guard(record.mailbox))
):
raise ValueError("The managed mailbox is unavailable.")
if not spec.enabled:
if not spec.enabled and not spec.move_spam and not spec.junk_senders:
remove_vacation(spec.mailbox)
return
config = mail.run("doveconf", "-f", "protocol=lmtp", "-n")
@@ -78,7 +106,7 @@ def apply_vacation(spec):
target = script_path(spec.mailbox)
for directory in (VACATION_ROOT, target.parent):
require_root_directory(directory, create_mode=0o751)
content = vacation_script(spec)
content = mailbox_delivery_script(spec)
if (
os.path.lexists(target)
and read_root_file(target, mode=0o640) == content
+33 -4
View File
@@ -10,6 +10,7 @@ from .mail_node import LOCAL_PART_MAX_LENGTH, MailboxSpec
MAIL_POLICY_LIMIT = 64 * 1024
DEFAULT_REPEAT_DAYS = 7
MAX_REPEAT_DAYS = 60
MAX_JUNK_SENDERS = 20
MAX_ALIASES = 100
MAX_DESTINATIONS = 10
OPERATIONS = ("set_mail_routing", "set_mail_vacation")
@@ -125,8 +126,23 @@ class MailVacation(MailPolicy):
starts_at: str = ""
ends_at: str = ""
repeat_days: int = DEFAULT_REPEAT_DAYS
move_spam: bool = False
junk_senders: tuple[str, ...] = ()
def __post_init__(self):
if (
type(self.move_spam) is not bool
or not isinstance(self.junk_senders, (list, tuple))
or len(self.junk_senders) > MAX_JUNK_SENDERS
):
raise ValueError("Choose up to 20 senders for the mailbox filter.")
senders = tuple(
dict.fromkeys(
mail_address(sender, self.mailbox.domain).lower()
for sender in self.junk_senders
)
)
object.__setattr__(self, "junk_senders", senders)
if (
type(self.repeat_days) is not int
or not 1 <= self.repeat_days <= MAX_REPEAT_DAYS
@@ -167,7 +183,7 @@ class MailVacation(MailPolicy):
raise ValueError("The end time must be after the start time.")
def manifest(self):
return {
payload = {
"version": 1,
"operation": "set_mail_vacation",
"mailbox": self.mailbox.manifest(),
@@ -181,6 +197,12 @@ class MailVacation(MailPolicy):
if self.repeat_days != DEFAULT_REPEAT_DAYS
else {}
)
if self.move_spam or self.junk_senders:
payload["spam"] = {
"move_spam": self.move_spam,
"junk_senders": list(self.junk_senders),
}
return payload
def parse_mail_policy(data):
@@ -204,10 +226,16 @@ def parse_mail_policy(data):
"starts_at",
"ends_at",
}
if data.get("operation") == "set_mail_vacation" and fields in (
vacation_fields,
vacation_fields | {"repeat_days"},
if (
data.get("operation") == "set_mail_vacation"
and fields - {"repeat_days", "spam"} == vacation_fields
):
spam = data.get("spam", {"move_spam": False, "junk_senders": []})
if not isinstance(spam, dict) or spam.keys() != {
"move_spam",
"junk_senders",
}:
raise ValueError("Expected structured mailbox spam rules.")
return MailVacation(
MailboxSpec.from_manifest(data["mailbox"]),
data["enabled"],
@@ -216,5 +244,6 @@ def parse_mail_policy(data):
data["starts_at"],
data["ends_at"],
data.get("repeat_days", DEFAULT_REPEAT_DAYS),
**spam,
)
raise ValueError("Expected a version 1 mail policy.")
+38 -3
View File
@@ -23,6 +23,8 @@ ACTIONS = (
"reload",
"restart",
"database-report",
"system-backup",
"server-tls",
)
APT = "/usr/bin/apt-get"
@@ -39,6 +41,10 @@ class OperatorRequest:
if self.action in {"reload", "restart"}:
if self.target not in SERVICES:
raise ValueError("Choose a managed service.")
elif self.action == "system-backup":
from .system_backup import archive_id
archive_id(self.target)
elif self.target:
raise ValueError("This operation does not use a service target.")
if self.action == "package-upgrade":
@@ -117,6 +123,10 @@ def packages(request):
raise ValueError(
"The package plan changed. Collect and review a new preview."
)
if plan["count"] > len(plan["packages"]):
raise ValueError(
"Review this package update from the server console."
)
if plan["count"]:
command(
APT,
@@ -167,6 +177,18 @@ def apply_request(request):
return packages(request)
if request.action == "database-report":
return database_report()
if request.action == "server-tls":
from .server_tls import server_tls_report
return server_tls_report()
if request.action == "system-backup":
if os.environ.get("COULOBRE_SYSTEM_BACKUPS") != "1":
raise ValueError(
"Enable system backups in the host configuration."
)
from .system_backup import create_backup
return create_backup(request.target)
with locked_root_directory(STATE):
service = SERVICES[request.target]
command("/usr/bin/systemctl", request.action, service)
@@ -175,6 +197,19 @@ def apply_request(request):
def main():
return serve_apply_request(
1, OperatorRequest.from_manifest, apply_request, include_result=True
)
from .http_defaults import HttpDefaultsRequest, apply_http_defaults
def parse(payload):
if (
isinstance(payload, dict)
and payload.get("operation") == "http-defaults"
):
return HttpDefaultsRequest.from_manifest(payload)
return OperatorRequest.from_manifest(payload)
def apply(request):
if isinstance(request, HttpDefaultsRequest):
return apply_http_defaults(request)
return apply_request(request)
return serve_apply_request(1, parse, apply, include_result=True)
+91
View File
@@ -0,0 +1,91 @@
import os
import re
import subprocess
from urllib.parse import urlsplit
from cryptography import x509
from .domain_names import canonical_domain
FIRST_CERTIFICATE = re.compile(
b"-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----", re.DOTALL
)
def server_tls_report():
origin = os.environ.get("COULOBRE_PASSWORD_RESET_ORIGIN", "")
try:
panel = urlsplit(origin)
panel_hostname = panel.hostname
except ValueError:
panel_hostname = None
endpoints = (
("panel", panel_hostname, 443, ()),
("mail-imap", os.environ.get("COULOBRE_MAIL_IMAP_HOST"), 993, ()),
(
"mail-smtp",
os.environ.get("COULOBRE_MAIL_SUBMISSION_HOST"),
587,
("-starttls", "smtp"),
),
)
return {
"endpoints": [
inspect_local_tls(service, hostname, port, extra)
for service, hostname, port, extra in endpoints
]
}
def inspect_local_tls(service, hostname, port, extra):
base = {"service": service, "status": "unavailable", "port": port}
if not hostname:
return base
try:
hostname = canonical_domain(hostname)
result = subprocess.run(
(
"/usr/bin/openssl",
"s_client",
"-connect",
f"127.0.0.1:{port}",
"-servername",
hostname,
"-showcerts",
*extra,
),
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
check=False,
timeout=5,
env={"PATH": "/usr/sbin:/usr/bin", "LC_ALL": "C"},
)
certificate = FIRST_CERTIFICATE.search(result.stdout)
if certificate is None:
return base | {"hostname": hostname}
leaf = x509.load_pem_x509_certificate(certificate[0])
names = leaf.extensions.get_extension_for_class(
x509.SubjectAlternativeName
).value.get_values_for_type(x509.DNSName)
except (
OSError,
ValueError,
x509.ExtensionNotFound,
subprocess.TimeoutExpired,
):
return base
return base | {
"status": "presented",
"hostname": hostname,
"issuer": leaf.issuer.rfc4514_string()[:350],
"expires": leaf.not_valid_after_utc.isoformat(),
"name_matches": any(matches_name(hostname, name) for name in names),
}
def matches_name(hostname, name):
name = name.lower()
if name.startswith("*."):
return hostname.partition(".")[2] == name[2:]
return name == hostname
+9
View File
@@ -218,10 +218,12 @@ except ValueError as error:
LOCAL_WEB_ACTIVATION = os.environ.get("COULOBRE_LOCAL_WEB_ACTIVATION") == "1"
WEBSITE_USAGE = os.environ.get("COULOBRE_WEBSITE_USAGE") == "1"
WEBSITE_WILDCARD_CERTIFICATES = os.environ.get("COULOBRE_ACME_DNS_01") == "1"
LOCAL_WEB_HTTPS = os.environ.get("COULOBRE_LOCAL_WEB_HTTPS") == "1"
WEB_FILE_MANAGER = os.environ.get("COULOBRE_WEB_FILE_MANAGER") == "1"
WEBSITE_JOBS = os.environ.get("COULOBRE_WEBSITE_JOBS") == "1"
LOCAL_WEB_SFTP = os.environ.get("COULOBRE_LOCAL_WEB_SFTP") == "1"
SYSTEM_BACKUPS = os.environ.get("COULOBRE_SYSTEM_BACKUPS") == "1"
LOCAL_FOLDER_SFTP = (
LOCAL_WEB_SFTP and os.environ.get("COULOBRE_LOCAL_FOLDER_SFTP") == "1"
)
@@ -479,3 +481,10 @@ if LOCAL_ACCOUNT_BACKUPS and OFFSITE_BACKUP_DESTINATIONS:
"schedule": 15.0,
"options": {"expires": 14.0},
}
if SYSTEM_BACKUPS:
CELERY_BEAT_SCHEDULE["dispatch-system-backups"] = {
"task": "coulobre.hosting.tasks.dispatch_system_backups",
"schedule": 60.0,
"options": {"expires": 55.0},
}
+322
View File
@@ -0,0 +1,322 @@
import argparse
import hashlib
import json
import os
import re
import subprocess
import tarfile
from datetime import UTC, datetime
from importlib.metadata import PackageNotFoundError, version
from pathlib import Path, PurePosixPath
from tempfile import TemporaryDirectory
from uuid import UUID, uuid4
from .node_files import (
check_root_file,
locked_root_directory,
read_root_file,
replace_configuration,
require_root_directory,
)
STATE = Path("/var/lib/coulobre/system-backups")
MYSQL_SOCKET = "/run/mysqld/mysqld.sock"
ENVIRONMENT = {"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LC_ALL": "C"}
MANIFEST = "recovery/manifest.json"
SCHEMA = 1
HOST_PATHS = (
"etc/coulobre",
"etc/apache2",
"etc/php",
"etc/mysql",
"etc/postfix",
"etc/dovecot",
"etc/rspamd",
"etc/bind",
"etc/letsencrypt",
"etc/ssh/coulobre-authorized-keys",
"etc/ssh/sshd_config.d",
"etc/systemd/system",
"var/lib/coulobre/web-node",
"var/lib/coulobre/database-node",
"var/lib/coulobre/mail-node",
"var/lib/coulobre-vacation",
"var/lib/coulobre-mail",
"srv/coulobre/web",
"srv/coulobre-mail",
"var/lib/coulobre/account-backups",
)
ARCHIVE_NAME = re.compile(r"backup-([0-9a-f-]{36})[.]tar[.]gz")
def archive_id(value):
try:
canonical = str(UUID(value))
except (ValueError, TypeError, AttributeError):
raise ValueError("Choose a valid system backup ID.") from None
if value != canonical:
raise ValueError("Choose a canonical system backup ID.")
return canonical
def archive_paths(identifier):
name = f"backup-{archive_id(identifier)}"
return STATE / f"{name}.tar.gz", STATE / f"{name}.json"
def run(*arguments, stdout=subprocess.DEVNULL, timeout=900):
try:
subprocess.run(
arguments,
env=ENVIRONMENT,
timeout=timeout,
stdin=subprocess.DEVNULL,
stdout=stdout,
check=True,
)
except subprocess.TimeoutExpired:
raise ValueError("The system backup operation timed out.") from None
except subprocess.CalledProcessError:
raise ValueError(
"The system backup command failed. Check the service journal."
) from None
def hash_archive(archive):
with archive.open("rb") as source:
return hashlib.file_digest(source, "sha256").hexdigest()
def check_archive_record(archive, record_path, *, contents=False):
check_root_file(archive, mode=0o600)
report = json.loads(read_root_file(record_path, mode=0o600))
if (
not isinstance(report, dict)
or report.get("archive") != archive.name
or report.get("bytes") != archive.stat().st_size
or not re.fullmatch(r"[a-f0-9]{64}", str(report.get("sha256", "")))
or contents
and report["sha256"] != hash_archive(archive)
):
raise ValueError(
"The system backup record does not match its archive."
)
return report
def release_version():
try:
return version("coulobre-panel")
except PackageNotFoundError:
return "source checkout"
def save_identities(destination):
for database in ("passwd", "group"):
result = subprocess.run(
("/usr/bin/getent", database),
env=ENVIRONMENT,
capture_output=True,
timeout=10,
check=True,
)
managed = [
line
for line in result.stdout.decode("utf-8").splitlines()
if line.split(":", 1)[0].startswith(("coulobre", "cbf-"))
]
(destination / database).write_text(
"\n".join(managed) + "\n", encoding="utf-8"
)
def create_backup(identifier):
if os.geteuid() != 0:
raise ValueError("Run system backups as root.")
archive, record = archive_paths(identifier)
try:
keep = int(os.environ.get("COULOBRE_SYSTEM_BACKUP_KEEP", "7"))
except ValueError:
keep = 0
if not 1 <= keep <= 30:
raise ValueError(
"Set system backup retention between 1 and 30 archives."
)
require_root_directory(STATE.parent, create_mode=0o750)
require_root_directory(STATE, create_mode=0o700)
with locked_root_directory(STATE):
if record.exists():
return check_archive_record(archive, record)
if archive.exists():
check_root_file(archive, mode=0o600)
archive.unlink()
sources = [
source for source in HOST_PATHS if os.path.lexists("/" + source)
]
with TemporaryDirectory(prefix=".snapshot-", dir=STATE) as temporary:
workspace = Path(temporary)
recovery = workspace / "recovery"
recovery.mkdir(mode=0o700)
manifest = {
"created_at": datetime.now(UTC).isoformat(),
"schema": SCHEMA,
"release": release_version(),
"root_paths": sources,
}
(workspace / MANIFEST).write_text(
json.dumps(manifest), encoding="utf-8"
)
save_identities(recovery)
dump = recovery / "mariadb.sql"
with dump.open("xb") as target:
run(
"/usr/bin/mariadb-dump",
"--protocol=socket",
"--user=root",
f"--socket={MYSQL_SOCKET}",
"--all-databases",
"--single-transaction",
"--quick",
"--routines",
"--events",
"--triggers",
"--hex-blob",
stdout=target,
)
if not dump.stat().st_size:
raise ValueError("The MariaDB recovery dump is empty.")
staged = workspace / "archive.tar.gz"
run(
"/usr/bin/tar",
"--create",
"--gzip",
f"--file={staged}",
"--numeric-owner",
"--exclude=*.sock",
"--one-file-system",
"-C",
temporary,
"recovery",
"-C",
"/",
*sources,
timeout=1200,
)
staged.chmod(0o600)
report = {
"archive": archive.name,
"bytes": staged.stat().st_size,
"sha256": hash_archive(staged),
"created_at": manifest["created_at"],
}
with staged.open("rb") as source:
os.fsync(source.fileno())
staged.replace(archive)
replace_configuration(record, json.dumps(report), mode=0o600)
expire_backups(archive, keep)
return report
def expire_backups(current, keep):
archives = []
for path in STATE.iterdir():
name = ARCHIVE_NAME.fullmatch(path.name)
if name and path != current:
try:
archive, record = archive_paths(name[1])
if record.exists():
report = check_archive_record(archive, record)
created = datetime.fromisoformat(report["created_at"])
archives.append((created, archive, record))
except (OSError, KeyError, TypeError, ValueError):
continue
for _, archive, record in sorted(archives, reverse=True)[keep - 1 :]:
archive.unlink()
record.unlink()
def package_path(name):
path = PurePosixPath(name)
if (
not path.parts
or path.is_absolute()
or ".." in path.parts
or str(path) != name
or not any(
name == root or name.startswith(root + "/")
for root in (*HOST_PATHS, "recovery")
)
):
raise ValueError(
"The archive contains a path outside its recovery scope."
)
return path
def stage_recovery(identifier):
if os.geteuid() != 0:
raise ValueError("Stage system recovery as root.")
archive, record = archive_paths(identifier)
destination = STATE / f"recovery-{archive_id(identifier)}"
with locked_root_directory(STATE):
if os.path.lexists(destination):
raise ValueError("A recovery staging directory already exists.")
check_archive_record(archive, record, contents=True)
with TemporaryDirectory(prefix=".restore-", dir=STATE) as temporary:
staging = Path(temporary) / "data"
staging.mkdir(mode=0o700)
links = []
special = []
with tarfile.open(archive, "r:gz") as snapshot:
source = snapshot.extractfile(MANIFEST)
if source is None:
raise ValueError("The system backup manifest is missing.")
manifest = json.loads(source.read(16385))
if (
not isinstance(manifest, dict)
or manifest.get("schema") != SCHEMA
):
raise ValueError(
"The recovery archive uses an unsupported format."
)
for member in snapshot:
path = package_path(member.name)
if member.isfile() or member.isdir():
snapshot.extract(member, staging, filter="data")
elif member.issym() or member.islnk():
links.append(
{
"path": str(path),
"target": member.linkname,
"type": "symlink"
if member.issym()
else "hardlink",
}
)
else:
special.append(str(path))
(staging / "recovery-special-files.json").write_text(
json.dumps(special, indent=2), encoding="utf-8"
)
(staging / "recovery-links.json").write_text(
json.dumps(links, indent=2), encoding="utf-8"
)
staging.replace(destination)
return destination
def main(argv=None):
parser = argparse.ArgumentParser(description="Coulobre system recovery")
parser.add_argument("action", choices=("create", "stage"))
parser.add_argument("backup_id", nargs="?")
args = parser.parse_args(argv)
try:
if args.action == "create":
print(json.dumps(create_backup(args.backup_id or str(uuid4()))))
elif args.backup_id:
print(stage_recovery(args.backup_id))
else:
parser.error("Choose the backup ID to stage.")
except (OSError, ValueError, tarfile.TarError) as error:
parser.exit(1, f"coulobre-system-backup: {error}\n")
return 0
+41 -6
View File
@@ -1,5 +1,6 @@
import fcntl
import os
import re
import shutil
from dataclasses import dataclass, field
from pathlib import Path
@@ -51,10 +52,32 @@ class WebCertificateRequest:
action: str
chain: str = field(default="", repr=False)
key: str = field(default="", repr=False)
wildcard: bool = False
email: str = ""
def __post_init__(self):
if self.action not in ACTIONS:
raise ValueError("Choose a supported certificate operation.")
if (
type(self.wildcard) is not bool
or not isinstance(self.email, str)
or (
self.email
and (
len(self.email) > 254
or not re.fullmatch(
r"[A-Za-z0-9._+%-]+@[A-Za-z0-9.-]+", self.email
)
)
)
or (
(self.wildcard or self.email)
and self.action not in {"issue", "reissue"}
)
):
raise ValueError(
"Choose supported ACME contact and challenge settings."
)
if self.action == "upload":
check_pem_size(self.chain, MAX_CERTIFICATE_BYTES)
check_pem_size(self.key, MAX_KEY_BYTES)
@@ -66,7 +89,11 @@ class WebCertificateRequest:
"operation": "manage_certificate",
"site": self.site.manifest(),
"action": self.action,
}
} | (
{"wildcard": self.wildcard, "email": self.email}
if self.wildcard or self.email
else {}
)
def manifest(self):
return self.identity() | (
@@ -80,6 +107,8 @@ class WebCertificateRequest:
fields = {"operation", "site", "action"}
if data.get("action") == "upload":
fields |= {"chain", "key"}
if "wildcard" in data or "email" in data:
fields |= {"wildcard", "email"}
if data.keys() != fields:
raise ValueError("Expected a certificate operation.")
return cls(
@@ -87,6 +116,8 @@ class WebCertificateRequest:
data["action"],
data.get("chain", ""),
data.get("key", ""),
data.get("wildcard", False),
data.get("email", ""),
)
@@ -176,10 +207,12 @@ def apply_website_certificate(request):
if os.geteuid() != 0:
raise ValueError("Run certificate management as root on the web node.")
site = request.site
if request.action == "issue":
if request.action == "issue" and not (request.wildcard or request.email):
provision_https(site)
elif request.action == "reissue":
reissue_certificate(site)
elif request.action in {"issue", "reissue"}:
reissue_certificate(
site, wildcard=request.wildcard, email=request.email
)
elif request.action == "upload":
install_uploaded_certificate(
site, *validated_pem(request.chain, request.key)
@@ -201,7 +234,7 @@ def reload_apache():
run("/usr/sbin/service", "apache2", "reload")
def reissue_certificate(site):
def reissue_certificate(site, *, wildcard=False, email=""):
with locked_web_node(fcntl.LOCK_EX):
paths = SitePaths.for_site(site)
check_https_prerequisites(site, paths)
@@ -217,7 +250,9 @@ def reissue_certificate(site):
if (path := lineage / f"{name}.pem").is_symlink()
}
try:
request_certificate(site, force=True)
request_certificate(
site, force=True, wildcard=wildcard, email=email
)
apache, enabled = https_paths(paths)
install_https_configuration(
site, apache, enabled, socket_path=paths.apache_socket
+26 -6
View File
@@ -22,6 +22,7 @@ from .web_node_apply import (
CERTBOT_ROOT = Path("/etc/letsencrypt")
ACME_WEBROOT = Path("/var/www/coulobre-acme")
ACME_DNS_HOOKS = Path("/etc/coulobre/acme-dns")
def provision_https(site):
@@ -60,19 +61,38 @@ def ensure_certificate(site):
request_certificate(site)
def request_certificate(site, *, force=False):
def request_certificate(site, *, force=False, wildcard=False, email=""):
challenge = ("--webroot", "--webroot-path", str(ACME_WEBROOT))
names = ("--domains", site.domain)
if wildcard:
require_root_directory(ACME_DNS_HOOKS)
auth, cleanup = (ACME_DNS_HOOKS / name for name in ("auth", "cleanup"))
for hook in (auth, cleanup):
check_root_file(hook)
if not os.access(hook, os.X_OK):
raise ValueError(
"Provide executable DNS-01 hooks on the web node."
)
challenge = (
"--manual",
"--preferred-challenges",
"dns",
"--manual-auth-hook",
str(auth),
"--manual-cleanup-hook",
str(cleanup),
)
names += ("--domains", f"*.{site.domain}")
command = (
"/usr/bin/certbot",
"certonly",
"--non-interactive",
"--force-renewal" if force else "--keep-until-expiring",
"--webroot",
"--webroot-path",
str(ACME_WEBROOT),
*challenge,
"--cert-name",
certbot_lineage(site).name,
"--domains",
site.domain,
*names,
*((f"--email={email}",) if email else ()),
)
try:
subprocess.run(