Manage configured hosting capabilities from the panel
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s

This commit is contained in:
parkel committed 2026-11-23 20:36:59 +01:00
1 parent 2d2cd1837e
commit 389bc07541
23 files changed
+749 -139

No files matched your search

+33
View File
@@ -496,6 +496,20 @@ connected. Follow their logs with `journalctl`.
sudo journalctl -u coulobre-panel -u coulobre-worker -u coulobre-beat sudo journalctl -u coulobre-panel -u coulobre-worker -u coulobre-beat
``` ```
## Manage panel roles
A verified superuser can assign a Customer or Customer manager role to an
active login from **Customers** or **Customer managers**. Choose **Assign
to existing login** and enter the username. Customer roles use their own
assigned hosting accounts. Customer managers use their own hosting account
assignments and hosting plan policy. New manager assignments use the default
customer manager profile when one is configured.
Logins with multiple roles can choose **Panel role** in the account area.
The role applies to the session, including direct page requests and actions.
Returning to the administrator role requires a verified second factor. If the
active role assignment is revoked, the session asks the user to sign in again.
## Select a panel theme ## Select a panel theme
The panel follows the browser's light or dark preference on the first visit. The panel follows the browser's light or dark preference on the first visit.
@@ -2657,6 +2671,25 @@ Keep the managed data directories on their service filesystems to allow
an atomic move into the archive directory. Existing backup archives remain an atomic move into the archive directory. Existing backup archives remain
available to operators with backup access. available to operators with backup access.
## Configure installed features in the panel
Open **About Coulobre → Configure features** as a superuser with a verified
second factor. The page shows the installation prerequisites and distinguishes
local mail and DNS services from linked receivers. Use **Configure DNS
defaults** to edit the zone template for new hosting accounts.
The switches control which installed capabilities the panel offers for new
actions. Existing managed sites, mailbox delivery, published DNS records,
schedules and queued provisioning continue running. Backup archives remain
accessible when new backup requests are paused. Pausing an application sign-in
also prevents redemption of pending tickets for that application.
Configure service packages, linked receiver identities, bridge keys and
backup credentials on the host using their deployment procedures. Enabling
a paused feature checks its available service socket and, for linked mail or
DNS, the receiver's readiness and version. A failed prerequisite check leaves
the saved choices intact. Changes are recorded in the administrator audit log.
## Monitor local and remote services ## Monitor local and remote services
The panel's **Service health** page shows the latest observation and timestamp The panel's **Service health** page shows the latest observation and timestamp
+6 -1
View File
@@ -11,6 +11,7 @@ from coulobre.account_restore_request import (
) )
from coulobre.database_node import DatabaseSpec from coulobre.database_node import DatabaseSpec
from .installation_features import panel_feature_allowed
from .models import AccountBackupSchedule from .models import AccountBackupSchedule
SCHEDULE_FIELDS = ( SCHEDULE_FIELDS = (
@@ -49,7 +50,11 @@ class AccountBackupScheduleForm(forms.Form):
self.allow_mail = allow_mail self.allow_mail = allow_mail
if not allow_mail and not self.initial.get("include_mailboxes"): if not allow_mail and not self.initial.get("include_mailboxes"):
del self.fields["include_mailboxes"] del self.fields["include_mailboxes"]
destinations = settings.OFFSITE_BACKUP_DESTINATIONS destinations = (
settings.OFFSITE_BACKUP_DESTINATIONS
if panel_feature_allowed("OFFSITE_BACKUP_DESTINATIONS")
else {}
)
current = self.initial.get("offsite_destination") current = self.initial.get("offsite_destination")
if destinations or current: if destinations or current:
choices = [("", "Local archive only"), *destinations.items()] choices = [("", "Local archive only"), *destinations.items()]
+3 -2
View File
@@ -11,6 +11,7 @@ from coulobre.web_node import WebSite
from .dns_defaults import zone_defaults from .dns_defaults import zone_defaults
from .dns_forms import normalize_record_rows from .dns_forms import normalize_record_rows
from .dns_publication import queue_zone_snapshot from .dns_publication import queue_zone_snapshot
from .installation_features import panel_feature_allowed
from .mail_dns_setup import mail_dns_proposal from .mail_dns_setup import mail_dns_proposal
from .models import ( from .models import (
HostingDnsZone, HostingDnsZone,
@@ -70,8 +71,8 @@ def setup_new_account(account, options):
) )
if managed_dns: if managed_dns:
existing_managed_mail = ( existing_managed_mail = (
settings.LOCAL_MAILBOX_PROVISIONING panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING")
and settings.MANAGE_MAIL_DNS and panel_feature_allowed("MANAGE_MAIL_DNS")
and account.mail_domains.filter(domain=domain).exists() and account.mail_domains.filter(domain=domain).exists()
) )
create_default_dns_zone( create_default_dns_zone(
@@ -1,5 +1,4 @@
from django import forms from django import forms
from django.conf import settings
from django.contrib.auth.mixins import PermissionRequiredMixin from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.db import IntegrityError from django.db import IntegrityError
@@ -20,6 +19,7 @@ from .independent_websites import (
create_website, create_website,
queue_website_operation, queue_website_operation,
) )
from .installation_features import panel_feature_allowed
from .models import HostingAccount, IndependentWebsite, WebsiteDomain from .models import HostingAccount, IndependentWebsite, WebsiteDomain
@@ -79,7 +79,7 @@ class IndependentWebsiteEditor(
template_name = "hosting/independent_website_form.html" template_name = "hosting/independent_website_form.html"
def dispatch(self, request, *args, **kwargs): def dispatch(self, request, *args, **kwargs):
if not settings.LOCAL_WEB_ACTIVATION: if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"):
raise Http404 raise Http404
return super().dispatch(request, *args, **kwargs) return super().dispatch(request, *args, **kwargs)
@@ -130,7 +130,9 @@ class IndependentWebsiteOperation(IndependentWebsiteEditor):
operation = Operation(self.kwargs["operation"]) operation = Operation(self.kwargs["operation"])
except ValueError: except ValueError:
raise Http404 from None raise Http404 from None
if operation == Operation.HTTPS and not settings.LOCAL_WEB_HTTPS: if operation == Operation.HTTPS and not panel_feature_allowed(
"LOCAL_WEB_HTTPS"
):
raise Http404 raise Http404
return operation return operation
+2 -1
View File
@@ -9,6 +9,7 @@ from coulobre.php_runtime import validate_php_version
from coulobre.service_access import ServiceAccessRequest from coulobre.service_access import ServiceAccessRequest
from .access import is_tenant, manages_account from .access import is_tenant, manages_account
from .installation_features import panel_feature_allowed
from .models import IndependentWebsite, WebsiteDomain, WebsiteRestoreJob from .models import IndependentWebsite, WebsiteDomain, WebsiteRestoreJob
from .node_client import ( from .node_client import (
activate_local_site, activate_local_site,
@@ -54,7 +55,7 @@ def website_actions(website):
if website.suspended: if website.suspended:
return (Operation.RESUME, Operation.RETIRE) return (Operation.RESUME, Operation.RETIRE)
actions = (Operation.PHP, Operation.SUSPEND) actions = (Operation.PHP, Operation.SUSPEND)
if settings.LOCAL_WEB_HTTPS and not website.https_enabled: if panel_feature_allowed("LOCAL_WEB_HTTPS") and not website.https_enabled:
actions += (Operation.HTTPS,) actions += (Operation.HTTPS,)
return actions return actions
@@ -0,0 +1,193 @@
from contextvars import ContextVar
from dataclasses import dataclass
from pathlib import Path
from django.conf import settings
from django.utils.functional import cached_property
from coulobre.linked_updates import UNIT_DIR
from .dns_defaults import zone_defaults
from .models import PanelFeaturePolicy
@dataclass(frozen=True)
class Feature:
setting: str
label: str
prerequisite: str
socket: str = ""
role: str = ""
@property
def configured(self):
if self.setting == "DEFAULT_DNS_ZONES":
defaults = zone_defaults()
return bool(
settings.LOCAL_DNS_PUBLISHING
and defaults.nameservers
and defaults.addresses
)
if self.setting == "PHPMYADMIN_URL":
return bool(
settings.PHPMYADMIN_URL and settings.LOCAL_DATABASE_CREDENTIALS
)
if self.setting == "ROUNDCUBE_URL":
return bool(
settings.ROUNDCUBE_URL
and (
settings.LOCAL_MAILBOX_CREDENTIALS
or settings.REMOTE_MAILBOX_CREDENTIALS
)
)
return bool(getattr(settings, self.setting))
@property
def linked(self):
return (
bool(self.role)
and (
UNIT_DIR / f"coulobre-{self.role}-apply@.service.d/remote.conf"
).is_file()
)
@property
def socket_ready(self):
if self.setting == "ROUNDCUBE_URL":
socket = (
"coulobre-mail-credentials"
if settings.REMOTE_MAILBOX_CREDENTIALS
else "coulobre-service-credentials"
)
return Path(f"/run/{socket}.sock").is_socket()
return not self.socket or Path(f"/run/{self.socket}.sock").is_socket()
FEATURES = (
Feature(
"LOCAL_WEB_ACTIVATION",
"Website provisioning",
"Apache and PHP provisioning",
"coulobre-web-apply",
),
Feature(
"LOCAL_WEB_HTTPS",
"Managed website certificates",
"Website certificate provisioning",
"coulobre-https-apply",
),
Feature(
"WEB_FILE_MANAGER",
"Website file manager",
"Website file service",
"coulobre-website-files",
),
Feature(
"WEBSITE_JOBS",
"Website scheduled tasks",
"Website task service",
"coulobre-website-jobs",
),
Feature(
"LOCAL_DNS_PUBLISHING",
"DNS publishing",
"Local BIND9 or a linked DNS receiver",
"coulobre-dns-apply",
"dns",
),
Feature(
"DEFAULT_DNS_ZONES",
"Default managed DNS zones for new accounts",
"DNS publishing, nameservers and hosting IP addresses",
),
Feature(
"LOCAL_MAILBOX_PROVISIONING",
"Mailbox provisioning",
"Local mail services or a linked mail receiver",
"coulobre-mail-apply",
"mail",
),
Feature(
"MANAGE_MAIL_DNS",
"Managed mail DNS records",
"Mail exchanger and sending IP addresses",
),
Feature(
"LOCAL_DATABASE_PROVISIONING",
"Database provisioning",
"MariaDB provisioning",
"coulobre-database-apply",
),
Feature(
"LOCAL_ACCOUNT_BACKUPS",
"Local account backups",
"Local backup service",
"coulobre-account-backup",
),
Feature(
"OFFSITE_BACKUP_DESTINATIONS",
"Off-site backup destinations",
"A configured destination and the transfer service",
"coulobre-account-offsite",
),
Feature(
"PHPMYADMIN_URL",
"phpMyAdmin sign-in",
"phpMyAdmin bridge and MariaDB credential service",
"coulobre-service-credentials",
),
Feature(
"ROUNDCUBE_URL",
"Roundcube sign-in",
"Roundcube bridge and mailbox credential service",
),
)
class FeaturePolicy:
@cached_property
def saved(self):
return (
PanelFeaturePolicy.objects.filter(pk=1).first()
or PanelFeaturePolicy()
)
@cached_property
def disabled(self):
return frozenset(self.saved.disabled)
current_policy = ContextVar("current_feature_policy", default=None)
def panel_feature_allowed(setting):
if not getattr(settings, setting):
return False
return not panel_feature_paused(setting)
def panel_feature_paused(setting):
policy = current_policy.get() or FeaturePolicy()
return setting in policy.disabled
def default_dns_zones_allowed(defaults):
if not defaults.nameservers or not defaults.addresses:
return False
policy = current_policy.get() or FeaturePolicy()
return (
panel_feature_allowed("LOCAL_DNS_PUBLISHING")
and "DEFAULT_DNS_ZONES" not in policy.disabled
)
class FeaturePolicyMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
token = current_policy.set(FeaturePolicy())
try:
return self.get_response(request)
finally:
current_policy.reset(token)
+145 -39
View File
@@ -1,13 +1,23 @@
from importlib.metadata import PackageNotFoundError, version from importlib.metadata import PackageNotFoundError, version
from django.conf import settings from django import forms
from django.contrib.auth.mixins import PermissionRequiredMixin from django.contrib import messages
from django.contrib.admin.models import CHANGE, LogEntry
from django.contrib.auth.mixins import (
PermissionRequiredMixin,
UserPassesTestMixin,
)
from django.db import transaction
from django.db.models import F
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache from django.views.decorators.cache import never_cache
from django.views.generic import TemplateView from django.views.generic import FormView, TemplateView
from .access import OperatorOnlyMixin from .access import OperatorOnlyMixin
from .dns_defaults import zone_defaults from .installation_features import FEATURES, FeaturePolicy
from .models import PanelFeaturePolicy
from .update_views import inspect_linked_nodes
@method_decorator(never_cache, name="dispatch") @method_decorator(never_cache, name="dispatch")
@@ -22,41 +32,137 @@ class InstallationView(
installed_version = version("coulobre-panel") installed_version = version("coulobre-panel")
except PackageNotFoundError: except PackageNotFoundError:
installed_version = "Unavailable" installed_version = "Unavailable"
policy = FeaturePolicy()
dns_defaults = zone_defaults() features = []
features = ( for feature in FEATURES:
("Local website provisioning", settings.LOCAL_WEB_ACTIVATION), configured = feature.configured
("Managed website certificates", settings.LOCAL_WEB_HTTPS), enabled = (
("Website file manager", settings.WEB_FILE_MANAGER), configured
("Website scheduled tasks", settings.WEBSITE_JOBS), and feature.setting not in policy.disabled
("Local DNS publishing", settings.LOCAL_DNS_PUBLISHING), and (
( feature.setting != "DEFAULT_DNS_ZONES"
"Default managed DNS zones for new accounts", or "LOCAL_DNS_PUBLISHING" not in policy.disabled
settings.LOCAL_DNS_PUBLISHING
and dns_defaults.nameservers
and dns_defaults.addresses,
),
(
"Local mailbox provisioning",
settings.LOCAL_MAILBOX_PROVISIONING,
),
("Managed mail DNS records", settings.MANAGE_MAIL_DNS),
(
"Local database provisioning",
settings.LOCAL_DATABASE_PROVISIONING,
),
("Local account backups", settings.LOCAL_ACCOUNT_BACKUPS),
(
"Off-site backup destinations",
settings.OFFSITE_BACKUP_DESTINATIONS,
),
("phpMyAdmin sign-in", settings.PHPMYADMIN_URL),
("Roundcube sign-in", settings.ROUNDCUBE_URL),
) )
)
features.append((feature, configured, enabled))
return super().get_context_data( return super().get_context_data(
installed_version=installed_version, installed_version=installed_version, features=features, **kwargs
features=[ )
(name, bool(configured)) for name, configured in features
],
**kwargs, class FeatureConfigurationForm(forms.Form):
revision = forms.IntegerField(min_value=0, widget=forms.HiddenInput)
def __init__(self, *args, policy, **kwargs):
super().__init__(*args, **kwargs)
self.initial["revision"] = policy.saved.revision
self.configured_features = [
feature for feature in FEATURES if feature.configured
]
for feature in self.configured_features:
self.fields[feature.setting] = forms.BooleanField(
required=False,
label=feature.label,
help_text=feature.prerequisite,
initial=feature.setting not in policy.disabled,
)
def changed_features(self):
return [
feature
for feature in self.configured_features
if feature.setting in self.changed_data
]
def check_features(form, changed):
new_enabled = [
feature for feature in changed if form.cleaned_data[feature.setting]
]
nodes = {}
if any(feature.linked for feature in new_enabled):
topology = inspect_linked_nodes()
nodes = {node["role"]: node for node in topology.get("nodes", [])}
for feature in new_enabled:
if not feature.socket_ready:
form.add_error(
feature.setting,
"Start the configured service before enabling this feature.",
)
elif feature.linked:
report = nodes.get(feature.role, {})
if report.get("state") != "configured" or report.get(
"release"
) != version("coulobre-panel"):
form.add_error(
feature.setting,
"The linked receiver must be ready and on the same "
"release.",
)
if (
feature.setting == "DEFAULT_DNS_ZONES"
and not form.cleaned_data.get("LOCAL_DNS_PUBLISHING")
):
form.add_error(feature.setting, "Enable DNS publishing first.")
@method_decorator(never_cache, name="dispatch")
class FeatureConfigurationView(UserPassesTestMixin, FormView):
form_class = FeatureConfigurationForm
template_name = "hosting/feature_configuration.html"
success_url = reverse_lazy("panel:installation")
def test_func(self):
return (
self.request.user.is_superuser and self.request.user.is_verified()
)
def get_form_kwargs(self):
return {**super().get_form_kwargs(), "policy": FeaturePolicy()}
def form_valid(self, form):
revision = form.cleaned_data["revision"]
policy = FeaturePolicy()
if revision != policy.saved.revision:
return self.stale_form(form)
changed = form.changed_features()
if not changed:
return super().form_valid(form)
check_features(form, changed)
if form.errors:
return self.form_invalid(form)
disabled = set(policy.disabled)
for feature in changed:
if form.cleaned_data[feature.setting]:
disabled.discard(feature.setting)
else:
disabled.add(feature.setting)
with transaction.atomic():
saved, _ = PanelFeaturePolicy.objects.get_or_create(pk=1)
updated = PanelFeaturePolicy.objects.filter(
pk=1, revision=revision
).update(disabled=sorted(disabled), revision=F("revision") + 1)
if not updated:
return self.stale_form(form)
LogEntry.objects.log_actions(
self.request.user.pk,
[saved],
CHANGE,
[
{
"changed": {
"fields": [feature.label for feature in changed]
}
}
],
)
messages.success(self.request, "Feature configuration saved.")
return super().form_valid(form)
def stale_form(self, form):
form.add_error(
None, "The configuration changed. Reopen this page and try again."
)
return self.render_to_response(
self.get_context_data(form=form), status=409
) )
+5 -3
View File
@@ -22,6 +22,7 @@ from coulobre.mail_dns import (
) )
from .access import OperatorOnlyMixin, TenantScopeMixin, is_tenant from .access import OperatorOnlyMixin, TenantScopeMixin, is_tenant
from .installation_features import panel_feature_allowed
from .mail_dns_setup import ( from .mail_dns_setup import (
closest_zone, closest_zone,
mail_dns_proposal, mail_dns_proposal,
@@ -156,8 +157,8 @@ class MailDnsCheckView(
report=report, report=report,
mail_domain=self.object, mail_domain=self.object,
can_refresh=( can_refresh=(
settings.MANAGE_MAIL_DNS panel_feature_allowed("MANAGE_MAIL_DNS")
and settings.LOCAL_MAILBOX_PROVISIONING and panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING")
and not is_tenant(self.request.user) and not is_tenant(self.request.user)
and self.request.user.has_perms(PROVISION_MAILBOX) and self.request.user.has_perms(PROVISION_MAILBOX)
and self.object.mailboxes.filter( and self.object.mailboxes.filter(
@@ -261,7 +262,8 @@ class RequestMailDnsSetup(OperatorOnlyMixin, PermissionRequiredMixin, View):
def post(self, request, pk): def post(self, request, pk):
if not ( if not (
settings.MANAGE_MAIL_DNS and settings.LOCAL_MAILBOX_PROVISIONING panel_feature_allowed("MANAGE_MAIL_DNS")
and panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING")
): ):
raise Http404 raise Http404
domain = get_object_or_404(HostingMailDomain, pk=pk) domain = get_object_or_404(HostingMailDomain, pk=pk)
+2 -2
View File
@@ -1,6 +1,5 @@
from datetime import timedelta from datetime import timedelta
from django.conf import settings
from django.contrib.auth.mixins import PermissionRequiredMixin from django.contrib.auth.mixins import PermissionRequiredMixin
from django.db import transaction from django.db import transaction
from django.http import Http404 from django.http import Http404
@@ -11,6 +10,7 @@ from django.views.decorators.cache import never_cache
from django.views.generic import TemplateView from django.views.generic import TemplateView
from .access import OperatorOnlyMixin from .access import OperatorOnlyMixin
from .installation_features import panel_feature_allowed
from .models import HostingMailDomain from .models import HostingMailDomain
from .tasks import refresh_mail_queue from .tasks import refresh_mail_queue
@@ -24,7 +24,7 @@ class MailQueueView(OperatorOnlyMixin, PermissionRequiredMixin, TemplateView):
template_name = "hosting/mail_queue.html" template_name = "hosting/mail_queue.html"
def get_domain(self, *, locked=False): def get_domain(self, *, locked=False):
if not settings.LOCAL_MAILBOX_PROVISIONING: if not panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING"):
raise Http404 raise Http404
domains = HostingMailDomain.objects.filter( domains = HostingMailDomain.objects.filter(
account__retired_at__isnull=True account__retired_at__isnull=True
@@ -0,0 +1,28 @@
# Generated by Django 5.2.19 on 2026-11-23 19:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0058_scope_service_signon_grants"),
]
operations = [
migrations.CreateModel(
name="PanelFeaturePolicy",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("disabled", models.JSONField(blank=True, default=list)),
("revision", models.PositiveBigIntegerField(default=0)),
],
),
]
+5
View File
@@ -608,6 +608,11 @@ class DirectAdminImport(models.Model):
fingerprint = models.CharField(max_length=64, unique=True) fingerprint = models.CharField(max_length=64, unique=True)
class PanelFeaturePolicy(models.Model):
disabled = models.JSONField(default=list, blank=True)
revision = models.PositiveBigIntegerField(default=0)
class DnsZoneDefaults(models.Model): class DnsZoneDefaults(models.Model):
nameservers = models.JSONField(default=list, blank=True) nameservers = models.JSONField(default=list, blank=True)
addresses = models.JSONField(default=list, blank=True) addresses = models.JSONField(default=list, blank=True)
+2 -1
View File
@@ -12,6 +12,7 @@ from django.views.decorators.http import require_POST
from .access import customer_for_user from .access import customer_for_user
from .credential_views import DatabaseCredentialView from .credential_views import DatabaseCredentialView
from .installation_features import panel_feature_allowed
from .models import HostingDatabase, PhpMyAdminGrant, ServiceCredentialAccess from .models import HostingDatabase, PhpMyAdminGrant, ServiceCredentialAccess
from .service_credentials import ( from .service_credentials import (
CredentialKind, CredentialKind,
@@ -30,7 +31,7 @@ from .signon import (
def phpmyadmin_available(request): def phpmyadmin_available(request):
return bool( return bool(
settings.PHPMYADMIN_URL panel_feature_allowed("PHPMYADMIN_URL")
and settings.PHPMYADMIN_BRIDGE_KEY and settings.PHPMYADMIN_BRIDGE_KEY
and enabled_credential_access(request, CredentialKind.DATABASE) and enabled_credential_access(request, CredentialKind.DATABASE)
) )
+2 -1
View File
@@ -12,6 +12,7 @@ from django.views.decorators.http import require_POST
from .access import customer_for_user from .access import customer_for_user
from .credential_views import MailboxCredentialView from .credential_views import MailboxCredentialView
from .installation_features import panel_feature_allowed
from .models import HostingMailbox, RoundcubeGrant, ServiceCredentialAccess from .models import HostingMailbox, RoundcubeGrant, ServiceCredentialAccess
from .service_credentials import ( from .service_credentials import (
CredentialKind, CredentialKind,
@@ -30,7 +31,7 @@ from .signon import (
def roundcube_available(request): def roundcube_available(request):
return bool( return bool(
settings.ROUNDCUBE_URL panel_feature_allowed("ROUNDCUBE_URL")
and settings.ROUNDCUBE_BRIDGE_KEY and settings.ROUNDCUBE_BRIDGE_KEY
and enabled_credential_access(request, CredentialKind.MAILBOX) and enabled_credential_access(request, CredentialKind.MAILBOX)
) )
@@ -16,7 +16,7 @@
</p> </p>
{% endif %} {% endif %}
</div> </div>
{% if not account_backup_pending %} {% if can_request_account_backup and not account_backup_pending %}
<form class="form-actions" method="post" action="{% url 'panel:account_backup_create' account.pk %}"> <form class="form-actions" method="post" action="{% url 'panel:account_backup_create' account.pk %}">
{% csrf_token %} {% csrf_token %}
{% if account_backup_allow_mail %} {% if account_backup_allow_mail %}
@@ -0,0 +1,27 @@
{% extends "hosting/base.html" %}
{% block title %}Configure features · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{% url 'panel:installation' %}">← About Coulobre</a>
<header class="page-heading"><h1>Configure features</h1></header>
<div class="surface editor-surface">
<p>Choose which configured features the panel can use for new requests. Existing sites, mailboxes, scheduled tasks and backups keep running.</p>
<form class="editor" method="post">
{% csrf_token %}
{{ form.non_field_errors }}
{{ form.revision }}
{% for field in form.visible_fields %}
<div>
<label for="{{ field.id_for_label }}">{{ field }} {{ field.label }}</label>
{{ field.errors }}
<p class="heading-meta" id="{{ field.id_for_label }}_helptext">{{ field.help_text }}</p>
</div>
{% empty %}
<p>No installed features can be configured here yet.</p>
{% endfor %}
<div class="form-actions">
{% if form.visible_fields %}<button class="button primary" type="submit">Save configuration</button>{% endif %}
<a class="button secondary" href="{% url 'panel:installation' %}">Cancel</a>
</div>
</form>
</div>
{% endblock %}
@@ -4,6 +4,7 @@
{% block content %} {% block content %}
<header class="page-heading"><h1>About Coulobre</h1></header> <header class="page-heading"><h1>About Coulobre</h1></header>
{% for message in messages %}<p class="notice" role="status">{{ message }}</p>{% endfor %}
<section class="surface" aria-labelledby="installation-heading"> <section class="surface" aria-labelledby="installation-heading">
<header class="section-heading"><h2 id="installation-heading">Installation</h2></header> <header class="section-heading"><h2 id="installation-heading">Installation</h2></header>
<dl class="details"> <dl class="details">
@@ -17,22 +18,28 @@
<h2 id="features-heading">Feature configuration</h2> <h2 id="features-heading">Feature configuration</h2>
<p class="muted">See <a href="{% url 'panel:service_health' %}">Service health</a> for the latest local and remote checks.</p> <p class="muted">See <a href="{% url 'panel:service_health' %}">Service health</a> for the latest local and remote checks.</p>
</div> </div>
{% if request.user.is_superuser and request.user.is_verified %}
<a class="button secondary" href="{% url 'panel:feature_configuration' %}">Configure features</a>
{% endif %}
</header> </header>
<div class="table-scroll"> <div class="table-scroll">
<table> <table>
<thead><tr><th scope="col">Feature</th><th scope="col">Configuration</th></tr></thead> <thead><tr><th scope="col">Feature</th><th scope="col">Configuration</th><th scope="col">Prerequisites</th></tr></thead>
<tbody> <tbody>
{% for name, enabled in features %} {% for feature, configured, enabled in features %}
<tr> <tr>
<th scope="row">{{ name }}</th> <th scope="row">{{ feature.label }}</th>
<td> <td>
<div class="table-actions"> <div class="table-actions">
{% if enabled %}<span class="status active">Enabled</span>{% else %}<span>Disabled</span>{% endif %} {% if enabled %}<span class="status active">Enabled</span>{% elif configured %}<span>Paused in panel</span>{% else %}<span>Requires setup</span>{% endif %}
{% if request.user.is_superuser and name == 'Default managed DNS zones for new accounts' %} {% if enabled and not feature.socket_ready %}<span class="muted">Service socket unavailable</span>{% endif %}
{% if configured and feature.role %}<span>{% if feature.linked %}Linked receiver{% else %}Local{% endif %}</span>{% endif %}
{% if request.user.is_superuser and feature.setting == 'DEFAULT_DNS_ZONES' %}
<a class="record-link" href="{% url 'panel:dns_defaults' %}">Configure DNS defaults</a> <a class="record-link" href="{% url 'panel:dns_defaults' %}">Configure DNS defaults</a>
{% endif %} {% endif %}
</div> </div>
</td> </td>
<td>{{ feature.prerequisite }}</td>
</tr> </tr>
{% endfor %} {% endfor %}
</tbody> </tbody>
@@ -0,0 +1,140 @@
from unittest.mock import PropertyMock, patch
from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
from django.urls import reverse
from django_otp.plugins.otp_totp.models import TOTPDevice
from .models import AccountBackupJob, HostingAccount, PanelFeaturePolicy
@override_settings(LOCAL_ACCOUNT_BACKUPS=True, LOCAL_DNS_PUBLISHING=True)
class FeatureConfigurationTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.operator = get_user_model().objects.create_superuser("operator")
cls.device = TOTPDevice.objects.create(user=cls.operator, name="Panel")
cls.account = HostingAccount.objects.create(
name="Existing account", primary_domain="site.example"
)
def sign_in(self, *, verified=True):
self.client.force_login(self.operator)
if verified:
session = self.client.session
session["otp_device_id"] = self.device.persistent_id
session.save()
def save(self, **data):
return self.client.post(reverse("panel:feature_configuration"), data)
def test_paused_backup_option_blocks_new_jobs_but_archives_stay_visible(
self,
):
self.sign_in()
result = self.save(revision=0, LOCAL_DNS_PUBLISHING="on")
self.assertRedirects(result, reverse("panel:installation"))
self.assertEqual(
PanelFeaturePolicy.objects.get().disabled,
["LOCAL_ACCOUNT_BACKUPS"],
)
self.assertEqual(
self.client.post(
reverse("panel:account_backup_create", args=[self.account.pk])
).status_code,
404,
)
self.assertFalse(AccountBackupJob.objects.exists())
self.assertEqual(
self.client.get(
reverse(
"panel:account_backup_archives", args=[self.account.pk]
)
).status_code,
200,
)
def test_failed_preflight_preserves_all_choices_and_revision(self):
self.sign_in()
policy = PanelFeaturePolicy.objects.create(
pk=1, disabled=["LOCAL_DNS_PUBLISHING"], revision=2
)
with patch(
"coulobre.hosting.installation_features.Feature.socket_ready",
new_callable=PropertyMock,
return_value=False,
):
response = self.save(revision=2, LOCAL_DNS_PUBLISHING="on")
self.assertContains(
response, "Start the configured service before enabling"
)
policy.refresh_from_db()
self.assertEqual(policy.disabled, ["LOCAL_DNS_PUBLISHING"])
self.assertEqual(policy.revision, 2)
self.assertEqual(self.save(revision=1).status_code, 409)
def test_linked_receiver_must_match_panel_release_before_enabling(self):
self.sign_in()
policy = PanelFeaturePolicy.objects.create(
pk=1, disabled=["LOCAL_DNS_PUBLISHING"]
)
module = "coulobre.hosting.installation_features.Feature"
update = "coulobre.hosting.installation_views"
with (
patch(
f"{module}.linked",
new_callable=PropertyMock,
return_value=True,
),
patch(
f"{module}.socket_ready",
new_callable=PropertyMock,
return_value=True,
),
patch(f"{update}.version", return_value="1.0.0"),
patch(
f"{update}.inspect_linked_nodes",
return_value={
"nodes": [
{
"role": "dns",
"release": "0.9.0",
"state": "configured",
}
]
},
) as linked,
):
response = self.save(
revision=0,
LOCAL_DNS_PUBLISHING="on",
LOCAL_ACCOUNT_BACKUPS="on",
)
self.assertContains(response, "linked receiver must be ready")
linked.return_value["nodes"][0]["release"] = "1.0.0"
response = self.save(
revision=0,
LOCAL_DNS_PUBLISHING="on",
LOCAL_ACCOUNT_BACKUPS="on",
)
self.assertRedirects(response, reverse("panel:installation"))
policy.refresh_from_db()
self.assertEqual(policy.disabled, [])
self.assertEqual(policy.revision, 1)
@override_settings(LOCAL_WEB_HTTPS=False)
def test_requires_verified_admin_and_never_enables_unconfigured_service(
self,
):
self.sign_in(verified=False)
response = self.save(revision=0)
self.assertEqual(response.status_code, 403)
self.sign_in()
response = self.save(
revision=0,
LOCAL_DNS_PUBLISHING="on",
LOCAL_ACCOUNT_BACKUPS="on",
LOCAL_WEB_HTTPS="on",
)
self.assertRedirects(response, reverse("panel:installation"))
self.assertFalse(PanelFeaturePolicy.objects.exists())
+10 -6
View File
@@ -171,6 +171,7 @@ class ServiceHealthPanelTests(TestCase):
HOSTING_PUBLIC_ADDRESSES=("192.0.2.20",), HOSTING_PUBLIC_ADDRESSES=("192.0.2.20",),
ROUNDCUBE_URL="https://webmail.example.net", ROUNDCUBE_URL="https://webmail.example.net",
ROUNDCUBE_BRIDGE_KEY="test-only-bridge-key", ROUNDCUBE_BRIDGE_KEY="test-only-bridge-key",
LOCAL_MAILBOX_CREDENTIALS=True,
) )
def test_installation_reports_configuration_to_operators(self): def test_installation_reports_configuration_to_operators(self):
url = reverse("panel:installation") url = reverse("panel:installation")
@@ -190,7 +191,10 @@ class ServiceHealthPanelTests(TestCase):
self.assertContains(response, "1.2.3") self.assertContains(response, "1.2.3")
self.assertContains(response, "Apache License 2.0") self.assertContains(response, "Apache License 2.0")
self.assertContains(response, reverse("panel:service_health")) self.assertContains(response, reverse("panel:service_health"))
features = dict(response.context["features"]) features = {
feature.label: enabled
for feature, _, enabled in response.context["features"]
}
self.assertTrue(features["Default managed DNS zones for new accounts"]) self.assertTrue(features["Default managed DNS zones for new accounts"])
self.assertTrue(features["Roundcube sign-in"]) self.assertTrue(features["Roundcube sign-in"])
self.assertNotContains(response, "test-only-bridge-key") self.assertNotContains(response, "test-only-bridge-key")
@@ -207,11 +211,11 @@ class ServiceHealthPanelTests(TestCase):
) )
self.client.force_login(self.admin) self.client.force_login(self.admin)
response = self.client.get(reverse("panel:installation")) response = self.client.get(reverse("panel:installation"))
self.assertTrue( features = {
dict(response.context["features"])[ feature.label: enabled
"Default managed DNS zones for new accounts" for feature, _, enabled in response.context["features"]
] }
) self.assertTrue(features["Default managed DNS zones for new accounts"])
self.assertContains(response, "Configure DNS defaults") self.assertContains(response, "Configure DNS defaults")
def test_view_marks_missing_and_old_observations_distinctly(self): def test_view_marks_missing_and_old_observations_distinctly(self):
+6 -1
View File
@@ -22,7 +22,7 @@ from .independent_website_views import (
IndependentWebsiteManifest, IndependentWebsiteManifest,
IndependentWebsiteOperation, IndependentWebsiteOperation,
) )
from .installation_views import InstallationView from .installation_views import FeatureConfigurationView, InstallationView
from .invitations import AcceptInvitation, ManageInvitation from .invitations import AcceptInvitation, ManageInvitation
from .mail_dns_views import MailDnsCheckView, RequestMailDnsSetup from .mail_dns_views import MailDnsCheckView, RequestMailDnsSetup
from .mail_policy_views import MailRoutingEditor, MailVacationEditor from .mail_policy_views import MailRoutingEditor, MailVacationEditor
@@ -89,6 +89,11 @@ urlpatterns = [
"service-health/", ServiceHealthView.as_view(), name="service_health" "service-health/", ServiceHealthView.as_view(), name="service_health"
), ),
path("about/", InstallationView.as_view(), name="installation"), path("about/", InstallationView.as_view(), name="installation"),
path(
"about/features/",
FeatureConfigurationView.as_view(),
name="feature_configuration",
),
path("account/role/", switch_panel_role, name="switch_panel_role"), path("account/role/", switch_panel_role, name="switch_panel_role"),
path( path(
"logins/assign-role/", "logins/assign-role/",
+115 -67
View File
@@ -93,6 +93,11 @@ from .independent_websites import (
website_actions, website_actions,
website_limit, website_limit,
) )
from .installation_features import (
default_dns_zones_allowed,
panel_feature_allowed,
panel_feature_paused,
)
from .invitations import InviteLoginForm, queue_invitation from .invitations import InviteLoginForm, queue_invitation
from .mail_policy_views import mail_policy_enabled from .mail_policy_views import mail_policy_enabled
from .models import ( from .models import (
@@ -249,7 +254,7 @@ def missing_account_setup(account, actor):
defaults = zone_defaults() defaults = zone_defaults()
options = [] options = []
if ( if (
settings.LOCAL_WEB_ACTIVATION panel_feature_allowed("LOCAL_WEB_ACTIVATION")
and actor.has_perms(ACTIVATE_WEB) and actor.has_perms(ACTIVATE_WEB)
and not account.webprovisioningplan_set.filter( and not account.webprovisioningplan_set.filter(
primary_domain=domain, activation__isnull=False primary_domain=domain, activation__isnull=False
@@ -257,16 +262,14 @@ def missing_account_setup(account, actor):
): ):
options.append(("setup_website", "Set up the primary website")) options.append(("setup_website", "Set up the primary website"))
if ( if (
settings.LOCAL_DNS_PUBLISHING default_dns_zones_allowed(defaults)
and defaults.nameservers
and defaults.addresses
and actor.has_perms((*PUBLISH_DNS, "hosting.add_hostingdnszone")) and actor.has_perms((*PUBLISH_DNS, "hosting.add_hostingdnszone"))
and not HostingDnsZone.objects.filter(domain=domain).exists() and not HostingDnsZone.objects.filter(domain=domain).exists()
): ):
options.append(("setup_dns", "Publish a Coulobre DNS zone")) options.append(("setup_dns", "Publish a Coulobre DNS zone"))
if ( if (
settings.LOCAL_MAILBOX_PROVISIONING panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING")
and settings.MANAGE_MAIL_DNS and panel_feature_allowed("MANAGE_MAIL_DNS")
and actor.has_perms(PROVISION_MAILBOX) and actor.has_perms(PROVISION_MAILBOX)
and not account.mail_domains.filter(domain=domain).exists() and not account.mail_domains.filter(domain=domain).exists()
): ):
@@ -313,7 +316,7 @@ class ExistingAccountSetup(
and bool(form["setup_email"].value()) and bool(form["setup_email"].value())
) )
or ( or (
settings.MANAGE_MAIL_DNS panel_feature_allowed("MANAGE_MAIL_DNS")
and self.account.mail_domains.filter( and self.account.mail_domains.filter(
domain=self.account.primary_domain domain=self.account.primary_domain
).exists() ).exists()
@@ -481,19 +484,12 @@ class AccountCreate(PermissionRequiredMixin, AccountEditor, CreateView):
actor = self.request.user actor = self.request.user
reseller = reseller_for_user(actor) is not None reseller = reseller_for_user(actor) is not None
defaults = zone_defaults() defaults = zone_defaults()
web = settings.LOCAL_WEB_ACTIVATION and ( web = panel_feature_allowed("LOCAL_WEB_ACTIVATION") and (
reseller or actor.has_perms(ACTIVATE_WEB) reseller or actor.has_perms(ACTIVATE_WEB)
) )
dns = ( dns = default_dns_zones_allowed(defaults) and (
settings.LOCAL_DNS_PUBLISHING
and defaults.nameservers
and defaults.addresses
and (
reseller reseller
or actor.has_perms( or actor.has_perms((*PUBLISH_DNS, "hosting.add_hostingdnszone"))
(*PUBLISH_DNS, "hosting.add_hostingdnszone")
)
)
) )
choices = { choices = {
"setup_website": (web, "Set up the primary website"), "setup_website": (web, "Set up the primary website"),
@@ -505,8 +501,8 @@ class AccountCreate(PermissionRequiredMixin, AccountEditor, CreateView):
"setup_www": (web or dns, "Include the www hostname"), "setup_www": (web or dns, "Include the www hostname"),
"setup_wildcard": (dns, "Include a wildcard (*) DNS record"), "setup_wildcard": (dns, "Include a wildcard (*) DNS record"),
"setup_email": ( "setup_email": (
settings.LOCAL_MAILBOX_PROVISIONING panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING")
and settings.MANAGE_MAIL_DNS and panel_feature_allowed("MANAGE_MAIL_DNS")
and (reseller or actor.has_perms(PROVISION_MAILBOX)), and (reseller or actor.has_perms(PROVISION_MAILBOX)),
"Set up email DNS for this domain", "Set up email DNS for this domain",
), ),
@@ -620,7 +616,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
) )
context["show_mail_queue"] = ( context["show_mail_queue"] = (
not tenant not tenant
and settings.LOCAL_MAILBOX_PROVISIONING and panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING")
and user.has_perm("hosting.view_hostingmaildomain") and user.has_perm("hosting.view_hostingmaildomain")
) )
manage_resources = reseller is not None and reseller.manage_resources manage_resources = reseller is not None and reseller.manage_resources
@@ -645,10 +641,11 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
context["primary_file_access"] = manage_files and site_is_active( context["primary_file_access"] = manage_files and site_is_active(
self.object self.object
) )
website_provisioning = panel_feature_allowed("LOCAL_WEB_ACTIVATION")
if settings.LOCAL_WEB_ACTIVATION or manage_files: if settings.LOCAL_WEB_ACTIVATION or manage_files:
websites = list(account_websites(self.object)) websites = list(account_websites(self.object))
can_manage = ( can_manage = (
settings.LOCAL_WEB_ACTIVATION website_provisioning
and not self.object.services_suspended and not self.object.services_suspended
and (tenant or user.has_perm(CHANGE_ACCOUNTS)) and (tenant or user.has_perm(CHANGE_ACCOUNTS))
and getattr(self.request, "impersonation", None) is None and getattr(self.request, "impersonation", None) is None
@@ -687,7 +684,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
): ):
context["website_storage"] = storage context["website_storage"] = storage
context["can_measure_site_storage"] = ( context["can_measure_site_storage"] = (
settings.LOCAL_WEB_ACTIVATION panel_feature_allowed("LOCAL_WEB_ACTIVATION")
and not tenant and not tenant
and user.has_perms(MEASURE_SITE_STORAGE) and user.has_perms(MEASURE_SITE_STORAGE)
) )
@@ -698,7 +695,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
if quota is not None and quota.domain == self.object.primary_domain: if quota is not None and quota.domain == self.object.primary_domain:
context["website_limit"] = quota context["website_limit"] = quota
context["can_change_site_storage_limit"] = ( context["can_change_site_storage_limit"] = (
settings.LOCAL_WEB_ACTIVATION panel_feature_allowed("LOCAL_WEB_ACTIVATION")
and not tenant and not tenant
and user.has_perms(CHANGE_SITE_STORAGE_LIMIT) and user.has_perms(CHANGE_SITE_STORAGE_LIMIT)
) )
@@ -721,7 +718,9 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
) )
context["website_php_job"] = php_job context["website_php_job"] = php_job
context["can_change_php_settings"] = ( context["can_change_php_settings"] = (
not tenant and user.has_perms(CHANGE_SITE_PHP_SETTINGS) website_provisioning
and not tenant
and user.has_perms(CHANGE_SITE_PHP_SETTINGS)
) )
version_job = getattr(self.object, "php_version_job", None) version_job = getattr(self.object, "php_version_job", None)
if ( if (
@@ -734,7 +733,8 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
) )
context["website_php_version_job"] = version_job context["website_php_version_job"] = version_job
context["can_change_php_version"] = ( context["can_change_php_version"] = (
can_change_php_version(self.request) website_provisioning
and can_change_php_version(self.request)
and not self.object.services_suspended and not self.object.services_suspended
and ( and (
version_job is None version_job is None
@@ -746,13 +746,16 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
.select_related("reservation") .select_related("reservation")
.order_by("reservation__domain") .order_by("reservation__domain")
) )
if not tenant and user.has_perms(MANAGE_WEBSITE_ALIASES): if (
website_provisioning
and not tenant
and user.has_perms(MANAGE_WEBSITE_ALIASES)
):
context["manage_website_aliases"] = True context["manage_website_aliases"] = True
context["can_add_website_alias"] = site_active context["can_add_website_alias"] = site_active
context["can_enable_alias_https"] = ( context["can_enable_alias_https"] = panel_feature_allowed(
settings.LOCAL_WEB_HTTPS "LOCAL_WEB_HTTPS"
and user.has_perms(ENABLE_WEB_HTTPS) ) and user.has_perms(ENABLE_WEB_HTTPS)
)
context["export_backup_manifest"] = not tenant and user.has_perms( context["export_backup_manifest"] = not tenant and user.has_perms(
EXPORT_BACKUP_MANIFEST EXPORT_BACKUP_MANIFEST
) )
@@ -766,7 +769,12 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
): ):
can_view_mailboxes = user.has_perm(VIEW_MAILBOXES) can_view_mailboxes = user.has_perm(VIEW_MAILBOXES)
context["show_account_backups"] = True context["show_account_backups"] = True
context["can_retry_offsite"] = user.has_perms(RETRY_OFFSITE_BACKUP) context["can_request_account_backup"] = panel_feature_allowed(
"LOCAL_ACCOUNT_BACKUPS"
)
context["can_retry_offsite"] = panel_feature_allowed(
"OFFSITE_BACKUP_DESTINATIONS"
) and user.has_perms(RETRY_OFFSITE_BACKUP)
context["manage_backup_retention"] = ( context["manage_backup_retention"] = (
settings.LOCAL_BACKUP_RETENTION settings.LOCAL_BACKUP_RETENTION
and user.has_perms(MANAGE_BACKUP_RETENTION) and user.has_perms(MANAGE_BACKUP_RETENTION)
@@ -799,9 +807,10 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
or can_view_mailboxes or can_view_mailboxes
): ):
context["account_backup_schedule"] = schedule context["account_backup_schedule"] = schedule
context["edit_account_backup_schedule"] = user.has_perms( context["edit_account_backup_schedule"] = (
MANAGE_BACKUP_SCHEDULE schedule is not None
) or context["can_request_account_backup"]
) and user.has_perms(MANAGE_BACKUP_SCHEDULE)
context["manage_sftp"] = ( context["manage_sftp"] = (
settings.LOCAL_WEB_SFTP settings.LOCAL_WEB_SFTP
and can_manage_sftp(user) and can_manage_sftp(user)
@@ -831,7 +840,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
context["automatic_database_provisioning"] = ( context["automatic_database_provisioning"] = (
automatic_resource_provisioning( automatic_resource_provisioning(
user, user,
settings.LOCAL_DATABASE_PROVISIONING, panel_feature_allowed("LOCAL_DATABASE_PROVISIONING"),
PROVISION_DATABASE, PROVISION_DATABASE,
) )
) )
@@ -840,8 +849,8 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
not tenant and user.has_perms(PROVISION_DATABASE) not tenant and user.has_perms(PROVISION_DATABASE)
): ):
context["manage_database_provisioning"] = True context["manage_database_provisioning"] = True
context["local_database_enabled"] = ( context["local_database_enabled"] = panel_feature_allowed(
settings.LOCAL_DATABASE_PROVISIONING "LOCAL_DATABASE_PROVISIONING"
) )
context["databases"] = databases context["databases"] = databases
if tenant or user.has_perm(VIEW_DNS_ZONES): if tenant or user.has_perm(VIEW_DNS_ZONES):
@@ -851,15 +860,17 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
"publication__manifest" "publication__manifest"
) )
context["tenant_dns_editing"] = True context["tenant_dns_editing"] = True
context["tenant_dns_publishing"] = ( context["tenant_dns_publishing"] = panel_feature_allowed(
settings.LOCAL_DNS_PUBLISHING "LOCAL_DNS_PUBLISHING"
) )
if not tenant and user.has_perms(PUBLISH_DNS): if not tenant and user.has_perms(PUBLISH_DNS):
zone_list = zone_list.select_related("publication").defer( zone_list = zone_list.select_related("publication").defer(
"publication__manifest" "publication__manifest"
) )
context["manage_dns_publishing"] = True context["manage_dns_publishing"] = True
context["local_dns_enabled"] = settings.LOCAL_DNS_PUBLISHING context["local_dns_enabled"] = panel_feature_allowed(
"LOCAL_DNS_PUBLISHING"
)
zones = list(zone_list) zones = list(zone_list)
context["dns_zones"] = zones context["dns_zones"] = zones
context["dns_zone_records"] = [ context["dns_zone_records"] = [
@@ -876,11 +887,15 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
context["has_primary_zone"] = primary_zone is not None context["has_primary_zone"] = primary_zone is not None
if primary_zone is None: if primary_zone is None:
context["dns_readiness"] = "No managed zone" context["dns_readiness"] = "No managed zone"
if not tenant and settings.LOCAL_DNS_PUBLISHING: if not tenant and panel_feature_allowed(
"LOCAL_DNS_PUBLISHING"
):
try: try:
draft = default_dns_zone( draft = default_dns_zone(
self.object, self.object,
managed_mail=settings.MANAGE_MAIL_DNS managed_mail=panel_feature_allowed(
"MANAGE_MAIL_DNS"
)
and self.object.mail_domains.filter( and self.object.mail_domains.filter(
domain=self.object.primary_domain domain=self.object.primary_domain
).exists(), ).exists(),
@@ -904,7 +919,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
context["automatic_mailbox_provisioning"] = ( context["automatic_mailbox_provisioning"] = (
automatic_resource_provisioning( automatic_resource_provisioning(
user, user,
settings.LOCAL_MAILBOX_PROVISIONING, panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING"),
PROVISION_MAILBOX, PROVISION_MAILBOX,
) )
) )
@@ -929,8 +944,8 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
not tenant and user.has_perms(PROVISION_MAILBOX) not tenant and user.has_perms(PROVISION_MAILBOX)
): ):
context["manage_mailbox_provisioning"] = True context["manage_mailbox_provisioning"] = True
context["local_mailbox_enabled"] = ( context["local_mailbox_enabled"] = panel_feature_allowed(
settings.LOCAL_MAILBOX_PROVISIONING "LOCAL_MAILBOX_PROVISIONING"
) )
context["change_mailbox_quota"] = ( context["change_mailbox_quota"] = (
not tenant and user.has_perms(CHANGE_MAILBOX_QUOTA) not tenant and user.has_perms(CHANGE_MAILBOX_QUOTA)
@@ -1002,7 +1017,7 @@ class SiteStorageLimitEdit(
template_name = "hosting/site_storage_limit_form.html" template_name = "hosting/site_storage_limit_form.html"
def dispatch(self, request, *args, **kwargs): def dispatch(self, request, *args, **kwargs):
if not settings.LOCAL_WEB_ACTIVATION: if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"):
raise Http404 raise Http404
return super().dispatch(request, *args, **kwargs) return super().dispatch(request, *args, **kwargs)
@@ -1051,7 +1066,7 @@ class SitePhpSettingsEdit(
template_name = "hosting/site_php_settings_form.html" template_name = "hosting/site_php_settings_form.html"
def dispatch(self, request, *args, **kwargs): def dispatch(self, request, *args, **kwargs):
if not settings.LOCAL_WEB_ACTIVATION: if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"):
raise Http404 raise Http404
return super().dispatch(request, *args, **kwargs) return super().dispatch(request, *args, **kwargs)
@@ -1098,7 +1113,7 @@ class SitePhpVersionEdit(PermissionRequiredMixin, FormView):
template_name = "hosting/site_php_version_form.html" template_name = "hosting/site_php_version_form.html"
def dispatch(self, request, *args, **kwargs): def dispatch(self, request, *args, **kwargs):
if not settings.LOCAL_WEB_ACTIVATION: if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"):
raise Http404 raise Http404
return super().dispatch(request, *args, **kwargs) return super().dispatch(request, *args, **kwargs)
@@ -1160,7 +1175,7 @@ class WebsiteAliasEditor(OperatorOnlyMixin, PermissionRequiredMixin, FormView):
template_name = "hosting/website_alias_form.html" template_name = "hosting/website_alias_form.html"
def dispatch(self, request, *args, **kwargs): def dispatch(self, request, *args, **kwargs):
if not settings.LOCAL_WEB_ACTIVATION: if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"):
raise Http404 raise Http404
return super().dispatch(request, *args, **kwargs) return super().dispatch(request, *args, **kwargs)
@@ -1214,9 +1229,9 @@ class WebsiteAliasAction(WebsiteAliasEditor):
) )
def can_enable_https(self): def can_enable_https(self):
return settings.LOCAL_WEB_HTTPS and self.request.user.has_perms( return panel_feature_allowed(
ENABLE_WEB_HTTPS "LOCAL_WEB_HTTPS"
) ) and self.request.user.has_perms(ENABLE_WEB_HTTPS)
def has_permission(self): def has_permission(self):
if not super().has_permission(): if not super().has_permission():
@@ -1259,7 +1274,7 @@ class RequestSiteStorageMeasurement(
permission_required = MEASURE_SITE_STORAGE permission_required = MEASURE_SITE_STORAGE
def post(self, request, pk): def post(self, request, pk):
if not settings.LOCAL_WEB_ACTIVATION: if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"):
raise Http404 raise Http404
try: try:
queue_site_storage_measurement(pk) queue_site_storage_measurement(pk)
@@ -1305,7 +1320,7 @@ class RequestAccountBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
permission_required = MANAGE_ACCOUNT_BACKUPS permission_required = MANAGE_ACCOUNT_BACKUPS
def post(self, request, pk): def post(self, request, pk):
if not settings.LOCAL_ACCOUNT_BACKUPS: if not panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS"):
raise Http404 raise Http404
include_mailboxes = request.POST.get("include_mail") == "1" include_mailboxes = request.POST.get("include_mail") == "1"
if include_mailboxes: if include_mailboxes:
@@ -1354,7 +1369,9 @@ class AccountBackupArchiveList(
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super().get_context_data(account=self.account, **kwargs) context = super().get_context_data(account=self.account, **kwargs)
user = self.request.user user = self.request.user
context["can_retry_offsite"] = user.has_perms(RETRY_OFFSITE_BACKUP) context["can_retry_offsite"] = panel_feature_allowed(
"OFFSITE_BACKUP_DESTINATIONS"
) and user.has_perms(RETRY_OFFSITE_BACKUP)
context["manage_backup_retention"] = ( context["manage_backup_retention"] = (
settings.LOCAL_BACKUP_RETENTION settings.LOCAL_BACKUP_RETENTION
and user.has_perms(MANAGE_BACKUP_RETENTION) and user.has_perms(MANAGE_BACKUP_RETENTION)
@@ -1378,7 +1395,9 @@ class RetryOffsiteBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
permission_required = RETRY_OFFSITE_BACKUP permission_required = RETRY_OFFSITE_BACKUP
def post(self, request, pk, backup_pk): def post(self, request, pk, backup_pk):
if not settings.LOCAL_ACCOUNT_BACKUPS: if not settings.LOCAL_ACCOUNT_BACKUPS or not panel_feature_allowed(
"OFFSITE_BACKUP_DESTINATIONS"
):
raise Http404 raise Http404
account = get_object_or_404(HostingAccount, pk=pk) account = get_object_or_404(HostingAccount, pk=pk)
backup = get_object_or_404( backup = get_object_or_404(
@@ -1689,6 +1708,8 @@ class EditAccountBackupSchedule(
def get_initial(self): def get_initial(self):
schedule = getattr(self.account, "backup_schedule", None) schedule = getattr(self.account, "backup_schedule", None)
if schedule is None: if schedule is None:
if not panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS"):
raise Http404
return { return {
"enabled": True, "enabled": True,
"frequency": AccountBackupSchedule.Frequency.DAILY, "frequency": AccountBackupSchedule.Frequency.DAILY,
@@ -1711,6 +1732,15 @@ class EditAccountBackupSchedule(
return super().get_context_data(account=self.account, **kwargs) return super().get_context_data(account=self.account, **kwargs)
def form_valid(self, form): def form_valid(self, form):
if (
form.cleaned_data["enabled"]
and not self.get_initial()["enabled"]
and not panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS")
):
form.add_error(
"enabled", "New backup requests are paused in the panel."
)
return self.form_invalid(form)
try: try:
save_backup_schedule( save_backup_schedule(
self.account.pk, self.account.pk,
@@ -1977,7 +2007,7 @@ class ResourceRequestCreate(PermissionRequiredMixin, CreateView):
def auto_provision(self): def auto_provision(self):
return automatic_resource_provisioning( return automatic_resource_provisioning(
self.request.user, self.request.user,
getattr(settings, self.provisioning_setting), panel_feature_allowed(self.provisioning_setting),
self.provisioning_permissions, self.provisioning_permissions,
) )
@@ -2070,7 +2100,7 @@ class ResourceProvisioningRequest(PermissionRequiredMixin, View):
) )
def post(self, request, pk): def post(self, request, pk):
if not getattr(settings, self.enabled_setting): if not panel_feature_allowed(self.enabled_setting):
raise Http404 raise Http404
queryset = self.queryset.all() queryset = self.queryset.all()
if self.reseller is not None: if self.reseller is not None:
@@ -2141,7 +2171,7 @@ class DnsZoneCreate(OperatorOnlyMixin, DnsZoneEditor):
try: try:
draft = default_dns_zone( draft = default_dns_zone(
self.account, self.account,
managed_mail=settings.MANAGE_MAIL_DNS managed_mail=panel_feature_allowed("MANAGE_MAIL_DNS")
and self.account.mail_domains.filter( and self.account.mail_domains.filter(
domain=self.domain domain=self.domain
).exists(), ).exists(),
@@ -2157,9 +2187,9 @@ class DnsZoneCreate(OperatorOnlyMixin, DnsZoneEditor):
@cached_property @cached_property
def publish_on_create(self): def publish_on_create(self):
return settings.LOCAL_DNS_PUBLISHING and self.request.user.has_perms( return panel_feature_allowed(
PUBLISH_DNS "LOCAL_DNS_PUBLISHING"
) ) and self.request.user.has_perms(PUBLISH_DNS)
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
return super().get_context_data( return super().get_context_data(
@@ -2167,6 +2197,13 @@ class DnsZoneCreate(OperatorOnlyMixin, DnsZoneEditor):
) )
def form_valid(self, form): def form_valid(self, form):
if form.cleaned_data["manage_mail_dns"] and panel_feature_paused(
"MANAGE_MAIL_DNS"
):
form.add_error(
"manage_mail_dns", "Managed mail DNS is paused in the panel."
)
return self.form_invalid(form)
try: try:
with transaction.atomic(): with transaction.atomic():
account = lock_hosting_account( account = lock_hosting_account(
@@ -2272,6 +2309,15 @@ class DnsZoneEdit(DnsZoneEditor):
def form_valid(self, form): def form_valid(self, form):
values = form.cleaned_data values = form.cleaned_data
if (
values["manage_mail_dns"]
and not self.zone.manage_mail_dns
and panel_feature_paused("MANAGE_MAIL_DNS")
):
form.add_error(
"manage_mail_dns", "Managed mail DNS is paused in the panel."
)
return self.form_invalid(form)
serial = values["serial"] serial = values["serial"]
if all( if all(
getattr(self.zone, field) == value getattr(self.zone, field) == value
@@ -2344,7 +2390,7 @@ class RequestDnsPublication(PermissionRequiredMixin, View):
return super().has_permission() return super().has_permission()
def post(self, request, pk): def post(self, request, pk):
if not settings.LOCAL_DNS_PUBLISHING: if not panel_feature_allowed("LOCAL_DNS_PUBLISHING"):
raise Http404 raise Http404
try: try:
zone = queue_dns_publication( zone = queue_dns_publication(
@@ -2569,10 +2615,12 @@ class PlanDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
return super().get_context_data( return super().get_context_data(
manage_activation=not is_tenant(user) manage_activation=not is_tenant(user)
and user.has_perms(ACTIVATE_WEB), and user.has_perms(ACTIVATE_WEB),
local_activation_enabled=settings.LOCAL_WEB_ACTIVATION, local_activation_enabled=panel_feature_allowed(
"LOCAL_WEB_ACTIVATION"
),
manage_https=not is_tenant(user) manage_https=not is_tenant(user)
and user.has_perms(ENABLE_WEB_HTTPS), and user.has_perms(ENABLE_WEB_HTTPS),
local_https_enabled=settings.LOCAL_WEB_HTTPS, local_https_enabled=panel_feature_allowed("LOCAL_WEB_HTTPS"),
**kwargs, **kwargs,
) )
@@ -2584,7 +2632,7 @@ class RequestWebActivation(
permission_required = ACTIVATE_WEB permission_required = ACTIVATE_WEB
def post(self, request, *args, **kwargs): def post(self, request, *args, **kwargs):
if not settings.LOCAL_WEB_ACTIVATION: if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"):
raise Http404 raise Http404
plan = self.get_object() plan = self.get_object()
if not plan.can_export: if not plan.can_export:
@@ -2610,7 +2658,7 @@ class RequestWebHTTPS(
permission_required = ENABLE_WEB_HTTPS permission_required = ENABLE_WEB_HTTPS
def post(self, request, *args, **kwargs): def post(self, request, *args, **kwargs):
if not settings.LOCAL_WEB_HTTPS: if not panel_feature_allowed("LOCAL_WEB_HTTPS"):
raise Http404 raise Http404
plan = self.get_object() plan = self.get_object()
if not plan.can_enable_https: if not plan.can_enable_https:
+3 -3
View File
@@ -1,7 +1,6 @@
from urllib.parse import urlencode from urllib.parse import urlencode
from django import forms from django import forms
from django.conf import settings
from django.contrib.auth.mixins import PermissionRequiredMixin from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.http import Http404, StreamingHttpResponse from django.http import Http404, StreamingHttpResponse
@@ -22,6 +21,7 @@ from coulobre.website_files import (
from .access import TenantScopeMixin, is_tenant from .access import TenantScopeMixin, is_tenant
from .independent_websites import active_websites from .independent_websites import active_websites
from .installation_features import panel_feature_allowed
from .models import HostingAccount from .models import HostingAccount
from .resource_requests import require_active_services from .resource_requests import require_active_services
from .sftp import site_is_active from .sftp import site_is_active
@@ -34,7 +34,7 @@ UNAVAILABLE = "The website files service is unavailable. Try again later."
def can_manage_website_files(request): def can_manage_website_files(request):
user = request.user user = request.user
return ( return (
settings.WEB_FILE_MANAGER panel_feature_allowed("WEB_FILE_MANAGER")
and getattr(request, "impersonation", None) is None and getattr(request, "impersonation", None) is None
and (is_tenant(user) or user.has_perms(MANAGE_FILES)) and (is_tenant(user) or user.has_perms(MANAGE_FILES))
) )
@@ -75,7 +75,7 @@ class WebsiteFilesView(
permission_required = MANAGE_FILES permission_required = MANAGE_FILES
def dispatch(self, request, *args, **kwargs): def dispatch(self, request, *args, **kwargs):
if not settings.WEB_FILE_MANAGER: if not panel_feature_allowed("WEB_FILE_MANAGER"):
raise Http404 raise Http404
return super().dispatch(request, *args, **kwargs) return super().dispatch(request, *args, **kwargs)
+3 -3
View File
@@ -1,5 +1,4 @@
from django import forms from django import forms
from django.conf import settings
from django.contrib.auth.mixins import PermissionRequiredMixin from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.db import transaction from django.db import transaction
@@ -18,6 +17,7 @@ from coulobre.website_job import MAX_JOB_COMMAND_LENGTH, validate_command
from .access import TenantScopeMixin, is_tenant from .access import TenantScopeMixin, is_tenant
from .independent_websites import check_actor from .independent_websites import check_actor
from .installation_features import panel_feature_allowed
from .models import HostingAccount from .models import HostingAccount
from .resource_requests import lock_hosting_account from .resource_requests import lock_hosting_account
from .website_job_schedule import next_website_run from .website_job_schedule import next_website_run
@@ -33,7 +33,7 @@ MANAGE_JOBS = ("hosting.view_hostingaccount", "hosting.manage_website_jobs")
def can_manage_website_jobs(request): def can_manage_website_jobs(request):
user = request.user user = request.user
return ( return (
settings.WEBSITE_JOBS panel_feature_allowed("WEBSITE_JOBS")
and getattr(request, "impersonation", None) is None and getattr(request, "impersonation", None) is None
and (is_tenant(user) or user.has_perms(MANAGE_JOBS)) and (is_tenant(user) or user.has_perms(MANAGE_JOBS))
) )
@@ -104,7 +104,7 @@ class WebsiteJobAccountView(
permission_required = MANAGE_JOBS permission_required = MANAGE_JOBS
def dispatch(self, request, *args, **kwargs): def dispatch(self, request, *args, **kwargs):
if not settings.WEBSITE_JOBS: if not panel_feature_allowed("WEBSITE_JOBS"):
raise Http404 raise Http404
return super().dispatch(request, *args, **kwargs) return super().dispatch(request, *args, **kwargs)
+1
View File
@@ -91,6 +91,7 @@ MIDDLEWARE = [
"django.contrib.messages.middleware.MessageMiddleware", "django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware",
"coulobre.hosting.panel_roles.PanelRoleMiddleware", "coulobre.hosting.panel_roles.PanelRoleMiddleware",
"coulobre.hosting.installation_features.FeaturePolicyMiddleware",
"coulobre.hosting.impersonation.CustomerImpersonationMiddleware", "coulobre.hosting.impersonation.CustomerImpersonationMiddleware",
] ]