Improve panel workflows for hosting, HTTPS, and mail

This commit is contained in:
parkel committed 2026-12-04 03:43:29 +01:00
1 parent 84173c67d3
commit 328e1cd94a
30 files changed
+1267 -102

No files matched your search

+22 -8
View File
@@ -1177,7 +1177,7 @@ When creating an account, select the services it should use. The website
option queues the Apache configuration. A new managed website with an empty option queues the Apache configuration. A new managed website with an empty
web root gets a neutral starter page unless you skip it during setup or web root gets a neutral starter page unless you skip it during setup or
activation. Already provisioned sites are not changed by an upgrade, and activation. Already provisioned sites are not changed by an upgrade, and
the starter page never replaces existing files. Replace or remove the the branded starter page never replaces existing files. Replace or remove the
generated `index.html` when you publish manually. Managed WordPress generated `index.html` when you publish manually. Managed WordPress
installation can replace an unmodified starter page automatically. installation can replace an unmodified starter page automatically.
Coulobre DNS can publish the apex, `www`, and a wildcard Coulobre DNS can publish the apex, `www`, and a wildcard
@@ -1797,13 +1797,27 @@ sudo systemctl enable --now coulobre-https-apply.socket \
coulobre-https-provisioner.service coulobre-https-provisioner.service
``` ```
On an active site's Apache preview, select **Enable HTTPS** and use Open **Manage HTTPS** in the hosting account's **Overview** or **Websites**
**Refresh status** to follow the request. This requires the **Can add tab. The hostname table shows the primary site, its existing web aliases,
website HTTPS request** permission and access to view hosting accounts and any independent websites. Select the hostnames to enable. The primary
and web provisioning plans. The worker uses the manifest's primary hostname and eligible existing aliases, such as `www`, are selected by
domain and keeps Certbot logs and credentials on the web node. If the default. Each hostname has its own request and result. A failed hostname
request fails, check the diagnostic and use **Retry HTTPS** after can be retried without reissuing certificates for working hostnames.
resolving the problem. Certbot handles later renewals.
For a new hostname, first give it a website route. Operators with alias
management access can attach it to the primary website. Use an independent
website if it should serve separate content. DNS records provide suggestions
only. Adding a website alias does not edit DNS, and a published DNS zone
does not prove that visitors or Let's Encrypt reach the correct web node.
With external DNS, update the records at the DNS provider.
Initial issuance checks the web node's configuration and uses Certbot
HTTP-01 validation for the exact hostname. If issuance fails, verify that
the public A, AAAA or CNAME routes to the intended web server and that
port 80 reaches it. See Certbot's log on the web node for more detail.
A ready Apache preview is not a deployed HTTPS virtual host. Apache
previews remain available for diagnosis, and the existing Certbot hook
continues to reload Apache after renewal.
The panel uses HTTP-01 for initial issuance. For DNS validation, obtain The panel uses HTTP-01 for initial issuance. For DNS validation, obtain
the certificate on the web node with its configured Certbot DNS plugin the certificate on the web node with its configured Certbot DNS plugin
+25 -4
View File
@@ -18,6 +18,15 @@ only use shared components available in its supported Core versions.
separate from forms so they cannot erase edits or move keyboard focus. separate from forms so they cannot erase edits or move keyboard focus.
For background jobs, show progress and the terminal result in that same For background jobs, show progress and the terminal result in that same
region. Keep recovery actions discoverable without a manual page refresh. region. Keep recovery actions discoverable without a manual page refresh.
- Show a background job beside the resource it affects without replacing
its main status. For example, a configured mailbox can also have an
import in progress. Replace the start action with a link to progress
while work is active, then link to the result or recovery workflow.
Keep refreshed content separate from inputs and focused actions.
- Account overviews should surface the current state and next step for
each service. Keep metadata compact and link to the relevant workflow
for the active role. Distinguish configuration from public reachability
or delivery. Use measured usage only when the panel has it.
- Use `.surface` for sections, `.section-heading` for ordinary section - Use `.surface` for sections, `.section-heading` for ordinary section
headers, and `.table-scroll` around tables. Keep horizontal overflow in headers, and `.table-scroll` around tables. Keep horizontal overflow in
the table wrapper and give empty or pending states an explicit label. the table wrapper and give empty or pending states an explicit label.
@@ -59,6 +68,14 @@ heading, help, fields, and actions should share a left edge.
- Prefer the shared compact type and spacing. Use [the panel stylesheet][css] - Prefer the shared compact type and spacing. Use [the panel stylesheet][css]
and its theme tokens for type, color, spacing, and focus states. Avoid and its theme tokens for type, color, spacing, and focus states. Avoid
fixed control widths, inline styles, and page-specific font sizes. fixed control widths, inline styles, and page-specific font sizes.
- Keep short forms in a compact card. For longer forms, use
`.editor-wide` and group related fields with `.editor-columns` and
`.editor-group`. Use the available width where it saves scrolling.
Groups stack in source and keyboard order when space is limited.
Use the same approach for parallel summary cards.
- For a small multi-selection, use a visible checklist with a fieldset
label and an empty state. Keep create and refresh actions beside the
picker. Refresh the options without clearing selections or other edits.
### Resource actions ### Resource actions
@@ -66,9 +83,11 @@ heading, help, fields, and actions should share a left edge.
for row-level actions such as **Import mail**, **Change password**, and for row-level actions such as **Import mail**, **Change password**, and
**Manage logins**. Use `.button danger compact` for opening a removal **Manage logins**. Use `.button danger compact` for opening a removal
workflow. Keep the final destructive confirmation visually distinct. workflow. Keep the final destructive confirmation visually distinct.
- Group row actions in a wrapping `.table-actions` or `.form-actions` - Group table actions in a wrapping `.table-actions` container. Center
container. Keep a single, full-size primary action in the page or section them vertically within the row and allow labels to wrap instead of
header when the page offers one, such as **Add mailbox**. widening the whole table. Keep overflow within `.table-scroll`.
Use `.form-actions` for submit and cancel controls, and keep a single
full-size primary action in the page or section header when applicable.
- Keep ordinary navigation, record names, and contextual help as links. An - Keep ordinary navigation, record names, and contextual help as links. An
action that opens a form, confirmation page, or download is still an action that opens a form, confirmation page, or download is still an
`<a href>` styled as a button. An action that submits the change uses a `<a href>` styled as a button. An action that submits the change uses a
@@ -88,7 +107,9 @@ Django's label association, error state, and description IDs.
Keep radio choices and multi-checkbox groups in a fieldset with a Keep radio choices and multi-checkbox groups in a fieldset with a
visible legend naming the group. visible legend naming the group.
- Keep a compound control, such as a numeric quota with **Unlimited**, - Keep a compound control, such as a numeric quota with **Unlimited**,
in its own editor row. Its checkbox still sits next to its own label. together in `.limit-control`. Keep **Unlimited** unbroken. When the
numeric input and checkbox cannot sit side by side, wrap the checkbox
and its label as one unit.
- Use the shared stylesheet in both Core and Premium. Check click and - Use the shared stylesheet in both Core and Premium. Check click and
keyboard operation, wrapping, and focus in both themes at a narrow width. keyboard operation, wrapping, and focus in both themes at a narrow width.
+3 -2
View File
@@ -18,6 +18,7 @@ from .dns_forms import zone_record_rows
from .domain_policies import managed_mail_domains, policy_for from .domain_policies import managed_mail_domains, policy_for
from .independent_websites import account_websites from .independent_websites import account_websites
from .installation_features import panel_feature_allowed from .installation_features import panel_feature_allowed
from .mailbox_imports import with_import_status
from .models import DomainServicePolicy, HostingAccount, SmtpApplication from .models import DomainServicePolicy, HostingAccount, SmtpApplication
from .resource_requests import ( from .resource_requests import (
customer_mailbox_quota_limit, customer_mailbox_quota_limit,
@@ -288,8 +289,8 @@ def domain_workspace(request, pk, page):
), ),
"mail_imap_host": settings.MAIL_IMAP_HOST, "mail_imap_host": settings.MAIL_IMAP_HOST,
"mail_submission_host": settings.MAIL_SUBMISSION_HOST, "mail_submission_host": settings.MAIL_SUBMISSION_HOST,
"mailboxes": mail_domain.mailboxes.select_related( "mailboxes": with_import_status(
"provisioning", "removal" mail_domain.mailboxes.select_related("provisioning", "removal")
) )
if mail_domain if mail_domain
else (), else (),
+14 -1
View File
@@ -13,7 +13,7 @@ from cryptography.fernet import Fernet, InvalidToken, MultiFernet
from django.conf import settings from django.conf import settings
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.db import transaction from django.db import transaction
from django.db.models import F from django.db.models import Exists, F, OuterRef
from django.utils import timezone from django.utils import timezone
from django.views.decorators.debug import sensitive_variables from django.views.decorators.debug import sensitive_variables
@@ -45,6 +45,19 @@ class BatchYieldError(Exception):
"""Yield the worker at a saved checkpoint.""" """Yield the worker at a saved checkpoint."""
def with_import_status(mailboxes):
imports = MailboxImport.objects.filter(mailbox_id=OuterRef("pk"))
return mailboxes.annotate(
import_active=Exists(imports.filter(finished_at__isnull=True)),
import_failed=Exists(
imports.filter(finished_at__isnull=False).exclude(problem="")
),
import_completed=Exists(
imports.filter(finished_at__isnull=False, problem="")
),
)
def available(): def available():
return ( return (
settings.MAILBOX_IMAP_IMPORT settings.MAILBOX_IMAP_IMPORT
@@ -22,6 +22,7 @@ class ResellerProfileForm(forms.ModelForm):
model = ResellerProfile model = ResellerProfile
fields = ("name", "account_limit", "hosting_plans") fields = ("name", "account_limit", "hosting_plans")
labels = {"hosting_plans": "Allowed hosting packages"} labels = {"hosting_plans": "Allowed hosting packages"}
widgets = {"hosting_plans": forms.CheckboxSelectMultiple}
help_texts = { help_texts = {
"account_limit": "Enter 0 to manage existing accounts only.", "account_limit": "Enter 0 to manage existing accounts only.",
} }
+1
View File
@@ -35,6 +35,7 @@ class ResellerPolicyForm(forms.ModelForm):
model = Reseller model = Reseller
fields = ("is_active", "account_limit", "hosting_plans") fields = ("is_active", "account_limit", "hosting_plans")
labels = {"hosting_plans": "Allowed hosting packages"} labels = {"hosting_plans": "Allowed hosting packages"}
widgets = {"hosting_plans": forms.CheckboxSelectMultiple}
help_texts = { help_texts = {
"account_limit": "Enter 0 to manage existing accounts only.", "account_limit": "Enter 0 to manage existing accounts only.",
"hosting_plans": ( "hosting_plans": (
@@ -0,0 +1,34 @@
"use strict";
for (const picker of document.querySelectorAll("[data-package-picker]")) {
const reload = picker.querySelector('button[name="refresh_plans"]');
if (!reload) continue;
const choices = picker.querySelector("[data-package-choices]");
const status = picker.querySelector("[data-package-refresh-status]");
reload.addEventListener("click", async (event) => {
event.preventDefault();
reload.disabled = true;
status.hidden = false;
status.textContent = "Refreshing available packages…";
try {
const response = await fetch(location.href, {cache: "no-store"});
if (!response.ok || response.redirected) throw new Error();
const page = new DOMParser().parseFromString(await response.text(), "text/html");
const updated = page.querySelector("[data-package-choices]");
if (!updated) throw new Error();
const selected = new Set(
[...choices.querySelectorAll('input[type="checkbox"]:checked')].map((input) => input.value)
);
for (const input of updated.querySelectorAll('input[type="checkbox"]')) {
input.checked = selected.has(input.value);
}
choices.replaceChildren(...updated.childNodes);
status.textContent = "Available packages refreshed.";
} catch {
status.textContent = "Could not reload packages. Try again.";
} finally {
reload.disabled = false;
}
});
}
+91 -3
View File
@@ -609,8 +609,23 @@ h3, h4, h5, h6 {
text-align: center; text-align: center;
} }
/* Keep row actions compact without pinning a wide layout to their labels. */
.table-scroll .button.compact { .table-scroll .button.compact {
white-space: nowrap; white-space: normal;
overflow-wrap: anywhere;
}
.table-scroll tr:has(.table-actions, .button.compact) > :is(th, td) {
vertical-align: middle;
}
.table-scroll .table-actions {
gap: 0.35rem;
}
.table-actions > form {
margin: 0;
min-inline-size: 0;
} }
.toolbar, .section-heading, .pagination, .form-actions { .toolbar, .section-heading, .pagination, .form-actions {
@@ -1044,12 +1059,15 @@ fieldset > div:has(> div > label > input:is([type="checkbox"], [type="radio"]))
.limit-control { .limit-control {
display: flex; display: flex;
flex-wrap: wrap;
align-items: center; align-items: center;
gap: 0.65rem; gap: 0.65rem;
} }
.limit-control input[type="number"] { .limit-control input[type="number"] {
min-width: 0; flex: 1 1 8rem;
inline-size: 8rem;
min-inline-size: 0;
} }
.limit-control input[type="checkbox"] { .limit-control input[type="checkbox"] {
@@ -1057,12 +1075,15 @@ fieldset > div:has(> div > label > input:is([type="checkbox"], [type="radio"]))
margin: 0; margin: 0;
} }
.limit-control label { .editor .limit-control label {
display: inline-flex; display: inline-flex;
flex: none;
align-items: center; align-items: center;
gap: 0.3rem; gap: 0.3rem;
margin: 0; margin: 0;
font-weight: inherit; font-weight: inherit;
white-space: nowrap;
overflow-wrap: normal;
} }
.welcome-email-preview { .welcome-email-preview {
@@ -1494,3 +1515,70 @@ fieldset > div:has(> div > label > input:is([type="checkbox"], [type="radio"]))
.hosting-node:focus .hosting-node-full { .hosting-node:focus .hosting-node-full {
display: block; display: block;
} }
.editor-wide {
max-width: 76rem;
}
.editor-intro {
max-width: 35rem;
margin-block-end: 1rem;
}
.editor-columns {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 28rem), 1fr));
gap: 1rem;
align-items: start;
}
.editor-columns > * {
min-inline-size: 0;
}
.editor .editor-group {
padding: 0.8rem;
border: 1px solid var(--line);
border-radius: var(--radius);
margin: 0;
min-inline-size: 0;
}
.editor-group legend {
padding-inline: 0.3rem;
font-weight: var(--font-weight-semibold);
}
.package-choices > div {
display: grid;
gap: 0.45rem;
}
.package-choices label {
font-weight: inherit;
}
.package-details {
display: grid;
gap: 0.25rem 0.65rem;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
min-inline-size: 12rem;
}
.package-details dd {
margin: 0;
}
.account-overview-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 20rem), 1fr));
gap: 1rem;
align-items: stretch;
}
.account-overview-grid > .editor-surface {
max-width: none;
min-inline-size: 0;
grid-template-rows: auto auto 1fr auto;
}
@@ -54,20 +54,7 @@
{% endif %} {% endif %}
<div><dt>Added</dt><dd>{{ account.created_at|date:"j M Y, H:i" }} UTC</dd></div> <div><dt>Added</dt><dd>{{ account.created_at|date:"j M Y, H:i" }} UTC</dd></div>
</dl> </dl>
<section class="surface account-overview account-content" id="overview" data-account-section tabindex="-1" aria-label="Account overview"> {% include "hosting/account_overview.html" %}
{% if offer_account_setup %}
<div class="section-heading">
<p>Some services still need setup.</p>
<a class="button primary" href="{% url 'panel:account_setup' account.pk %}">Complete hosting setup</a>
</div>
{% endif %}
<dl class="account-readiness">
{% if show_website %}<div><dt>Website</dt><dd><a href="#websites">{{ website_readiness }}</a></dd></div>{% endif %}
{% if show_website %}<div><dt>HTTPS</dt><dd><a href="#websites">{{ https_readiness }}</a></dd></div>{% endif %}
{% if is_tenant or perms.hosting.view_hostingdnszone %}<div><dt>DNS</dt><dd><a href="#domains-dns">{{ dns_readiness }}</a></dd></div>{% endif %}
{% if is_tenant or perms.hosting.view_hostingmailbox %}<div><dt>Email</dt><dd><a href="#email">{{ mail_readiness }}</a></dd></div>{% endif %}
</dl>
</section>
{% if can_change_hosting_services or service_change or can_retire_account or is_operator and perms.hosting.change_hostingaccount %} {% if can_change_hosting_services or service_change or can_retire_account or is_operator and perms.hosting.change_hostingaccount %}
<section class="account-content" id="account-management" data-account-section tabindex="-1" aria-label="Account management"> <section class="account-content" id="account-management" data-account-section tabindex="-1" aria-label="Account management">
{% if can_retire_account or is_operator and perms.hosting.change_hostingaccount %} {% if can_retire_account or is_operator and perms.hosting.change_hostingaccount %}
@@ -87,8 +74,11 @@
{% endif %} {% endif %}
{% if show_website or independent_websites or add_independent_website %} {% if show_website or independent_websites or add_independent_website %}
<section class="account-content" id="websites" data-account-section tabindex="-1" aria-label="Websites"> <section class="account-content" id="websites" data-account-section tabindex="-1" aria-label="Websites">
{% if show_website_usage or primary_file_access or manage_website_jobs or manage_sftp or manage_wordpress %} {% if may_manage_https or show_website_usage or primary_file_access or manage_website_jobs or manage_sftp or manage_wordpress %}
<div class="form-actions account-actions"> <div class="form-actions account-actions">
{% if may_manage_https %}
<a class="button secondary" href="{% url 'panel:website_https' account.pk %}">Manage HTTPS</a>
{% endif %}
{% if show_website_usage %} {% if show_website_usage %}
<a class="button secondary" href="{% url 'panel:website_usage' account.pk %}">Usage and logs</a> <a class="button secondary" href="{% url 'panel:website_usage' account.pk %}">Usage and logs</a>
{% endif %} {% endif %}
@@ -0,0 +1,49 @@
<section class="account-content live-sections" id="overview" data-account-section tabindex="-1" aria-label="Account overview">
{% if offer_account_setup %}
<section class="surface">
<header class="section-heading">
<div><h2>Finish setting up this account</h2><p class="heading-meta">Some services still need setup.</p></div>
<a class="button primary" href="{% url 'panel:account_setup' account.pk %}">Complete hosting setup</a>
</header>
</section>
{% endif %}
<div class="account-overview-grid">
{% if show_website %}
<section class="surface editor-surface editor">
<h2>Website</h2>
<p><strong>{{ website_readiness }}</strong>{% if website_storage.measured_at %} · {{ website_storage.used_bytes|filesizeformat }} used{% endif %}</p>
<p class="muted">Manage websites, aliases, and PHP settings.</p>
<div class="form-actions"><a class="button secondary compact" href="#websites">View websites</a></div>
</section>
<section class="surface editor-surface editor">
<h2>HTTPS</h2>
<p>{% if https_status.state %}<span class="status {{ https_status.state }}">{{ https_status.label }}</span>{% else %}<strong>{{ https_status.label }}</strong>{% endif %}</p>
{% if may_manage_https %}
<p class="muted">See certificate setup for the primary domain and other website hostnames.</p>
<div class="form-actions"><a class="button secondary compact" href="{% url 'panel:website_https' account.pk %}">Manage HTTPS</a></div>
{% else %}
<p class="muted">Ask your server administrator or the assigned customer to manage certificates.</p>
{% endif %}
</section>
{% endif %}
{% if is_tenant or perms.hosting.view_hostingdnszone %}
<section class="surface editor-surface editor">
<h2>Domains and DNS</h2>
<p><strong>{{ dns_readiness }}</strong></p>
<p class="muted">{% if has_primary_zone %}Zone publication does not confirm the registrar uses these nameservers.{% else %}Open DNS to check the records you need at your provider.{% endif %}</p>
<div class="form-actions"><a class="button secondary compact" href="#domains-dns">View DNS settings</a></div>
</section>
{% endif %}
{% if is_tenant or perms.hosting.view_hostingmailbox %}
<section class="surface editor-surface editor">
<h2>Email</h2>
<p>
{% if mail_readiness_style %}<span class="status {{ mail_readiness_style }}">{{ mail_readiness }}</span>{% else %}<strong>{{ mail_readiness }}</strong>{% endif %}
{% if mail_domains %} · {{ mailboxes|length }} mailbox{{ mailboxes|length|pluralize:"es" }}{% endif %}
</p>
<p class="muted">Manage mailboxes and check the domain's email DNS before routing mail here.</p>
<div class="form-actions"><a class="button secondary compact" href="#email">View email settings</a></div>
</section>
{% endif %}
</div>
</section>
@@ -2,6 +2,9 @@
{% block title %}SSL Certificates · Coulobre Panel{% endblock %} {% block title %}SSL Certificates · Coulobre Panel{% endblock %}
{% block page_title %}SSL Certificates{% endblock %} {% block page_title %}SSL Certificates{% endblock %}
{% block page_metadata %}<p class="heading-meta">{{ account.primary_domain }}</p>{% endblock %} {% block page_metadata %}<p class="heading-meta">{{ account.primary_domain }}</p>{% endblock %}
{% block page_actions %}
{% if not request.impersonation %}<a class="button secondary" href="{% url 'panel:website_https' account.pk %}">HTTPS by hostname</a>{% endif %}
{% endblock %}
{% block page_tabs %} {% block page_tabs %}
{% if sites %} {% if sites %}
<nav class="account-navigation" aria-label="Certificates"> <nav class="account-navigation" aria-label="Certificates">
@@ -57,30 +57,30 @@
<td> <td>
<div class="table-actions"> <div class="table-actions">
{% if is_reseller or is_operator and perms.hosting.change_customer %} {% if is_reseller or is_operator and perms.hosting.change_customer %}
<a class="button secondary" href="{% url 'panel:manage_invitation' 'customer' customer.pk %}">Contact and invitation</a> <a class="button secondary compact" href="{% url 'panel:manage_invitation' 'customer' customer.pk %}">Contact and invitation</a>
{% endif %} {% endif %}
{% if is_operator and perms.hosting.add_hostingaccount and perms.hosting.view_hostingaccount %} {% if is_operator and perms.hosting.add_hostingaccount and perms.hosting.view_hostingaccount %}
<a class="button secondary" href="{% url 'panel:account_create' %}?customer={{ customer.pk }}">Add hosting</a> <a class="button secondary compact" href="{% url 'panel:account_create' %}?customer={{ customer.pk }}">Add hosting</a>
{% endif %} {% endif %}
{% if perms.hosting.change_customer and not customer.user.is_staff and not customer.user.is_superuser and not customer.user.hosting_reseller %} {% if perms.hosting.change_customer and not customer.user.is_staff and not customer.user.is_superuser and not customer.user.hosting_reseller %}
<form method="post" action="{% url 'panel:customer_access' customer.pk %}{% querystring %}"> <form method="post" action="{% url 'panel:customer_access' customer.pk %}{% querystring %}">
{% csrf_token %} {% csrf_token %}
{% if customer.user.is_active %} {% if customer.user.is_active %}
<button class="button secondary" type="submit" name="access" value="suspend" aria-label="Suspend sign-in for {{ customer }}">Suspend sign-in</button> <button class="button secondary compact" type="submit" name="access" value="suspend" aria-label="Suspend sign-in for {{ customer }}">Suspend sign-in</button>
{% else %} {% else %}
<button class="button secondary" type="submit" name="access" value="restore" aria-label="Restore sign-in for {{ customer }}">Restore sign-in</button> <button class="button secondary compact" type="submit" name="access" value="restore" aria-label="Restore sign-in for {{ customer }}">Restore sign-in</button>
{% endif %} {% endif %}
</form> </form>
{% endif %} {% endif %}
{% if can_impersonate and customer.may_be_impersonated %} {% if can_impersonate and customer.may_be_impersonated %}
<form method="post" action="{% url 'panel:impersonation_start' customer.pk %}"> <form method="post" action="{% url 'panel:impersonation_start' customer.pk %}">
{% csrf_token %} {% csrf_token %}
<button class="button secondary" type="submit" aria-label="View as customer {{ customer }}">View as customer</button> <button class="button secondary compact" type="submit" aria-label="View as customer {{ customer }}">View as customer</button>
</form> </form>
{% if can_start_support %} {% if can_start_support %}
<form method="post" action="{% url 'panel:impersonation_write_start' customer.pk %}"> <form method="post" action="{% url 'panel:impersonation_write_start' customer.pk %}">
{% csrf_token %} {% csrf_token %}
<button class="button secondary" type="submit" aria-label="Start support with write access for {{ customer }}">Support with write access</button> <button class="button secondary compact" type="submit" aria-label="Start support with write access for {{ customer }}">Support with write access</button>
</form> </form>
{% endif %} {% endif %}
{% endif %} {% endif %}
@@ -67,7 +67,7 @@
Storage limit change {{ mailbox.provisioning.state }} Storage limit change {{ mailbox.provisioning.state }}
{% else %}{{ mailbox.provisioning.state|default:"Requested"|capfirst }}{% endif %} {% else %}{{ mailbox.provisioning.state|default:"Requested"|capfirst }}{% endif %}
</td> </td>
<td><div class="form-actions"> <td><div class="table-actions">
{% if mailbox.provisioning.state == 'configured' and not mailbox.removal %} {% if mailbox.provisioning.state == 'configured' and not mailbox.removal %}
{% if show_mailbox_credentials %} {% if show_mailbox_credentials %}
<a class="button secondary compact" href="{% url 'panel:mailbox_credentials' mailbox.pk %}">Credentials</a> <a class="button secondary compact" href="{% url 'panel:mailbox_credentials' mailbox.pk %}">Credentials</a>
@@ -0,0 +1,13 @@
<div class="plan-field">
<div class="plan-field-heading">
{{ field.label_tag }}
{% if field.help_text %}
<details class="field-help" data-field-help>
<summary aria-label="Help for {{ field.label }}">?</summary>
<p id="{{ field.auto_id }}_helptext">{{ field.help_text }}</p>
</details>
{% endif %}
</div>
{{ field.errors }}
{{ field }}
</div>
@@ -6,25 +6,25 @@
<a class="quiet-link" href="{% url 'panel:hosting_plans' %}">← Hosting packages</a> <a class="quiet-link" href="{% url 'panel:hosting_plans' %}">← Hosting packages</a>
{% endblock %} {% endblock %}
{% block page_content %} {% block page_content %}
<section class="surface editor-surface"> <section class="surface editor-surface editor-wide">
<form method="post" class="editor"> <form method="post" class="editor">
{% csrf_token %} {% csrf_token %}
{{ form.non_field_errors }} {{ form.non_field_errors }}
{% for field in form.visible_fields %} <div class="editor-columns">
<div class="plan-field"> {% for field in package_identity %}
<div class="plan-field-heading"> {% include "hosting/hosting_package_field.html" with field=field only %}
{{ field.label_tag }}
{% if field.help_text %}
<details class="field-help" data-field-help>
<summary aria-label="Help for {{ field.label }}">?</summary>
<p id="{{ field.auto_id }}_helptext">{{ field.help_text }}</p>
</details>
{% endif %}
</div>
{{ field.errors }}
{{ field }}
</div>
{% endfor %} {% endfor %}
</div>
<div class="editor-columns">
{% for title, fields in package_sections %}
<fieldset class="editor-group editor">
<legend>{{ title }}</legend>
{% for field in fields %}
{% include "hosting/hosting_package_field.html" with field=field only %}
{% endfor %}
</fieldset>
{% endfor %}
</div>
{% for field in form.hidden_fields %}{{ field }}{% endfor %} {% for field in form.hidden_fields %}{{ field }}{% endfor %}
<div class="form-actions"> <div class="form-actions">
<button class="button primary" type="submit">{{ submit_label }}</button> <button class="button primary" type="submit">{{ submit_label }}</button>
@@ -4,8 +4,21 @@
{% endif %} {% endif %}
{% else %} {% else %}
{% if mailbox_import_enabled and mailbox.provisioning.state == "configured" %} {% if mailbox_import_enabled and mailbox.provisioning.state == "configured" %}
<span class="table-actions" data-live-status="mailbox-import-{{ mailbox.pk }}">
{% if mailbox.import_active %}
<span class="status pending" data-live-pending>Import in progress</span>
<a class="button secondary compact" href="{% url 'panel:mailbox_import' mailbox.pk %}" aria-label="View import progress for {{ mailbox }}">View import progress</a>
{% elif mailbox.import_failed %}
<span class="status failed">Import needs attention</span>
<a class="button secondary compact" href="{% url 'panel:mailbox_import' mailbox.pk %}" aria-label="Review import for {{ mailbox }}">Review import</a>
{% elif mailbox.import_completed %}
<span class="status ready">Import complete</span>
<a class="button secondary compact" href="{% url 'panel:mailbox_import' mailbox.pk %}" aria-label="View import result for {{ mailbox }}">View import result</a>
{% else %}
<a class="button secondary compact" href="{% url 'panel:mailbox_import' mailbox.pk %}" aria-label="Import mail into {{ mailbox }}">Import mail</a> <a class="button secondary compact" href="{% url 'panel:mailbox_import' mailbox.pk %}" aria-label="Import mail into {{ mailbox }}">Import mail</a>
{% endif %} {% endif %}
</span>
{% endif %}
{% if show_mailbox_rotation and mailbox.provisioning.state == "configured" %} {% if show_mailbox_rotation and mailbox.provisioning.state == "configured" %}
<a class="button secondary compact" href="{% url 'panel:mailbox_credential_rotation' mailbox.pk %}" aria-label="Change password for {{ mailbox }}">Change password</a> <a class="button secondary compact" href="{% url 'panel:mailbox_credential_rotation' mailbox.pk %}" aria-label="Change password for {{ mailbox }}">Change password</a>
{% endif %} {% endif %}
@@ -1,21 +1,21 @@
{% extends "hosting/base.html" %} {% extends "hosting/workspace_page.html" %}
{% block title %}Remove mailbox · Coulobre Panel{% endblock %} {% block title %}Remove mailbox · Coulobre Panel{% endblock %}
{% block content %} {% block page_title %}Remove mailbox{% endblock %}
<header class="page-heading"> {% block page_metadata %}<p class="heading-meta domain">{{ mailbox }}</p>{% endblock %}
<h1>Remove mailbox</h1> {% block page_content %}
<p class="heading-meta">{{ mailbox }}</p> <section class="surface editor-surface" aria-label="Mailbox removal">
</header>
<section class="surface form-panel">
{% if removal.problem %}<p role="alert">{{ removal.problem }}</p>{% endif %}
{% if removal and not removal.problem %} {% if removal and not removal.problem %}
<p>Mailbox removal {{ removal.state }}.</p> <div class="editor">
<a class="button secondary" href="{{ return_url }}">Back to mailboxes</a> <p role="status">Mailbox removal {{ removal.state }}.</p>
<div class="form-actions"><a class="button secondary" href="{{ return_url }}">Back to mailboxes</a></div>
</div>
{% else %} {% else %}
<p>Stop delivery and sign-in for this address. An operator can recover the archived messages on the mail server.</p> <form method="post" class="editor">
<form method="post">
{% csrf_token %} {% csrf_token %}
{{ form.as_p }} {% if removal.problem %}<p class="notice" role="alert">{{ removal.problem }}</p>{% endif %}
<p class="muted">Stop delivery and sign-in for this address. An operator can recover the archived messages on the mail server.</p>
{{ form.as_div }}
<div class="form-actions"> <div class="form-actions">
<button class="button danger" type="submit">{% if removal %}Retry removal{% else %}Remove mailbox{% endif %}</button> <button class="button danger" type="submit">{% if removal %}Retry removal{% else %}Remove mailbox{% endif %}</button>
<a class="button secondary" href="{{ return_url }}">Cancel</a> <a class="button secondary" href="{{ return_url }}">Cancel</a>
@@ -0,0 +1,21 @@
{% if policy.hosting_plans %}
<fieldset class="editor editor-group" data-package-picker{% if policy.hosting_plans.help_text or policy.hosting_plans.errors %} aria-describedby="{% if policy.hosting_plans.help_text %}{{ policy.hosting_plans.auto_id }}_helptext{% endif %}{% if policy.hosting_plans.errors %}{% if policy.hosting_plans.help_text %} {% endif %}{{ policy.hosting_plans.auto_id }}_error{% endif %}"{% endif %}>
<legend>{{ policy.hosting_plans.label }}</legend>
{% if policy.hosting_plans.help_text %}<p id="{{ policy.hosting_plans.auto_id }}_helptext" class="muted">{{ policy.hosting_plans.help_text }}</p>{% endif %}
{{ policy.hosting_plans.errors }}
<div class="package-choices" data-package-choices>
{% if policy.hosting_plans.field.queryset %}
{{ policy.hosting_plans }}
{% else %}
<p class="muted">No hosting packages are available.</p>
{% endif %}
</div>
{% if can_add_hosting_plan %}
<div class="form-actions">
<a class="button secondary compact" href="{% url 'panel:hosting_plan_create' %}" target="_blank" rel="noopener">Create package (new tab)</a>
<button class="button secondary compact" type="submit" name="refresh_plans" value="1" formnovalidate>Reload packages</button>
</div>
<p class="muted" role="status" data-package-refresh-status hidden></p>
{% endif %}
</fieldset>
{% endif %}
@@ -1,11 +1,43 @@
{% extends "hosting/workspace_page.html" %} {% extends "hosting/workspace_page.html" %}
{% block title %}Hosting packages · Coulobre Panel{% endblock %} {% block title %}Hosting packages · Coulobre Panel{% endblock %}
{% block page_title %}Hosting packages{% endblock %} {% block page_title %}Hosting packages{% endblock %}
{% block page_metadata %}<p class="heading-meta">Compare the limits of packages available for your hosting accounts.</p>{% endblock %}
{% block page_content %} {% block page_content %}
<section class="surface"> {% if plans %}
<ul class="workspace-list"> <section class="surface" aria-label="Available hosting packages">
{% for plan in plans %}<li><strong>{{ plan.name }}</strong>{% if plan.description %}<p>{{ plan.description }}</p>{% endif %}</li> <div class="table-scroll">
{% empty %}<li>No packages have been made available to you.</li>{% endfor %} <table class="package-summary">
</ul> <thead><tr>
<th scope="col">Package</th><th scope="col">Website storage</th><th scope="col">Websites</th>
<th scope="col">Mailboxes</th><th scope="col">Databases</th><th scope="col">Details</th>
</tr></thead>
<tbody>
{% for plan in plans %}
<tr>
<th scope="row">{{ plan.name }}{% if plan.description %}<p class="heading-meta">{{ plan.description }}</p>{% endif %}</th>
<td>{% if plan.website_storage_limit_mib is not None %}{{ plan.website_storage_limit_mib }} MiB{% else %}Unlimited{% endif %}</td>
<td>{{ plan.website_limit|default_if_none:"Unlimited" }}</td>
<td>{% if plan.mailbox_limit == 0 %}Disabled{% else %}{{ plan.mailbox_limit|default_if_none:"Unlimited" }}{% endif %}</td>
<td>{% if plan.database_limit == 0 %}Disabled{% else %}{{ plan.database_limit|default_if_none:"Unlimited" }}{% endif %}</td>
<td>
<details>
<summary>Package details<span class="visually-hidden"> for {{ plan.name }}</span></summary>
<dl class="package-details">
<dt>Storage per mailbox</dt><dd>{% if plan.mailbox_quota_mib is not None %}{{ plan.mailbox_quota_mib }} MiB{% else %}Unlimited{% endif %}</dd>
<dt>Scheduled tasks</dt><dd>{% if plan.website_job_limit == 0 %}Disabled{% else %}{{ plan.website_job_limit|default_if_none:"Unlimited" }}{% endif %}</dd>
<dt>Catch-all mail</dt><dd>{{ plan.allow_mail_catchall|yesno:"Allowed,Not allowed" }}</dd>
<dt>External mail forwarding</dt><dd>{{ plan.allow_external_mail_forwarding|yesno:"Allowed,Not allowed" }}</dd>
<dt>PHP series</dt><dd>{{ plan.php_versions|default:"Installed stable versions" }}</dd>
</dl>
</details>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</section> </section>
{% else %}
<p class="surface section-text">No packages have been made available to you.</p>
{% endif %}
{% endblock %} {% endblock %}
@@ -0,0 +1,9 @@
<div class="editor-columns">
<fieldset class="editor editor-group">
<legend>Account access</legend>
{{ policy.non_field_errors }}
{% if policy.is_active %}<div>{{ policy.is_active.as_field_group }}</div>{% endif %}
<div>{{ policy.account_limit.as_field_group }}</div>
</fieldset>
{% include "hosting/manager_package_picker.html" %}
</div>
@@ -31,11 +31,12 @@
</section> </section>
{% else %} {% else %}
<section class="surface"><div class="table-scroll"><table> <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> <thead><tr><th scope="col">Website</th><th scope="col">Account</th><th scope="col">Last known issuer</th><th scope="col">Expiry</th><th scope="col">Actions</th></tr></thead>
<tbody>{% for domain, account, job in sites %}<tr> <tbody>{% for domain, account, job in sites %}<tr>
<th scope="row">{{ domain }}</th><td><a href="{{ account.get_absolute_url }}">{{ account.name }}</a></td> <th scope="row">{{ domain }}</th><td><a href="{{ account.get_absolute_url }}">{{ account.name }}</a></td>
<td>{{ job.certificate.issuer|default:"Unavailable" }}</td><td>{{ job.certificate.not_after|default:"Unavailable" }}</td> <td>{{ job.certificate.issuer|default:"Unavailable" }}</td><td>{{ job.certificate.not_after|default:"Unavailable" }}</td>
</tr>{% empty %}<tr><td colspan="4">No active websites on this page.</td></tr>{% endfor %}</tbody> <td><div class="table-actions"><a class="button secondary compact" href="{% url 'panel:website_https' account.pk %}">Manage HTTPS</a></div></td>
</tr>{% empty %}<tr><td colspan="5">No active websites on this page.</td></tr>{% endfor %}</tbody>
</table></div>{% include "hosting/pagination.html" %}</section> </table></div>{% include "hosting/pagination.html" %}</section>
{% endif %} {% endif %}
{% endblock %} {% endblock %}
@@ -6,9 +6,9 @@
<a class="quiet-link" href="{% if reseller %}{{ reseller.get_absolute_url }}{% else %}{% url 'panel:resellers' %}{% endif %}">← {% if reseller %}{{ reseller }}{% else %}Managers{% endif %}</a> <a class="quiet-link" href="{% if reseller %}{{ reseller.get_absolute_url }}{% else %}{% url 'panel:resellers' %}{% endif %}">← {% if reseller %}{{ reseller }}{% else %}Managers{% endif %}</a>
{% endblock %} {% endblock %}
{% block page_content %} {% block page_content %}
<section class="surface editor-surface"> <section class="surface editor-surface editor-wide">
{% if profiles %} {% if profiles %}
<form method="get" class="editor"> <form method="get" class="editor editor-intro">
<div> <div>
<label for="manager-profile">Manager package</label> <label for="manager-profile">Manager package</label>
<select id="manager-profile" name="profile"> <select id="manager-profile" name="profile">
@@ -23,20 +23,13 @@
<form method="post" class="editor reseller-editor"> <form method="post" class="editor reseller-editor">
{% csrf_token %} {% csrf_token %}
{% if login_form %} {% if login_form %}
<fieldset class="editor"> <fieldset class="editor editor-group editor-intro">
<legend>Login</legend> <legend>Login</legend>
{{ form.as_div }} {{ form.as_div }}
</fieldset> </fieldset>
<fieldset class="editor"> {% include "hosting/manager_policy_fields.html" with policy=policy_form %}
<legend>Access and packages</legend>
{{ policy_form.as_div }}
</fieldset>
{% else %} {% else %}
{{ form.as_div }} {% include "hosting/manager_policy_fields.html" with policy=form %}
{% endif %}
{% if can_add_hosting_plan %}
<p><a href="{% url 'panel:hosting_plan_create' %}" target="_blank" rel="noopener">Create a hosting package</a>. The package opens in a new tab.</p>
<button class="button secondary" type="submit" name="refresh_plans" value="1" formnovalidate>Reload available packages</button>
{% endif %} {% endif %}
<div class="form-actions"> <div class="form-actions">
<button class="button primary" type="submit">{{ submit_label }}</button> <button class="button primary" type="submit">{{ submit_label }}</button>
@@ -45,4 +38,5 @@
</form> </form>
</section> </section>
<script src="{% panel_asset 'hosting/limit-controls.js' %}" defer></script> <script src="{% panel_asset 'hosting/limit-controls.js' %}" defer></script>
<script src="{% panel_asset 'hosting/package-picker.js' %}" defer></script>
{% endblock %} {% endblock %}
@@ -6,11 +6,23 @@
<a class="quiet-link" href="{% url 'panel:reseller_profiles' %}">← Manager packages</a> <a class="quiet-link" href="{% url 'panel:reseller_profiles' %}">← Manager packages</a>
{% endblock %} {% endblock %}
{% block page_content %} {% block page_content %}
<section class="surface editor-surface"> <section class="surface editor-surface editor-wide">
<form method="post" class="editor"> <form method="post" class="editor">
{% csrf_token %} {% csrf_token %}
{{ form.as_div }} <div class="editor-columns">
<fieldset class="editor editor-group">
<legend>Manager package</legend>
{{ form.non_field_errors }}
<div>{{ form.name.as_field_group }}</div>
<div>{{ form.account_limit.as_field_group }}</div>
<div>{{ form.use_as_default.as_field_group }}</div>
</fieldset>
{% include "hosting/manager_package_picker.html" with policy=form %}
</div>
<div class="form-actions">
<button type="submit" class="button primary">Save package</button> <button type="submit" class="button primary">Save package</button>
<a class="button secondary" href="{% url 'panel:reseller_profiles' %}">Cancel</a>
</div>
</form> </form>
</section> </section>
<script src="{% panel_asset 'hosting/limit-controls.js' %}" defer></script> <script src="{% panel_asset 'hosting/limit-controls.js' %}" defer></script>
@@ -0,0 +1,107 @@
{% extends "hosting/workspace_page.html" %}
{% block title %}Website HTTPS · Coulobre Panel{% endblock %}
{% block page_title %}Website HTTPS{% endblock %}
{% block page_metadata %}<p class="heading-meta domain">{{ account.primary_domain }}</p>{% endblock %}
{% block page_actions %}
<a class="button secondary" href="{{ account.get_absolute_url }}#websites">Back to websites</a>
{% endblock %}
{% block page_content %}
<div class="live-sections">
{% if not enabled %}
<p class="notice">Managed website certificates are unavailable on this installation.</p>
{% elif account.services_suspended %}
<p class="notice">Resume this hosting account before changing HTTPS.</p>
{% endif %}
{% if customer_aliases %}
<p class="notice">Ask your hosting provider to enable HTTPS for website aliases.</p>
{% endif %}
<section class="surface" aria-labelledby="https-hostnames" data-live-status="https-hostnames">
<header class="section-heading">
<div>
<h2 id="https-hostnames">Website hostnames</h2>
<p class="heading-meta">Configured means Coulobre has installed HTTPS. It does not confirm that public DNS points here.</p>
</div>
{% if is_customer %}<a class="button secondary" href="{% url 'panel:customer_certificates' account.pk %}">Certificate details</a>{% endif %}
</header>
<div class="table-scroll">
<table>
<thead><tr><th scope="col">Hostname</th><th scope="col">Website route</th><th scope="col">HTTPS</th></tr></thead>
<tbody>
{% for row in rows %}
<tr>
<th scope="row" class="domain">{{ row.domain }}</th>
<td>{{ row.route }}</td>
<td>
{% if row.status.state %}
<span class="status {{ row.status.state }}"{% if row.status.pending %} data-live-pending{% endif %}>{{ row.status.label }}</span>
{% else %}{{ row.status.label }}{% endif %}
{% if row.status.state == "failed" %}
<p class="heading-meta">Check that public DNS points to this website and that port 80 is reachable before retrying.</p>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</section>
{% if enabled and not account.services_suspended %}
<div{% if not selection.is_bound %} data-live-status="https-selection"{% endif %}>
{% if has_selectable or selection.errors %}
<section class="surface editor-surface" aria-labelledby="https-enable">
<form method="post" class="editor">
{% csrf_token %}
<header>
<h2 id="https-enable">Enable HTTPS</h2>
<p class="muted">Select the hostnames to enable. Each needs public DNS pointing to its website and a reachable HTTP route for Let's Encrypt. Existing certificates on other hostnames are left alone.</p>
</header>
{{ selection.as_div }}
<div class="form-actions">
<button class="button primary" type="submit" name="action" value="issue">Enable HTTPS for selected hostnames</button>
</div>
</form>
</section>
{% endif %}
</div>
{% endif %}
{% if candidates or may_attach %}
<section class="surface editor-surface{% if candidates and may_attach %} editor-wide{% endif %}" aria-labelledby="https-other-hostnames">
<div class="editor">
<header>
<h2 id="https-other-hostnames">Other hostnames</h2>
<p class="muted">A DNS record does not create a website route. Attach a hostname to the primary website before enabling HTTPS, or set it up as an independent website to serve separate content.</p>
</header>
{% if candidates %}
<div class="table-scroll">
<table>
<thead><tr><th scope="col">Hostname in managed DNS</th><th scope="col">Record types</th></tr></thead>
<tbody>
{% for domain, types in candidates %}<tr><th scope="row" class="domain">{{ domain }}</th><td>{{ types }}</td></tr>{% endfor %}
</tbody>
</table>
</div>
{% endif %}
{% if may_attach %}
<form method="post" class="editor">
{% csrf_token %}
<div>
{{ attach.domain.label_tag }}
{{ attach.domain.errors }}
<input type="text" name="{{ attach.domain.html_name }}" id="{{ attach.domain.id_for_label }}" maxlength="253" value="{{ attach.domain.value|default_if_none:'' }}" list="https-dns-names" aria-describedby="https-domain-help{% if attach.domain.errors %} {{ attach.domain.auto_id }}_error{% endif %}"{% if attach.domain.errors %} aria-invalid="true"{% endif %} required>
<datalist id="https-dns-names">
{% for domain, types in candidates %}<option value="{{ domain }}">{% endfor %}
</datalist>
<p class="muted" id="https-domain-help">Attaching a hostname does not edit DNS. After its website route becomes active, reopen this page to include it in your selection.</p>
</div>
<div class="form-actions">
<button class="button secondary" type="submit" name="action" value="attach">Attach to primary website</button>
</div>
</form>
{% else %}
<p class="muted">Ask your hosting provider to attach a hostname that is not already mapped.</p>
{% endif %}
</div>
</section>
{% endif %}
</div>
{% endblock %}
@@ -99,6 +99,39 @@ class MailboxImportTests(TestCase):
) )
self.assertContains(response, f">{label}</a>") self.assertContains(response, f">{label}</a>")
def test_mailbox_rows_reflect_only_their_own_import(self):
self.sign_in(self.customer)
account = self.mailbox.mail_domain.account
unrelated = HostingMailbox.objects.create(
mail_domain=self.mailbox.mail_domain, local_part="unrelated"
)
MailboxProvisioning.objects.create(
mailbox=unrelated, finished_at=timezone.now()
)
job = self.queue()
email = reverse("panel:domain_workspace", args=[account.pk, "email"])
for phase in ("checking", "copying", "waiting", "retry"):
job.phase = phase
job.save(update_fields=["phase"])
for path in (email, account.get_absolute_url()):
response = self.client.get(path)
self.assertContains(response, "Import in progress", count=1)
self.assertContains(response, "View import progress", count=2)
self.assertContains(
response,
f'data-live-status="mailbox-import-{unrelated.pk}"',
)
self.assertEqual(self.client.get(self.url()).status_code, 200)
self.assertEqual(MailboxImport.objects.count(), 1)
job.finished_at = timezone.now()
job.problem = "Check your source password."
job.save(update_fields=["finished_at", "problem"])
self.assertContains(self.client.get(email), "Import needs attention")
job.problem = ""
job.save(update_fields=["problem"])
self.assertContains(self.client.get(email), "Import complete")
self.assertNotContains(self.client.get(email), "Import in progress")
def test_only_the_owner_and_authorized_operator_can_start_import(self): def test_only_the_owner_and_authorized_operator_can_start_import(self):
self.sign_in(self.stranger) self.sign_in(self.stranger)
self.assertEqual(self.client.get(self.url()).status_code, 404) self.assertEqual(self.client.get(self.url()).status_code, 404)
@@ -0,0 +1,237 @@
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from django_otp.plugins.otp_totp.models import TOTPDevice
from .models import (
Customer,
HostingAccount,
HostingDnsZone,
IndependentWebsite,
Reseller,
WebActivation,
WebHTTPS,
WebProvisioningPlan,
WebsiteAlias,
WebsiteCertificateJob,
WebsiteDomain,
)
from .tasks import apply_certificate_job
@override_settings(LOCAL_WEB_ACTIVATION=True, LOCAL_WEB_HTTPS=True)
class WebsiteHttpsTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.operator = users.create_superuser("operator")
cls.customer = users.create_user("customer")
cls.outsider = users.create_user("outsider")
cls.manager = users.create_user("manager")
for user in (cls.operator, cls.customer, cls.outsider, cls.manager):
TOTPDevice.objects.create(user=user, name="Panel")
manager = Reseller.objects.create(user=cls.manager)
owner = Customer.objects.create(user=cls.customer)
other_owner = Customer.objects.create(user=cls.outsider)
cls.account = HostingAccount.objects.create(
name="Hosted",
primary_domain="hosted.example",
customer=owner,
reseller=manager,
)
other = HostingAccount.objects.create(
name="Other", primary_domain="other.example", customer=other_owner
)
WebsiteDomain.objects.create(
account=other, domain="reserved.hosted.example"
)
cls.plan = WebProvisioningPlan.objects.create(
account=cls.account,
primary_domain=cls.account.primary_domain,
apache_config="Installed",
completed_at=timezone.now(),
)
WebActivation.objects.create(plan=cls.plan, finished_at=timezone.now())
cls.alias = WebsiteAlias.objects.create(
reservation=WebsiteDomain.objects.create(
account=cls.account, domain="www.hosted.example"
),
primary_domain=cls.account.primary_domain,
finished_at=timezone.now(),
http_active=True,
https_active=True,
)
cls.secondary = IndependentWebsite.objects.create(
reservation=WebsiteDomain.objects.create(
account=cls.account, domain="site.hosted.example"
),
activated=True,
finished_at=timezone.now(),
)
HostingDnsZone.objects.create(
account=cls.account,
domain="hosted.example",
nameservers=["ns1.example.net"],
responsible_name="hostmaster.hosted.example",
addresses=[
{"name": "new.hosted.example", "address": "192.0.2.9"},
{"name": "v6.hosted.example", "address": "2001:db8::9"},
{"name": "mail.hosted.example", "address": "192.0.2.9"},
{"name": "*.hosted.example", "address": "192.0.2.9"},
],
mx_records=[
{
"name": "hosted.example",
"priority": 10,
"exchange": "mail.hosted.example",
}
],
extra_records=[
{
"name": "alias.hosted.example",
"record_type": "CNAME",
"value": "hosted.example.",
}
],
)
def sign_in(self, user):
self.client.force_login(user)
session = self.client.session
session["otp_device_id"] = TOTPDevice.objects.get(
user=user
).persistent_id
session.save()
def url(self):
return reverse("panel:website_https", args=[self.account.pk])
def test_operator_sees_routes_and_can_attach_explicit_names_only(self):
self.sign_in(self.operator)
response = self.client.get(self.url())
self.assertContains(response, "new.hosted.example")
self.assertContains(response, "v6.hosted.example")
self.assertContains(response, "alias.hosted.example")
self.assertNotContains(response, "mail.hosted.example")
self.assertNotContains(response, "*.hosted.example")
self.assertEqual(
response.context["selection"].initial["hostnames"],
["hosted.example"],
)
for hostname in ("outside.example", "reserved.hosted.example"):
self.assertContains(
self.client.post(
self.url(), {"action": "attach", "domain": hostname}
),
'class="errorlist',
)
self.assertEqual(
self.client.post(
self.url(),
{"action": "attach", "domain": "external.hosted.example"},
).status_code,
302,
)
alias = WebsiteAlias.objects.get(
reservation__domain="external.hosted.example"
)
self.assertFalse(alias.http_active)
self.assertFalse(WebsiteCertificateJob.objects.exists())
alias.http_active = True
alias.finished_at = timezone.now()
alias.save(update_fields=["http_active", "finished_at"])
self.assertIn(
"external.hosted.example",
self.client.get(self.url())
.context["selection"]
.initial["hostnames"],
)
def test_failure_is_per_host_and_existing_alias_stays_intact(self):
self.sign_in(self.operator)
response = self.client.post(
self.url(),
{
"action": "issue",
"hostnames": ["hosted.example", "site.hosted.example"],
},
)
self.assertEqual(response.status_code, 302)
primary, secondary = WebsiteCertificateJob.objects.order_by("pk")
with patch(
"coulobre.hosting.node_client.apply_on_local_node",
side_effect=[
ValueError("The HTTP-01 route is not reachable."),
{"certificate": {"installed": True}},
],
):
apply_certificate_job(primary.pk)
apply_certificate_job(secondary.pk)
primary.refresh_from_db()
secondary.refresh_from_db()
self.assertEqual(primary.state, "failed")
self.assertEqual(secondary.state, "configured")
self.alias.refresh_from_db()
self.assertTrue(self.alias.https_active)
response = self.client.get(self.url())
self.assertContains(response, "Needs attention")
self.assertContains(
response, "that port 80 is reachable before retrying"
)
self.assertEqual(
response.context["selection"].initial["hostnames"],
["hosted.example"],
)
def test_legacy_https_on_older_preview_is_not_reissued(self):
WebHTTPS.objects.create(plan=self.plan, finished_at=timezone.now())
WebProvisioningPlan.objects.create(
account=self.account,
primary_domain=self.account.primary_domain,
apache_config="New preview",
completed_at=timezone.now(),
)
self.sign_in(self.operator)
response = self.client.get(self.url())
rows = {row.domain: row for row in response.context["rows"]}
self.assertFalse(rows["hosted.example"].selectable)
self.assertEqual(rows["hosted.example"].status.label, "Configured")
overview = self.client.get(self.account.get_absolute_url())
self.assertContains(overview, self.url())
self.assertEqual(overview.context["website_readiness"], "Configured")
def test_post_is_scoped_and_keeps_existing_alias_permissions(self):
self.sign_in(self.outsider)
self.assertEqual(self.client.get(self.url()).status_code, 404)
self.sign_in(self.manager)
self.assertEqual(self.client.get(self.url()).status_code, 403)
self.sign_in(self.customer)
self.assertEqual(
self.client.post(
self.url(),
{"action": "attach", "domain": "test.hosted.example"},
).status_code,
403,
)
for hostname in ("www.hosted.example", "other.example"):
self.assertContains(
self.client.post(
self.url(), {"action": "issue", "hostnames": [hostname]}
),
"Select a valid choice",
)
self.assertFalse(WebsiteCertificateJob.objects.exists())
self.assertEqual(
self.client.post(
self.url(),
{"action": "issue", "hostnames": ["hosted.example"]},
).status_code,
302,
)
self.assertEqual(
WebsiteCertificateJob.objects.get().requested_customer_id,
self.account.customer_id,
)
+2
View File
@@ -118,6 +118,7 @@ from .smtp_applications import smtp_applications
from .system_backup_views import SystemBackupView from .system_backup_views import SystemBackupView
from .update_views import ChangelogView, UpdateView from .update_views import ChangelogView, UpdateView
from .website_file_views import WebsiteFilesView from .website_file_views import WebsiteFilesView
from .website_https_views import website_https
from .website_job_views import WebsiteJobEditor, WebsiteJobList from .website_job_views import WebsiteJobEditor, WebsiteJobList
from .website_usage_views import WebsiteUsageView from .website_usage_views import WebsiteUsageView
from .wordpress_views import AccountWordPressView from .wordpress_views import AccountWordPressView
@@ -187,6 +188,7 @@ urlpatterns = [
name="http_defaults", name="http_defaults",
), ),
path("ssl/", operator_certificates, name="operator_certificates"), path("ssl/", operator_certificates, name="operator_certificates"),
path("accounts/<int:pk>/https/", website_https, name="website_https"),
path( path(
"hosting/<int:pk>/certificates/", "hosting/<int:pk>/certificates/",
customer_certificates, customer_certificates,
+80 -13
View File
@@ -108,6 +108,7 @@ from .invitations import InviteLoginForm, queue_invitation
from .limit_forms import add_unlimited_fields from .limit_forms import add_unlimited_fields
from .mail_domain_alias_views import may_manage_aliases from .mail_domain_alias_views import may_manage_aliases
from .mail_policy_views import mail_policy_enabled from .mail_policy_views import mail_policy_enabled
from .mailbox_imports import with_import_status
from .mailbox_removal import can_remove_mailbox from .mailbox_removal import can_remove_mailbox
from .models import ( from .models import (
AccountBackupJob, AccountBackupJob,
@@ -192,6 +193,12 @@ from .website_aliases import (
queue_website_alias, queue_website_alias,
) )
from .website_file_views import can_manage_website_files from .website_file_views import can_manage_website_files
from .website_https_views import (
ENABLE_WEB_HTTPS,
MANAGE_WEBSITE_ALIASES,
may_manage_https,
primary_https_status,
)
from .website_job_views import can_access_website_jobs from .website_job_views import can_access_website_jobs
from .workspace_onboarding import onboarding_context from .workspace_onboarding import onboarding_context
@@ -240,8 +247,6 @@ COMPONENT_RESTORE_PERMISSIONS = {
), ),
} }
ACTIVATE_WEB = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webactivation") ACTIVATE_WEB = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webactivation")
MANAGE_WEBSITE_ALIASES = (VIEW_ACCOUNTS, "hosting.manage_website_aliases")
ENABLE_WEB_HTTPS = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webhttps")
PROVISION_DATABASE = ( PROVISION_DATABASE = (
VIEW_ACCOUNTS, VIEW_ACCOUNTS,
VIEW_DATABASES, VIEW_DATABASES,
@@ -1009,14 +1014,32 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
context["mail_domains"] = self.object.mail_domains.select_related( context["mail_domains"] = self.object.mail_domains.select_related(
"assignment" "assignment"
).order_by("domain") ).order_by("domain")
assignments = [
getattr(domain, "assignment", None)
for domain in context["mail_domains"]
]
states = {
assignment.state for assignment in assignments if assignment
}
if "failed" in states:
context["mail_readiness"] = "Mail domain setup blocked"
context["mail_readiness_style"] = "failed"
elif states.intersection({"queued", "running"}):
context["mail_readiness"] = "Setting up mail"
context["mail_readiness_style"] = "pending"
else:
context["mail_readiness"] = ( context["mail_readiness"] = (
"Check email setup" "Mail domain configured"
if context["mail_domains"] if "configured" in states
else "Mail domain added"
if assignments
else "Not set up" else "Not set up"
) )
mailboxes = HostingMailbox.objects.filter( mailboxes = with_import_status(
HostingMailbox.objects.filter(
mail_domain__account=self.object mail_domain__account=self.object
).select_related("mail_domain", "provisioning", "removal") ).select_related("mail_domain", "provisioning", "removal")
)
context["can_remove_mailbox"] = can_remove_mailbox(self.request) context["can_remove_mailbox"] = can_remove_mailbox(self.request)
context["can_manage_smtp_apps"] = smtp_applications_available( context["can_manage_smtp_apps"] = smtp_applications_available(
self.request self.request
@@ -1076,21 +1099,31 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
"manage_sftp", "manage_sftp",
) )
) )
if context["show_website"]: context["may_manage_https"] = may_manage_https(
plan = ( self.request, self.object
self.object.webprovisioningplan_set.filter(
primary_domain=self.object.primary_domain
) )
.select_related("activation", "https") if context["show_website"]:
plans = self.object.webprovisioningplan_set.filter(
primary_domain=self.object.primary_domain
).select_related("activation")
plan = (
plans.filter(
activation__finished_at__isnull=False,
activation__problem="",
)
.order_by("-pk")
.first()
)
if plan is None:
plan = (
plans.filter(activation__isnull=False)
.order_by("-pk") .order_by("-pk")
.first() .first()
) )
context["website_readiness"] = provisioning_readiness( context["website_readiness"] = provisioning_readiness(
getattr(plan, "activation", None), "Not set up", "Configured" getattr(plan, "activation", None), "Not set up", "Configured"
) )
context["https_readiness"] = provisioning_readiness( context["https_status"] = primary_https_status(self.object)
getattr(plan, "https", None), "Not set up", "Configured"
)
return context return context
@@ -2821,6 +2854,40 @@ class HostingPlanEditor:
template_name = "hosting/hosting_plan_form.html" template_name = "hosting/hosting_plan_form.html"
success_url = reverse_lazy("panel:hosting_plans") success_url = reverse_lazy("panel:hosting_plans")
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
form = context["form"]
context["package_identity"] = (form["name"], form["description"])
context["package_sections"] = (
(
"Websites and storage",
(
form["website_limit"],
form["website_storage_limit_mib"],
form["website_job_limit"],
),
),
(
"Email",
(
form["mailbox_limit"],
form["mailbox_quota_mib"],
form["allow_mail_catchall"],
form["allow_external_mail_forwarding"],
),
),
("Databases", (form["database_limit"],)),
(
"PHP",
tuple(
form[name]
for name in self.fields
if name.startswith("php_")
),
),
)
return context
def get_form_kwargs(self): def get_form_kwargs(self):
kwargs = super().get_form_kwargs() kwargs = super().get_form_kwargs()
if "data" in kwargs: if "data" in kwargs:
+408
View File
@@ -0,0 +1,408 @@
"""Manage HTTPS for the websites and aliases on one hosting account."""
from dataclasses import dataclass
from django import forms
from django.contrib import messages
from django.core.exceptions import PermissionDenied, ValidationError
from django.db import transaction
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_http_methods
from coulobre.domain_names import canonical_domain
from .access import customer_for_user, is_tenant
from .certificate_views import account_certificate_sites, queue_certificate
from .dns_forms import record_rows
from .independent_websites import account_websites
from .installation_features import panel_feature_allowed
from .models import HostingAccount, WebsiteAlias
from .resource_requests import lock_hosting_account, require_active_services
from .sftp import site_is_active
from .website_aliases import queue_alias_operation, queue_website_alias
ENABLE_WEB_HTTPS = (
"hosting.view_hostingaccount",
"hosting.view_webprovisioningplan",
"hosting.add_webhttps",
)
MANAGE_WEBSITE_ALIASES = (
"hosting.view_hostingaccount",
"hosting.manage_website_aliases",
)
@dataclass(frozen=True)
class HostStatus:
state: str
label: str
pending: bool = False
CONFIGURED = HostStatus("ready", "Configured")
NOT_CONFIGURED = HostStatus("", "Not configured")
NEEDS_ATTENTION = HostStatus("failed", "Needs attention")
NOT_MAPPED = HostStatus("", "Not mapped to a website")
def may_manage_https(request, account):
if getattr(request, "impersonation", None):
return False
customer = customer_for_user(request.user)
if customer is not None:
return account.customer_id == customer.pk
return not is_tenant(request.user) and request.user.has_perms(
ENABLE_WEB_HTTPS
)
def job_status(job):
if job is None:
return NOT_CONFIGURED
return {
"queued": HostStatus("pending", "Queued", True),
"running": HostStatus("pending", "In progress", True),
"failed": NEEDS_ATTENTION,
"configured": CONFIGURED,
}[job.state]
def website_status(account, site, *, configured=False, fallback=None):
jobs = account.certificate_jobs.filter(site=site.manifest())
latest = jobs.exclude(action="inspect").order_by("-pk").first()
evidence = jobs.exclude(certificate={}).order_by("-pk").first()
installed = (
evidence.certificate.get("installed", False)
if evidence is not None
else configured
)
if latest and latest.finished_at is None:
return job_status(latest)
if installed:
return CONFIGURED
if latest and latest.problem:
return NEEDS_ATTENTION
if evidence is not None:
return NOT_CONFIGURED
return job_status(fallback)
def primary_https_status(account, site=None):
if site is None:
site = account_certificate_sites(account).get(account.primary_domain)
if site is None:
return NOT_CONFIGURED
plans = account.webprovisioningplan_set.filter(
primary_domain=site.domain, https__isnull=False
).select_related("https")
installed = plans.filter(
https__finished_at__isnull=False, https__problem=""
).exists()
latest = plans.order_by("-https__requested_at", "-pk").first()
if latest and latest.https.finished_at is None:
return job_status(latest.https)
return website_status(
account,
site,
configured=installed,
fallback=latest.https if latest else None,
)
@dataclass(frozen=True)
class HostRow:
domain: str
route: str
status: HostStatus
selectable: bool
def routed_hosts(account):
sites = account_certificate_sites(account)
rows = {}
independent = {
website.reservation.domain: website
for website in account_websites(account).filter(
retired_at__isnull=True
)
}
for domain, site in sites.items():
website = independent.get(domain)
primary = domain == account.primary_domain
status = (
primary_https_status(account, site)
if primary
else website_status(
account,
site,
configured=website.https_enabled,
fallback=(
website
if website.operation == website.Operation.HTTPS
else None
),
)
)
rows[domain] = HostRow(
domain,
"Primary website" if primary else "Independent website",
status,
not status.pending and status != CONFIGURED,
)
for domain in {account.primary_domain, *independent} - rows.keys():
rows[domain] = HostRow(
domain, "Website not active", NOT_CONFIGURED, False
)
aliases = {
alias.reservation.domain: alias
for alias in WebsiteAlias.objects.filter(
reservation__account=account,
primary_domain=account.primary_domain,
).select_related("reservation")
}
for domain, alias in aliases.items():
if alias.finished_at is None:
status = job_status(alias)
elif alias.https_active:
status = CONFIGURED
elif alias.problem:
status = NEEDS_ATTENTION
else:
status = NOT_CONFIGURED
rows[domain] = HostRow(
domain,
"Primary website alias"
if alias.http_active
else "Alias not active",
status,
alias.http_active
and alias.finished_at is not None
and not alias.https_active
and alias.operation != WebsiteAlias.Operation.REMOVE,
)
return rows, sites, aliases
def mail_hostnames(records):
return {
row["value"].split(maxsplit=1)[1].rstrip(".").lower()
for row in records
if row["type"] == "MX"
}
def dns_candidates(records, existing, mx_hosts):
candidates = {}
for row in records:
name = row["name"].rstrip(".").lower()
if (
row["type"] not in {"A", "AAAA", "CNAME"}
or name in existing
or name in mx_hosts
):
continue
try:
name = canonical_domain(name)
except ValueError:
continue
candidates.setdefault(name, set()).add(row["type"])
return [
(domain, ", ".join(sorted(types)))
for domain, types in sorted(candidates.items())
]
def alias_within_account(account, name):
zones = account.dns_zones.values_list("domain", flat=True)
return any(
name != account.primary_domain
and (name == zone or name.endswith(f".{zone}"))
for zone in (account.primary_domain, *zones)
)
class HttpsSelectionForm(forms.Form):
hostnames = forms.MultipleChoiceField(
label="Hostnames",
widget=forms.CheckboxSelectMultiple,
)
def __init__(self, selectable, preferred, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["hostnames"].choices = [
(name, name) for name in selectable
]
self.initial["hostnames"] = [
name for name in selectable if name in preferred
]
class AttachHostnameForm(forms.Form):
domain = forms.CharField(label="Hostname", max_length=253)
def clean_domain(self):
try:
return canonical_domain(self.cleaned_data["domain"])
except ValueError as error:
raise ValidationError(str(error)) from error
def request_https(request, account, selected, customer_id):
count = 0
declined = []
with transaction.atomic():
account = lock_hosting_account(account.pk, customer_id)
require_active_services(account)
rows, sites, aliases = routed_hosts(account)
for domain in dict.fromkeys(selected):
if (
domain not in rows
or not rows[domain].selectable
or customer_id is not None
and domain in aliases
):
declined.append(
f"{domain}: This hostname is no longer selectable."
)
continue
try:
if domain in aliases:
queue_alias_operation(
account.pk,
aliases[domain].pk,
WebsiteAlias.Operation.HTTPS,
allow_https=True,
)
else:
queue_certificate(
account,
sites[domain],
request.user,
"issue",
customer_id,
)
except ValidationError as error:
declined.append(f"{domain}: {' '.join(error.messages)}")
else:
count += 1
return count, declined
@never_cache
@require_http_methods(("GET", "HEAD", "POST"))
def website_https(request, pk):
customer = customer_for_user(request.user)
accounts = HostingAccount.objects.filter(retired_at__isnull=True)
if customer is not None:
accounts = accounts.filter(customer=customer)
account = get_object_or_404(accounts, pk=pk)
if not may_manage_https(request, account):
raise PermissionDenied
enabled = panel_feature_allowed("LOCAL_WEB_HTTPS")
may_attach = (
customer is None
and request.user.has_perms(MANAGE_WEBSITE_ALIASES)
and panel_feature_allowed("LOCAL_WEB_ACTIVATION")
and site_is_active(account)
and not account.services_suspended
)
rows, _, aliases = routed_hosts(account)
records = [
row
for zone in account.dns_zones.all()
for row in record_rows(zone.spec)
]
mx_hosts = mail_hostnames(records)
preferred = {
domain
for domain in aliases
if domain not in mx_hosts
and domain.split(".")[0] not in {"mail", "autoconfig", "autodiscover"}
}
rows = sorted(
rows.values(),
key=lambda row: (row.domain != account.primary_domain, row.domain),
)
selectable = [
row.domain
for row in rows
if row.selectable
and enabled
and not account.services_suspended
and (customer is None or row.domain not in aliases)
]
action = request.POST.get("action") if request.method == "POST" else None
selection = HttpsSelectionForm(
selectable,
{account.primary_domain, *preferred},
request.POST if action == "issue" else None,
)
attach = AttachHostnameForm(request.POST if action == "attach" else None)
if request.method == "POST":
if action == "issue" and enabled:
if selection.is_valid():
try:
count, declined = request_https(
request,
account,
selection.cleaned_data["hostnames"],
customer.pk if customer else None,
)
except HostingAccount.DoesNotExist:
raise Http404 from None
except ValidationError as error:
selection.add_error(None, " ".join(error.messages))
else:
if count:
messages.success(
request,
"HTTPS requests queued.",
)
for problem in declined:
messages.error(request, problem)
return redirect("panel:website_https", pk)
elif action == "attach" and may_attach:
if attach.is_valid():
domain = attach.cleaned_data["domain"]
try:
with transaction.atomic():
current = lock_hosting_account(pk, None)
require_active_services(current)
if not alias_within_account(current, domain):
raise ValidationError(
"Enter a hostname under a domain on "
"this hosting account."
)
queue_website_alias(pk, domain)
except HostingAccount.DoesNotExist:
raise Http404 from None
except ValidationError as error:
attach.add_error("domain", " ".join(error.messages))
else:
messages.success(
request,
"Hostname queued. Enable HTTPS after its "
"website route is active.",
)
return redirect("panel:website_https", pk)
else:
raise PermissionDenied
return render(
request,
"hosting/website_https.html",
{
"account": account,
"rows": rows,
"candidates": dns_candidates(
records, {row.domain for row in rows}, mx_hosts
),
"selection": selection,
"attach": attach,
"has_selectable": bool(selectable),
"may_attach": may_attach,
"customer_aliases": customer is not None and bool(aliases),
"enabled": enabled,
},
)
+1
View File
@@ -47,6 +47,7 @@ SYSTEM_PAGES = {
CUSTOMER_NAV_ROUTES = { CUSTOMER_NAV_ROUTES = {
"customer_certificates": "certificates", "customer_certificates": "certificates",
"website_https": "certificates",
"customer_redirects": "redirects", "customer_redirects": "redirects",
"folder_sftp_users": "sftp", "folder_sftp_users": "sftp",
"sftp_keys": "sftp", "sftp_keys": "sftp",