From 2846e83644754e301b82694affad07a8e5f48316 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sun, 22 Nov 2026 11:43:42 +0100 Subject: [PATCH 1/2] Delegate customer onboarding and provisioning to resellers --- src/coulobre/hosting/admin.py | 17 ++- .../migrations/0046_reseller_onboarding.py | 52 +++++++ src/coulobre/hosting/models.py | 21 ++- src/coulobre/hosting/reseller_accounts.py | 8 +- src/coulobre/hosting/reseller_onboarding.py | 109 ++++++++++++++ .../hosting/reseller_onboarding_views.py | 119 +++++++++++++++ src/coulobre/hosting/reseller_views.py | 12 +- src/coulobre/hosting/resource_requests.py | 4 +- .../templates/hosting/account_detail.html | 39 +++-- .../hosting/templates/hosting/base.html | 2 +- .../templates/hosting/customer_form.html | 18 ++- .../templates/hosting/customer_list.html | 8 +- .../templates/hosting/reseller_detail.html | 6 + src/coulobre/hosting/urls.py | 14 ++ src/coulobre/hosting/views.py | 139 ++++++++++++------ 15 files changed, 498 insertions(+), 70 deletions(-) create mode 100644 src/coulobre/hosting/migrations/0046_reseller_onboarding.py create mode 100644 src/coulobre/hosting/reseller_onboarding.py create mode 100644 src/coulobre/hosting/reseller_onboarding_views.py diff --git a/src/coulobre/hosting/admin.py b/src/coulobre/hosting/admin.py index 30acb90..9763dc7 100644 --- a/src/coulobre/hosting/admin.py +++ b/src/coulobre/hosting/admin.py @@ -77,7 +77,7 @@ class HostingPlanAdmin(admin.ModelAdmin): @admin.register(Reseller) class ResellerAdmin(admin.ModelAdmin): - list_display = ("user", "account_limit") + list_display = ("user", "account_limit", "manage_resources") list_select_related = ("user",) search_fields = ("user__username",) filter_horizontal = ("hosting_plans",) @@ -91,10 +91,21 @@ class ResellerAdmin(admin.ModelAdmin): @admin.register(Customer) class CustomerAdmin(admin.ModelAdmin): - list_display = ("user",) - list_select_related = ("user",) + list_display = ("user", "reseller") + list_select_related = ("user", "reseller__user") search_fields = ("user__username",) + def get_list_display(self, request): + if not request.user.has_perm("hosting.view_reseller"): + return ("user",) + return super().get_list_display(request) + + def get_exclude(self, request, obj=None): + excluded = list(super().get_exclude(request, obj) or ()) + if not request.user.has_perm("hosting.view_reseller"): + excluded.append("reseller") + return excluded + @admin.register(CustomerImpersonation) class CustomerImpersonationAdmin(admin.ModelAdmin): diff --git a/src/coulobre/hosting/migrations/0046_reseller_onboarding.py b/src/coulobre/hosting/migrations/0046_reseller_onboarding.py new file mode 100644 index 0000000..b8bf00d --- /dev/null +++ b/src/coulobre/hosting/migrations/0046_reseller_onboarding.py @@ -0,0 +1,52 @@ +# Generated by Django 5.2.19 on 2026-11-22 10:39 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0045_panel_authentication"), + ] + + operations = [ + migrations.AddField( + model_name="customer", + name="reseller", + field=models.ForeignKey( + blank=True, + null=True, + on_delete=django.db.models.deletion.SET_NULL, + related_name="managed_customers", + to="hosting.reseller", + ), + ), + migrations.AddField( + model_name="reseller", + name="manage_resources", + field=models.BooleanField( + default=False, + help_text=( + "Allow database and mailbox requests and provisioning." + ), + ), + ), + migrations.AlterField( + model_name="resellerauditevent", + name="action", + field=models.CharField( + choices=[ + ("create", "Created reseller"), + ("update", "Updated reseller"), + ("assign", "Assigned hosting account"), + ("unassign", "Unassigned hosting account"), + ("plan", "Changed hosting account plan"), + ("cust_add", "Created customer login"), + ("cust_lnk", "Linked customer login"), + ("request", "Requested hosting resource"), + ("deploy", "Queued resource provisioning"), + ], + max_length=8, + ), + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index f7f3cb8..02214f4 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -55,6 +55,10 @@ class Reseller(models.Model): }, ) account_limit = models.PositiveIntegerField(default=0) + manage_resources = models.BooleanField( + default=False, + help_text="Allow database and mailbox requests and provisioning.", + ) hosting_plans = models.ManyToManyField("HostingPlan", blank=True) def __str__(self): @@ -74,6 +78,10 @@ class ResellerAuditEvent(models.Model): ASSIGN = "assign", "Assigned hosting account" UNASSIGN = "unassign", "Unassigned hosting account" PLAN = "plan", "Changed hosting account plan" + CUSTOMER_CREATE = "cust_add", "Created customer login" + CUSTOMER_LINK = "cust_lnk", "Linked customer login" + RESOURCE_REQUEST = "request", "Requested hosting resource" + RESOURCE_PROVISION = "deploy", "Queued resource provisioning" reseller = models.ForeignKey( Reseller, @@ -104,6 +112,14 @@ class Customer(models.Model): }, ) + reseller = models.ForeignKey( + Reseller, + on_delete=models.SET_NULL, + null=True, + blank=True, + related_name="managed_customers", + ) + def __str__(self): return self.user.get_username() @@ -663,11 +679,12 @@ class WebProvisioningPlan(models.Model): class ProvisioningJobManager(models.Manager): def queue(self, **target): job, created = self.get_or_create(**target) - if not created: + return created or bool( self.requeue(self.filter(pk=job.pk).exclude(problem="")) + ) def requeue(self, jobs, **updates): - jobs.filter(finished_at__isnull=False).update( + return jobs.filter(finished_at__isnull=False).update( requested_at=timezone.now(), last_dispatched_at=None, started_at=None, diff --git a/src/coulobre/hosting/reseller_accounts.py b/src/coulobre/hosting/reseller_accounts.py index f64b884..974c781 100644 --- a/src/coulobre/hosting/reseller_accounts.py +++ b/src/coulobre/hosting/reseller_accounts.py @@ -29,6 +29,7 @@ def plan_reference(plan): def policy_snapshot(reseller): return { "account_limit": reseller.account_limit, + "manage_resources": reseller.manage_resources, "hosting_plans": [ plan_reference(plan) for plan in reseller.hosting_plans.order_by("pk") @@ -70,7 +71,9 @@ def create_reseller(login_form, policy, actor): user.is_active = policy["is_active"] user.save() reseller = Reseller.objects.create( - user=user, account_limit=policy["account_limit"] + user=user, + account_limit=policy["account_limit"], + manage_resources=policy.get("manage_resources", False), ) if "hosting_plans" in policy: reseller.hosting_plans.set(policy["hosting_plans"]) @@ -102,6 +105,9 @@ def update_reseller(reseller_id, policy, actor): if reseller.account_limit != policy["account_limit"]: reseller.account_limit = policy["account_limit"] reseller.save(update_fields=["account_limit"]) + if "manage_resources" in policy: + reseller.manage_resources = policy["manage_resources"] + reseller.save(update_fields=["manage_resources"]) if "hosting_plans" in policy: reseller.hosting_plans.set(policy["hosting_plans"]) changes = policy_changes(before, policy_snapshot(reseller)) diff --git a/src/coulobre/hosting/reseller_onboarding.py b/src/coulobre/hosting/reseller_onboarding.py new file mode 100644 index 0000000..0c7e4d7 --- /dev/null +++ b/src/coulobre/hosting/reseller_onboarding.py @@ -0,0 +1,109 @@ +from django.core.exceptions import PermissionDenied, ValidationError +from django.db import transaction + +from .access import reseller_for_user +from .models import Customer, HostingAccount, Reseller, ResellerAuditEvent +from .reseller_accounts import lock_resellers, record_event +from .resource_requests import lock_hosting_account, require_open_account + +Action = ResellerAuditEvent.Action + + +def scoped_customers(reseller): + return reseller.managed_customers.filter( + user__is_staff=False, + user__is_superuser=False, + user__hosting_reseller__isnull=True, + ) + + +def lock_reseller_account(access, account_id, *, resources=False): + account = lock_hosting_account(account_id, customer_id=None) + if account.reseller_id != access.pk: + raise HostingAccount.DoesNotExist + reseller = lock_resellers( + Reseller.objects.filter(pk=access.pk, user_id=access.user_id) + ).first() + if ( + reseller is None + or not reseller.user.is_active + or reseller_for_user(reseller.user) is None + ): + raise PermissionDenied + if resources and not reseller.manage_resources: + raise PermissionDenied + require_open_account(account) + return account, reseller + + +def require_unassigned_customer(account): + if account.customer_id is not None: + raise ValidationError("This hosting account already has a customer.") + + +@transaction.atomic +def create_reseller_customer(access, account_id, form): + account, reseller = lock_reseller_account(access, account_id) + require_unassigned_customer(account) + customer = Customer.objects.create(user=form.save(), reseller=reseller) + save_customer_link(account, reseller, customer, Action.CUSTOMER_CREATE) + return account + + +@transaction.atomic +def link_reseller_customer(access, account_id, customer_id): + account, reseller = lock_reseller_account(access, account_id) + require_unassigned_customer(account) + customer = ( + scoped_customers(reseller) + .select_for_update() + .filter(pk=customer_id, user__is_active=True) + .first() + ) + if customer is None: + raise ValidationError("This customer is no longer available.") + save_customer_link(account, reseller, customer, Action.CUSTOMER_LINK) + return account + + +def save_customer_link(account, reseller, customer, action): + account.customer = customer + account.save(update_fields=["customer"]) + record_event( + reseller, + reseller.user.get_username(), + action, + {"customer": str(customer)}, + account_domain=account.primary_domain, + ) + + +@transaction.atomic +def request_reseller_resource(access, account_id, create, values): + account, reseller = lock_reseller_account( + access, account_id, resources=True + ) + resource = create(account.pk, **values) + record_resource_event(reseller, account, Action.RESOURCE_REQUEST, resource) + return resource + + +@transaction.atomic +def provision_reseller_resource(access, account_id, provision, resource): + account, reseller = lock_reseller_account( + access, account_id, resources=True + ) + if provision(resource): + record_resource_event( + reseller, account, Action.RESOURCE_PROVISION, resource + ) + + +def record_resource_event(reseller, account, action, resource): + record_event( + reseller, + reseller.user.get_username(), + action, + {"resource": str(resource), "type": resource._meta.verbose_name}, + account_domain=account.primary_domain, + ) diff --git a/src/coulobre/hosting/reseller_onboarding_views.py b/src/coulobre/hosting/reseller_onboarding_views.py new file mode 100644 index 0000000..fab3681 --- /dev/null +++ b/src/coulobre/hosting/reseller_onboarding_views.py @@ -0,0 +1,119 @@ +from django import forms +from django.contrib.auth import get_user_model +from django.contrib.auth.forms import UserCreationForm +from django.contrib.auth.mixins import PermissionRequiredMixin +from django.core.exceptions import ValidationError +from django.db import IntegrityError +from django.http import Http404 +from django.shortcuts import get_object_or_404, redirect +from django.utils.decorators import method_decorator +from django.utils.functional import cached_property +from django.views.decorators.debug import sensitive_post_parameters +from django.views.generic import FormView + +from .access import reseller_for_user +from .models import HostingAccount +from .reseller_onboarding import ( + create_reseller_customer, + link_reseller_customer, + scoped_customers, +) + + +class ResellerCustomerLoginForm(UserCreationForm): + email = forms.EmailField( + required=False, + help_text="Used for customer password recovery when enabled.", + ) + + class Meta(UserCreationForm.Meta): + fields = ("username", "email") + + +class ResellerCustomerLinkForm(forms.Form): + customer = forms.ModelChoiceField(queryset=None) + + def __init__(self, *args, customers, **kwargs): + super().__init__(*args, **kwargs) + self.fields["customer"].queryset = customers + + +class ResellerCustomerEditor(PermissionRequiredMixin, FormView): + template_name = "hosting/customer_form.html" + + @cached_property + def reseller(self): + return reseller_for_user(self.request.user) + + @cached_property + def account(self): + return get_object_or_404( + HostingAccount, + pk=self.kwargs["pk"], + reseller=self.reseller, + retired_at__isnull=True, + customer__isnull=True, + ) + + def has_permission(self): + return self.reseller is not None + + def get_context_data(self, **kwargs): + return super().get_context_data(account=self.account, **kwargs) + + +@method_decorator( + sensitive_post_parameters("password1", "password2"), name="dispatch" +) +class ResellerCustomerCreate(ResellerCustomerEditor): + form_class = ResellerCustomerLoginForm + extra_context = {"title": "Add customer login"} + + def form_valid(self, form): + account = self.account + try: + account = create_reseller_customer(self.reseller, account.pk, form) + except HostingAccount.DoesNotExist as error: + raise Http404 from error + except ValidationError as error: + form.add_error(None, error) + return self.form_invalid(form) + except IntegrityError: + user = form.instance + if ( + not get_user_model() + .objects.filter(username__iexact=user.username) + .exists() + ): + raise + form.add_error( + "username", user.unique_error_message(type(user), ["username"]) + ) + return self.form_invalid(form) + return redirect(account) + + +class ResellerCustomerLink(ResellerCustomerEditor): + form_class = ResellerCustomerLinkForm + extra_context = {"title": "Link existing customer"} + + def get_form_kwargs(self): + return super().get_form_kwargs() | { + "customers": scoped_customers(self.reseller) + .filter(user__is_active=True) + .select_related("user") + .order_by("user__username") + } + + def form_valid(self, form): + account = self.account + try: + account = link_reseller_customer( + self.reseller, account.pk, form.cleaned_data["customer"].pk + ) + except HostingAccount.DoesNotExist as error: + raise Http404 from error + except ValidationError as error: + form.add_error(None, error) + return self.form_invalid(form) + return redirect(account) diff --git a/src/coulobre/hosting/reseller_views.py b/src/coulobre/hosting/reseller_views.py index 826a10b..5487305 100644 --- a/src/coulobre/hosting/reseller_views.py +++ b/src/coulobre/hosting/reseller_views.py @@ -33,8 +33,16 @@ class ResellerPolicyForm(forms.ModelForm): class Meta: model = Reseller - fields = ("is_active", "account_limit", "hosting_plans") - labels = {"hosting_plans": "Allowed hosting plans"} + fields = ( + "is_active", + "account_limit", + "hosting_plans", + "manage_resources", + ) + labels = { + "hosting_plans": "Allowed hosting plans", + "manage_resources": "Manage databases and mailboxes", + } help_texts = { "account_limit": "Enter 0 to stop self-service account creation.", "hosting_plans": ( diff --git a/src/coulobre/hosting/resource_requests.py b/src/coulobre/hosting/resource_requests.py index c584c5c..192946b 100644 --- a/src/coulobre/hosting/resource_requests.py +++ b/src/coulobre/hosting/resource_requests.py @@ -95,7 +95,7 @@ def queue_mailbox_provisioning(mailbox): mailbox.mail_domain.account_id, customer_id=None ) require_active_services(account) - MailboxProvisioning.objects.queue(mailbox=mailbox) + return MailboxProvisioning.objects.queue(mailbox=mailbox) @transaction.atomic @@ -200,7 +200,7 @@ def require_active_services(account): def queue_database_provisioning(database): account = lock_hosting_account(database.account_id, customer_id=None) require_active_services(account) - DatabaseProvisioning.objects.queue(database=database) + return DatabaseProvisioning.objects.queue(database=database) @transaction.atomic diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index f149fa5..a93e5fb 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -39,6 +39,21 @@ {% endif %} {% if is_operator and perms.hosting.view_customer %}
Customer
{{ account.customer|default_if_none:"Unassigned" }}
+ {% elif is_reseller %} +
Customer
+
+ {% if account.customer_id %} + {% if account.customer.reseller_id == account.reseller_id %} + {{ account.customer }} + {% else %}Assigned{% endif %} + {% else %} + Add customer login + {% if reseller_customer_link %} + Link existing customer + {% endif %} + {% endif %} +
+
{% endif %}
Added
{{ account.created_at|date:"j M Y, H:i" }} UTC
@@ -92,14 +107,14 @@ {% endif %} {% endif %} - {% if is_customer or is_operator and perms.hosting.add_hostingdatabase %} + {% if is_customer or reseller_resource_management or is_operator and perms.hosting.add_hostingdatabase %} Request database {% endif %} {% if databases %}
- {% if is_operator %}{% endif %} + {% if is_operator or manage_database_provisioning %}{% endif %} {% for database in databases %} @@ -115,16 +130,18 @@ {% endif %} - {% if is_operator %} + {% if is_operator or manage_database_provisioning %} @@ -231,7 +248,7 @@ {% endif %} {% endif %} - {% if is_customer or is_operator and perms.hosting.add_hostingmailbox %} + {% if is_customer or reseller_resource_management or is_operator and perms.hosting.add_hostingmailbox %} Request mailbox {% endif %} @@ -242,7 +259,7 @@ - {% if is_operator %}{% endif %} + {% if is_operator or manage_mailbox_provisioning %}{% endif %} @@ -264,10 +281,12 @@ {% endif %} - {% if is_operator %} + {% if is_operator or manage_mailbox_provisioning %} diff --git a/src/coulobre/hosting/templates/hosting/base.html b/src/coulobre/hosting/templates/hosting/base.html index c82d43f..c966d73 100644 --- a/src/coulobre/hosting/templates/hosting/base.html +++ b/src/coulobre/hosting/templates/hosting/base.html @@ -27,7 +27,7 @@ Hosting accounts {% endif %} - {% if is_operator and perms.hosting.view_customer %} + {% if is_reseller or is_operator and perms.hosting.view_customer %} Customers diff --git a/src/coulobre/hosting/templates/hosting/customer_form.html b/src/coulobre/hosting/templates/hosting/customer_form.html index 23c90e4..273cd8d 100644 --- a/src/coulobre/hosting/templates/hosting/customer_form.html +++ b/src/coulobre/hosting/templates/hosting/customer_form.html @@ -1,15 +1,23 @@ {% extends "hosting/base.html" %} -{% block title %}Add customer · Coulobre Panel{% endblock %} +{% block title %}{{ title|default:"Add customer" }} · Coulobre Panel{% endblock %} {% block content %} - ← Customers -

Add customer

+ {% if account %} + ← {{ account.name }} + {% else %} + ← Customers + {% endif %} +

{{ title|default:"Add customer" }}

{% csrf_token %} {{ form.as_div }}
- - Cancel + + {% if account %} + Cancel + {% else %} + Cancel + {% endif %}
diff --git a/src/coulobre/hosting/templates/hosting/customer_list.html b/src/coulobre/hosting/templates/hosting/customer_list.html index 1e67d59..080c433 100644 --- a/src/coulobre/hosting/templates/hosting/customer_list.html +++ b/src/coulobre/hosting/templates/hosting/customer_list.html @@ -3,7 +3,7 @@ {% block content %}

Customers

- {% if perms.hosting.add_customer %} + {% if is_operator and perms.hosting.add_customer %} Add customer {% endif %}
@@ -21,7 +21,7 @@ - {% if perms.hosting.change_customer or can_impersonate %}{% endif %} + {% if is_operator and perms.hosting.change_customer or can_impersonate %}{% endif %} @@ -32,7 +32,7 @@ {% if customer.user.is_active %}Active {% else %}Suspended{% endif %} - {% if perms.hosting.change_customer or can_impersonate %} + {% if is_operator and perms.hosting.change_customer or can_impersonate %}
DatabaseDeployment
DatabaseDeployment
- Download manifest + {% if is_operator %} + Download manifest + {% endif %} {% if manage_database_provisioning %} {% url 'panel:database_provision' database.pk as provision_url %} {% include "hosting/resource_provisioning.html" with provisioning=database.provisioning enabled=local_database_enabled action=provision_url resource=database provision_label="Provision database" %} {% endif %}
- {% if manage_database_provisioning and database.provisioning.problem %} + {% if is_operator and manage_database_provisioning and database.provisioning.problem %}

{{ database.provisioning.problem }}

{% endif %}
Email address Storage limitDeploymentDeployment
{% if mailbox.quota_mib is not None %}{{ mailbox.quota_mib }} MiB{% else %}Unlimited{% endif %}
- Download manifest + {% if is_operator %} + Download manifest + {% endif %} {% if change_mailbox_quota %} Change storage limit {% endif %} @@ -276,7 +295,7 @@ {% include "hosting/resource_provisioning.html" with provisioning=mailbox.provisioning enabled=local_mailbox_enabled action=provision_url resource=mailbox provision_label="Provision mailbox" %} {% endif %}
- {% if manage_mailbox_provisioning and mailbox.provisioning.problem %} + {% if is_operator and manage_mailbox_provisioning and mailbox.provisioning.problem %}

{{ mailbox.provisioning.problem }}

{% endif %}
Username Sign-in statusActionsActions
{% if perms.hosting.change_customer and not customer.user.is_staff and not customer.user.is_superuser and not customer.user.hosting_reseller %} @@ -67,6 +67,8 @@
{% elif search %}

No customers match this search.

+ {% elif is_reseller %} +

Open an unassigned hosting account to add a customer login.

{% else %}

No customers yet.

{% endif %} diff --git a/src/coulobre/hosting/templates/hosting/reseller_detail.html b/src/coulobre/hosting/templates/hosting/reseller_detail.html index e906357..909307c 100644 --- a/src/coulobre/hosting/templates/hosting/reseller_detail.html +++ b/src/coulobre/hosting/templates/hosting/reseller_detail.html @@ -10,6 +10,7 @@
Panel sign-in
{{ reseller.user.is_active|yesno:"Active,Suspended" }}
+
Database and mailbox management
{{ reseller.manage_resources|yesno:"Allowed,Operator only" }}
Accounts allocated
{{ account_count }} of {{ reseller.account_limit }}
{% if perms.hosting.view_hostingplan %}
@@ -67,6 +68,11 @@ {% if event.changes.account_limit %}
Account limit {{ event.changes.account_limit.before|default_if_none:"—" }} → {{ event.changes.account_limit.after }}
{% endif %} + {% if event.changes.customer %}
{{ event.changes.customer }}
{% endif %} + {% if event.changes.resource %}
{{ event.changes.type|capfirst }} {{ event.changes.resource }}
{% endif %} + {% if event.changes.manage_resources %} +
Database and mailbox management {{ event.changes.manage_resources.before|yesno:"allowed,operator only,—" }} → {{ event.changes.manage_resources.after|yesno:"allowed,operator only" }}
+ {% endif %} {% if event.changes.is_active %}
Panel sign-in {{ event.changes.is_active.before|yesno:"active,suspended,—" }} → {{ event.changes.is_active.after|yesno:"active,suspended" }}
{% endif %} diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index 9baa78a..913d32e 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -14,6 +14,10 @@ from .password_reset import ( CustomerResetDoneView, ) from .phpmyadmin import PhpMyAdminLaunch, redeem_phpmyadmin +from .reseller_onboarding_views import ( + ResellerCustomerCreate, + ResellerCustomerLink, +) from .reseller_views import ( ResellerCreate, ResellerDetail, @@ -73,6 +77,16 @@ urlpatterns = [ name="account_retirement", ), path("accounts//", views.AccountDetail.as_view(), name="account"), + path( + "accounts//customers/new/", + ResellerCustomerCreate.as_view(), + name="reseller_customer_create", + ), + path( + "accounts//customers/link/", + ResellerCustomerLink.as_view(), + name="reseller_customer_link", + ), path( "accounts//service-access/", views.ChangeHostingServices.as_view(), diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 77b004b..219ec92 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -114,6 +114,11 @@ from .php_versions import ( ) from .phpmyadmin import phpmyadmin_available from .reseller_accounts import create_reseller_account, save_operator_account +from .reseller_onboarding import ( + provision_reseller_resource, + request_reseller_resource, + scoped_customers, +) from .resource_requests import ( change_mailbox_quota, create_database_request, @@ -365,6 +370,14 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): reseller = reseller_for_user(user) customer = customer_for_user(user) tenant = reseller is not None or customer is not None + manage_resources = reseller is not None and reseller.manage_resources + context["reseller_resource_management"] = manage_resources + context["reseller_customer_link"] = reseller is not None and ( + self.object.customer_id is None + and scoped_customers(reseller) + .filter(user__is_active=True) + .exists() + ) context["can_retire_account"] = not tenant and user.has_perms( RETIRE_ACCOUNTS ) @@ -532,7 +545,9 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): ] and roundcube_available(self.request) if tenant or user.has_perm(VIEW_DATABASES): databases = self.object.databases.all() - if not tenant and user.has_perms(PROVISION_DATABASE): + if manage_resources or ( + not tenant and user.has_perms(PROVISION_DATABASE) + ): databases = databases.select_related("provisioning") context["manage_database_provisioning"] = True context["local_database_enabled"] = ( @@ -573,14 +588,16 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView): mailboxes = HostingMailbox.objects.filter( mail_domain__account=self.object ).select_related("mail_domain") - if not tenant and user.has_perms(PROVISION_MAILBOX): + if manage_resources or ( + not tenant and user.has_perms(PROVISION_MAILBOX) + ): mailboxes = mailboxes.select_related("provisioning") context["manage_mailbox_provisioning"] = True context["local_mailbox_enabled"] = ( settings.LOCAL_MAILBOX_PROVISIONING ) - context["change_mailbox_quota"] = user.has_perms( - CHANGE_MAILBOX_QUOTA + context["change_mailbox_quota"] = ( + not tenant and user.has_perms(CHANGE_MAILBOX_QUOTA) ) if context.get("show_webmail"): mailboxes = list( @@ -1393,7 +1410,7 @@ class SiteSFTPKeys(PermissionRequiredMixin, FormView): return super().form_valid(form) -class CustomerList(OperatorOnlyMixin, PermissionRequiredMixin, ListView): +class CustomerList(TenantScopeMixin, PermissionRequiredMixin, ListView): queryset = Customer.objects.select_related( "user__hosting_reseller" ).order_by("user__username") @@ -1404,7 +1421,10 @@ class CustomerList(OperatorOnlyMixin, PermissionRequiredMixin, ListView): def get_queryset(self): self.search = self.request.GET.get("q", "").strip()[:150] + reseller = reseller_for_user(self.request.user) queryset = super().get_queryset() + if reseller is not None: + queryset = queryset.filter(pk__in=scoped_customers(reseller)) if self.search: queryset = queryset.filter(user__username__icontains=self.search) return queryset @@ -1529,17 +1549,22 @@ class ResourceRequestCreate(PermissionRequiredMixin, CreateView): def customer(self): return customer_for_user(self.request.user) + @cached_property + def reseller(self): + return reseller_for_user(self.request.user) + def has_permission(self): - return self.customer is not None or ( - reseller_for_user(self.request.user) is None - and super().has_permission() - ) + if self.reseller is not None: + return self.reseller.manage_resources + return self.customer is not None or super().has_permission() @cached_property def account(self): accounts = HostingAccount.objects.filter(retired_at__isnull=True) if self.customer is not None: accounts = accounts.filter(customer=self.customer) + if self.reseller is not None: + accounts = accounts.filter(reseller=self.reseller) return get_object_or_404(accounts, pk=self.kwargs["pk"]) def get_context_data(self, **kwargs): @@ -1559,13 +1584,21 @@ class ResourceRequestCreate(PermissionRequiredMixin, CreateView): def form_valid(self, form): try: with support_write_session(self.request) as session: - self.object = self.create_request( - self.account.pk, - **form.cleaned_data, - customer_id=self.customer.pk - if self.customer is not None - else None, - ) + if self.reseller is not None: + self.object = request_reseller_resource( + self.reseller, + self.account.pk, + self.create_request, + form.cleaned_data, + ) + else: + self.object = self.create_request( + self.account.pk, + **form.cleaned_data, + customer_id=self.customer.pk + if self.customer is not None + else None, + ) if session is not None: CustomerImpersonationAction.objects.create( session=session, @@ -1609,22 +1642,53 @@ class DownloadDatabaseManifest( ) -class RequestDatabaseProvisioning( - OperatorOnlyMixin, PermissionRequiredMixin, View -): - permission_required = PROVISION_DATABASE +class ResourceProvisioningRequest(PermissionRequiredMixin, View): + @cached_property + def reseller(self): + return reseller_for_user(self.request.user) + + def has_permission(self): + if self.reseller is not None: + return self.reseller.manage_resources + return ( + customer_for_user(self.request.user) is None + and super().has_permission() + ) def post(self, request, pk): - if not settings.LOCAL_DATABASE_PROVISIONING: + if not getattr(settings, self.enabled_setting): raise Http404 - database = get_object_or_404( - HostingDatabase.objects.select_related("account"), pk=pk - ) + queryset = self.queryset.all() + if self.reseller is not None: + queryset = queryset.filter( + **{f"{self.account_relation}__reseller": self.reseller} + ) + resource = get_object_or_404(queryset, pk=pk) + account = self.get_account(resource) try: - queue_database_provisioning(database) + if self.reseller is None: + self.provision(resource) + else: + provision_reseller_resource( + self.reseller, account.pk, self.provision, resource + ) + except HostingAccount.DoesNotExist as error: + raise Http404 from error except ValidationError as error: return provisioning_conflict(error) - return redirect(database.account) + return redirect(account) + + +class RequestDatabaseProvisioning(ResourceProvisioningRequest): + permission_required = PROVISION_DATABASE + enabled_setting = "LOCAL_DATABASE_PROVISIONING" + queryset = HostingDatabase.objects.select_related("account") + account_relation = "account" + provision = staticmethod(queue_database_provisioning) + + @staticmethod + def get_account(database): + return database.account class DnsZoneEditor(PermissionRequiredMixin, FormView): @@ -1905,23 +1969,16 @@ class MailboxQuotaEdit(OperatorOnlyMixin, PermissionRequiredMixin, UpdateView): return redirect(self.object.mail_domain.account) -class RequestMailboxProvisioning( - OperatorOnlyMixin, PermissionRequiredMixin, View -): +class RequestMailboxProvisioning(ResourceProvisioningRequest): permission_required = PROVISION_MAILBOX + enabled_setting = "LOCAL_MAILBOX_PROVISIONING" + queryset = HostingMailbox.objects.select_related("mail_domain__account") + account_relation = "mail_domain__account" + provision = staticmethod(queue_mailbox_provisioning) - def post(self, request, pk): - if not settings.LOCAL_MAILBOX_PROVISIONING: - raise Http404 - mailbox = get_object_or_404( - HostingMailbox.objects.select_related("mail_domain__account"), - pk=pk, - ) - try: - queue_mailbox_provisioning(mailbox) - except ValidationError as error: - return provisioning_conflict(error) - return redirect(mailbox.mail_domain.account) + @staticmethod + def get_account(mailbox): + return mailbox.mail_domain.account class HostingPlanList(OperatorOnlyMixin, PermissionRequiredMixin, ListView): -- 2.43.0 From 98bf8e127b51051ce4be22b9241acc4713291924 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sun, 22 Nov 2026 11:43:42 +0100 Subject: [PATCH 2/2] Document and verify reseller account boundaries --- docs/deployment.md | 25 ++ .../hosting/test_reseller_onboarding.py | 278 ++++++++++++++++++ 2 files changed, 303 insertions(+) create mode 100644 src/coulobre/hosting/test_reseller_onboarding.py diff --git a/docs/deployment.md b/docs/deployment.md index 3fd7257..8be31ba 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -1971,6 +1971,31 @@ limit and retain their assigned plans. Operators can assign and move accounts from the hosting account form. Use the audit history to review changes to reseller policy and account assignments made through the panel. +### Onboard customers and delegate provisioning + +A reseller can open an unassigned hosting account in their own portfolio and +select **Add customer login**. Enter a new username and password, and add an +email address to support customer password recovery. Share the initial +credentials with the customer through a trusted channel. An existing +customer created by the same reseller can be added with **Link existing +customer**. The operator controls changes to existing assignments and to +customer sign-in status. The reseller's **Customers** page lists their own +logins. + +Enable **Manage databases and mailboxes** on the reseller policy to let that +reseller request and provision both resources for their hosting accounts. +New requests use the account's existing database and mailbox limits and +mailbox storage quota. A deployment must enable the relevant provisioner +before the reseller can queue work. The panel shows provisioning status, +while service credentials and deployment manifests follow their existing +permissions. Both local and separate mail receivers use the same panel +permission. + +The operator's reseller detail page records customer creation and linking, +resource requests, provisioning attempts queued or retried, and changes to +the reseller policy. Customer sign-in and operator support access use the +same workflows as operator-created accounts. + ## Suspend and resume hosting services Open the hosting account and use **Hosting service access**. This requires diff --git a/src/coulobre/hosting/test_reseller_onboarding.py b/src/coulobre/hosting/test_reseller_onboarding.py new file mode 100644 index 0000000..2b572dd --- /dev/null +++ b/src/coulobre/hosting/test_reseller_onboarding.py @@ -0,0 +1,278 @@ +from unittest.mock import patch + +from django.contrib.auth import get_user_model +from django.contrib.auth.models import Permission +from django.test import TestCase, override_settings +from django.urls import reverse +from django.utils import timezone + +from .models import ( + Customer, + DatabaseProvisioning, + HostingAccount, + HostingDatabase, + HostingMailbox, + HostingMailDomain, + HostingPlan, + MailboxProvisioning, + Reseller, + ResellerAuditEvent, +) +from .reseller_onboarding import request_reseller_resource + +PASSWORD = "fixture-password-for-customer" +Action = ResellerAuditEvent.Action + + +@override_settings( + LOCAL_DATABASE_PROVISIONING=True, + LOCAL_MAILBOX_PROVISIONING=True, +) +class ResellerOnboardingTests(TestCase): + @classmethod + def setUpTestData(cls): + users = get_user_model().objects + cls.operator = users.create_superuser("operator") + cls.alice = Reseller.objects.create( + user=users.create_user("alice"), manage_resources=True + ) + cls.bob = Reseller.objects.create( + user=users.create_user("bob"), manage_resources=True + ) + cls.plan = HostingPlan.objects.create( + name="Small", + database_limit=1, + mailbox_limit=1, + mailbox_quota_mib=50, + ) + cls.account = HostingAccount.objects.create( + name="Alice account", + primary_domain="alice.test", + reseller=cls.alice, + hosting_plan=cls.plan, + ) + cls.second = HostingAccount.objects.create( + name="Second Alice account", + primary_domain="second.test", + reseller=cls.alice, + hosting_plan=cls.plan, + ) + cls.other = HostingAccount.objects.create( + name="Bob account", + primary_domain="bob.test", + reseller=cls.bob, + hosting_plan=cls.plan, + ) + cls.other_customer = Customer.objects.create( + user=users.create_user("bob-customer"), reseller=cls.bob + ) + cls.operator_customer = Customer.objects.create( + user=users.create_user("operator-customer") + ) + + def setUp(self): + self.client.force_login(self.alice.user) + + def post_customer(self, account, **overrides): + return self.client.post( + reverse("panel:reseller_customer_create", args=[account.pk]), + { + "username": "new-customer", + "email": "customer@example.test", + "password1": PASSWORD, + "password2": PASSWORD, + **overrides, + }, + ) + + def test_create_and_link_a_customer_to_owned_accounts(self): + self.assertContains( + self.client.get(self.account.get_absolute_url()), + "Add customer login", + ) + self.assertRedirects( + self.post_customer(self.account, reseller=self.bob.pk), + self.account.get_absolute_url(), + ) + customer = Customer.objects.get(user__username="new-customer") + self.assertEqual(customer.reseller_id, self.alice.pk) + self.assertTrue(customer.user.check_password(PASSWORD)) + self.assertEqual(customer.user.email, "customer@example.test") + self.assertFalse(customer.user.is_staff) + self.account.refresh_from_db() + self.assertEqual(self.account.customer_id, customer.pk) + + url = reverse("panel:reseller_customer_link", args=[self.second.pk]) + form = self.client.get(url) + self.assertContains(form, "new-customer") + self.assertNotContains(form, "bob-customer") + self.assertNotContains(form, "operator-customer") + for outsider in (self.other_customer, self.operator_customer): + response = self.client.post(url, {"customer": outsider.pk}) + self.assertIn("customer", response.context["form"].errors) + self.assertRedirects( + self.client.post(url, {"customer": customer.pk}), + self.second.get_absolute_url(), + ) + self.assertEqual( + set(customer.hostingaccount_set.values_list("pk", flat=True)), + {self.account.pk, self.second.pk}, + ) + self.assertEqual(self.post_customer(self.account).status_code, 404) + events = self.alice.audit_events.order_by("pk") + self.assertEqual( + list( + events.values_list( + "action", "actor_username", "account_domain" + ) + ), + [ + (Action.CUSTOMER_CREATE, "alice", "alice.test"), + (Action.CUSTOMER_LINK, "alice", "second.test"), + ], + ) + self.assertEqual(events.first().changes, {"customer": "new-customer"}) + + self.client.force_login(customer.user) + self.assertContains( + self.client.get(self.second.get_absolute_url()), self.second.name + ) + self.assertEqual( + self.client.get(self.other.get_absolute_url()).status_code, 404 + ) + self.client.force_login(self.bob.user) + self.assertNotContains( + self.client.get(reverse("panel:customers")), "new-customer" + ) + self.assertContains( + self.client.get(reverse("panel:customers")), "bob-customer" + ) + + def test_reseller_cannot_create_a_customer_for_another_reseller(self): + self.assertEqual(self.post_customer(self.other).status_code, 404) + self.assertFalse( + Customer.objects.filter(user__username="new-customer").exists() + ) + + self.alice.user.user_permissions.set( + Permission.objects.filter(content_type__app_label="hosting") + ) + url = reverse("panel:customer_access", args=[self.other_customer.pk]) + self.assertEqual( + self.client.post(url, {"access": "suspend"}).status_code, 403 + ) + self.client.force_login(self.operator) + self.assertContains( + self.client.get(reverse("panel:customers")), "bob-customer" + ) + self.assertRedirects( + self.client.post(url, {"access": "suspend"}), + reverse("panel:customers"), + ) + + def test_delegated_resource_management_preserves_limits_and_audits_jobs( + self, + ): + database_url = reverse("panel:database_create", args=[self.account.pk]) + mailbox_url = reverse("panel:mailbox_create", args=[self.account.pk]) + detail = self.account.get_absolute_url() + self.assertRedirects( + self.client.post(database_url, {"suffix": "shop"}), detail + ) + self.assertRedirects( + self.client.post(mailbox_url, {"local_part": "info"}), detail + ) + self.assertContains( + self.client.post(database_url, {"suffix": "over"}), + "has reached its database limit", + ) + self.assertContains( + self.client.post(mailbox_url, {"local_part": "over"}), + "has reached its mailbox limit", + ) + database = HostingDatabase.objects.get(account=self.account) + mailbox = HostingMailbox.objects.get(mail_domain__account=self.account) + self.assertEqual(mailbox.quota_mib, 50) + for model, resource in (("database", database), ("mailbox", mailbox)): + url = reverse(f"panel:{model}_provision", args=[resource.pk]) + manifest = reverse(f"panel:{model}_manifest", args=[resource.pk]) + self.assertContains(self.client.get(detail), f"Provision {model}") + self.assertEqual(self.client.get(manifest).status_code, 403) + for _ in range(2): + self.assertRedirects(self.client.post(url), detail) + self.assertEqual(DatabaseProvisioning.objects.get().database, database) + self.assertEqual(MailboxProvisioning.objects.get().mailbox, mailbox) + self.assertEqual( + list( + self.alice.audit_events.order_by("pk").values_list( + "action", flat=True + ) + ), + [Action.RESOURCE_REQUEST] * 2 + [Action.RESOURCE_PROVISION] * 2, + ) + DatabaseProvisioning.objects.update( + finished_at=timezone.now(), problem="Failed" + ) + retry = reverse("panel:database_provision", args=[database.pk]) + self.assertRedirects(self.client.post(retry), detail) + self.assertEqual(DatabaseProvisioning.objects.get().state, "queued") + self.assertEqual( + self.alice.audit_events.filter( + action=Action.RESOURCE_PROVISION + ).count(), + 3, + ) + + def test_resource_scope_and_policy_are_checked_for_each_request(self): + database = HostingDatabase.objects.create( + account=self.other, suffix="shop" + ) + domain = HostingMailDomain.objects.create( + account=self.other, domain="bob.test" + ) + mailbox = HostingMailbox.objects.create( + mail_domain=domain, local_part="info" + ) + for model, resource in (("database", database), ("mailbox", mailbox)): + location = reverse(f"panel:{model}_provision", args=[resource.pk]) + self.assertEqual(self.client.post(location).status_code, 404) + for model, values in ( + ("database", {"suffix": "test"}), + ("mailbox", {"local_part": "test"}), + ): + path = reverse(f"panel:{model}_create", args=[self.other.pk]) + self.assertEqual(self.client.post(path, values).status_code, 404) + self.assertFalse(DatabaseProvisioning.objects.exists()) + self.assertFalse(MailboxProvisioning.objects.exists()) + + original = request_reseller_resource + + def revoke_before_save(*args, **kwargs): + Reseller.objects.filter(pk=self.alice.pk).update( + manage_resources=False + ) + return original(*args, **kwargs) + + path = reverse("panel:database_create", args=[self.account.pk]) + with patch( + "coulobre.hosting.views.request_reseller_resource", + side_effect=revoke_before_save, + ): + self.assertEqual( + self.client.post(path, {"suffix": "test"}).status_code, 403 + ) + self.assertFalse(self.account.databases.exists()) + self.assertFalse(self.alice.audit_events.exists()) + + @override_settings(LOCAL_DATABASE_PROVISIONING=False) + def test_deployment_can_disable_a_provisioner(self): + database = HostingDatabase.objects.create( + account=self.account, suffix="shop" + ) + path = reverse("panel:database_provision", args=[database.pk]) + self.assertNotContains( + self.client.get(self.account.get_absolute_url()), + "Provision database", + ) + self.assertEqual(self.client.post(path).status_code, 404) + self.assertFalse(DatabaseProvisioning.objects.exists()) -- 2.43.0