Add SSH public key management to hosting accounts
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s

This commit is contained in:
parkel committed 2026-11-21 10:56:47 +01:00
1 parent a3f7a2e7cb
commit cde9fe00d4
16 files changed
+717 -2

No files matched your search

+1
View File
@@ -20,6 +20,7 @@ PREVIEW_VIEWS = frozenset(
"panel:account",
"panel:database_create",
"panel:mailbox_create",
"panel:sftp_keys",
}
)
EndReason = CustomerImpersonation.EndReason
@@ -0,0 +1,62 @@
# Generated by Django 5.2.19 on 2026-11-21 09:38
import django.db.models.deletion
import django.utils.timezone
from django.db import migrations, models
import coulobre.hosting.fields
class Migration(migrations.Migration):
dependencies = [
("hosting", "0018_web_https"),
]
operations = [
migrations.CreateModel(
name="SiteSFTP",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"requested_at",
models.DateTimeField(default=django.utils.timezone.now),
),
(
"last_dispatched_at",
models.DateTimeField(blank=True, null=True),
),
("started_at", models.DateTimeField(blank=True, null=True)),
("finished_at", models.DateTimeField(blank=True, null=True)),
("problem", models.TextField(blank=True)),
(
"domain",
coulobre.hosting.fields.DomainNameField(max_length=253),
),
("public_keys", models.TextField(blank=True)),
(
"requested_customer_id",
models.PositiveBigIntegerField(blank=True, null=True),
),
(
"account",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
related_name="sftp",
to="hosting.hostingaccount",
),
),
],
options={
"verbose_name": "site SFTP access",
"verbose_name_plural": "site SFTP access",
},
),
]
+15
View File
@@ -352,6 +352,21 @@ class WebHTTPS(ProvisioningJob):
verbose_name = "website HTTPS request"
class SiteSFTP(ProvisioningJob):
account = models.OneToOneField(
HostingAccount, on_delete=models.CASCADE, related_name="sftp"
)
domain = DomainNameField(max_length=253)
public_keys = models.TextField(blank=True)
requested_customer_id = models.PositiveBigIntegerField(
null=True, blank=True
)
class Meta:
verbose_name = "site SFTP access"
verbose_name_plural = "site SFTP access"
class DatabaseProvisioning(ProvisioningJob):
database = models.OneToOneField(
HostingDatabase, on_delete=models.CASCADE, related_name="provisioning"
+10
View File
@@ -16,6 +16,16 @@ def enable_local_https(site):
)
def update_local_sftp(keys):
apply_on_local_node(
keys,
"/run/coulobre-sftp-apply.sock",
"web node",
"SFTP key request",
identity=keys.identity(),
)
def provision_local_database(database):
apply_on_local_node(
database,
+136
View File
@@ -0,0 +1,136 @@
from django import forms
from django.core.exceptions import ValidationError
from django.db import transaction
from coulobre.sftp_keys import (
MAX_KEYS_BYTES,
public_key_fingerprint,
read_public_keys,
)
from .access import customer_for_user, is_tenant
from .models import SiteSFTP
from .resource_requests import lock_hosting_account
def can_manage_sftp(user):
return customer_for_user(user) is not None or (
not is_tenant(user)
and user.has_perms(
("hosting.view_hostingaccount", "hosting.change_sitesftp")
)
)
def site_is_active(account):
return account.webprovisioningplan_set.filter(
primary_domain=account.primary_domain,
activation__finished_at__isnull=False,
activation__problem="",
).exists()
@transaction.atomic
def queue_sftp_keys(
account_id, operation, *, public_keys="", fingerprint="", customer_id=None
):
account = lock_hosting_account(account_id, customer_id)
request = SiteSFTP.objects.filter(account=account).first()
previous = request.public_keys if request is not None else ""
keys = change_key_list(previous, operation, public_keys, fingerprint)
if operation == "remove" and keys == previous:
return
if keys and not site_is_active(account):
raise ValidationError(
"Activate the site for the current domain first."
)
if not keys and request is None:
return
updates = {
"domain": account.primary_domain if keys else request.domain,
"public_keys": keys,
"requested_customer_id": customer_id,
}
if request is None:
SiteSFTP.objects.create(account=account, **updates)
return
same_keys = (
request.domain == updates["domain"]
and request.public_keys == keys
and request.requested_customer_id == customer_id
)
if request.finished_at is None:
if not same_keys:
raise ValidationError(
"Wait for the current SFTP key request to finish."
)
elif not same_keys or request.problem:
SiteSFTP.objects.requeue(
SiteSFTP.objects.filter(pk=request.pk), **updates
)
def change_key_list(previous, operation, public_keys, fingerprint):
if operation == "revoke":
return ""
if operation == "remove":
return "".join(
f"{key}\n"
for key in previous.splitlines()
if public_key_fingerprint(key) != fingerprint
)
return merge_public_keys(previous, public_keys)
def merge_public_keys(*lists):
keys = dict.fromkeys(key for keys in lists for key in keys.splitlines())
value = "".join(f"{key}\n" for key in keys)
if len(value.encode("utf-8")) > MAX_KEYS_BYTES:
raise ValidationError("The site's SSH key list exceeds 16 KiB.")
return value
class PublicKeyFileInput(forms.FileInput):
allow_multiple_selected = True
class SFTPKeyUploadForm(forms.Form):
operation = forms.ChoiceField(
choices=(("add", "Add"), ("remove", "Remove"), ("revoke", "Revoke"))
)
fingerprint = forms.RegexField(
r"\ASHA256:[A-Za-z0-9+/]{43}\Z", required=False
)
public_keys = forms.Field(
label="SSH public key files",
required=False,
widget=PublicKeyFileInput,
help_text="Choose .pub files or a list with one public key per line.",
)
def clean(self):
cleaned = super().clean()
if cleaned.get("operation") == "remove" and not cleaned.get(
"fingerprint"
):
self.add_error(None, "Select an SSH key to remove.")
if cleaned.get("operation") != "add":
cleaned["public_keys"] = ""
return cleaned
uploads = cleaned.get("public_keys")
if not uploads:
self.add_error("public_keys", "Choose an SSH public key file.")
return cleaned
try:
keys = merge_public_keys(
*(read_public_keys(file) for file in uploads)
)
if not keys:
raise ValueError("The files do not contain an SSH public key.")
except ValueError as error:
self.add_error("public_keys", str(error))
except ValidationError as error:
self.add_error("public_keys", error)
else:
cleaned["public_keys"] = keys
return cleaned
+38
View File
@@ -6,12 +6,14 @@ from django.db.models import Q
from django.utils import timezone
from coulobre.dns_node import DnsZone
from coulobre.sftp_keys import SFTPKeys
from coulobre.web_node import WebSite
from .models import (
DatabaseProvisioning,
DnsPublication,
MailboxProvisioning,
SiteSFTP,
WebActivation,
WebHTTPS,
WebProvisioningPlan,
@@ -22,11 +24,14 @@ from .node_client import (
provision_local_database,
provision_local_mailbox,
publish_local_zone,
update_local_sftp,
)
from .sftp import site_is_active
REDISPATCH_AFTER = timedelta(minutes=5)
WEB_ACTIVATION_QUEUE = "coulobre-web-activation"
WEB_HTTPS_QUEUE = "coulobre-web-https"
WEB_SFTP_QUEUE = "coulobre-web-sftp"
DATABASE_PROVISIONING_QUEUE = "coulobre-database-provisioning"
DNS_PUBLISHING_QUEUE = "coulobre-dns-publishing"
MAILBOX_PROVISIONING_QUEUE = "coulobre-mailbox-provisioning"
@@ -81,6 +86,12 @@ def dispatch_web_https():
dispatch_provisioning_jobs(WebHTTPS, enable_web_https, WEB_HTTPS_QUEUE)
@shared_task
def dispatch_web_sftp():
if settings.LOCAL_WEB_SFTP:
dispatch_provisioning_jobs(SiteSFTP, update_web_sftp, WEB_SFTP_QUEUE)
@shared_task
def dispatch_database_provisioning():
if settings.LOCAL_DATABASE_PROVISIONING:
@@ -169,6 +180,33 @@ def apply_web_https(provisioning):
enable_local_https(WebSite(plan.account_id, plan.primary_domain))
@shared_task(acks_late=True, reject_on_worker_lost=True)
def update_web_sftp(request_id):
if settings.LOCAL_WEB_SFTP:
run_provisioning_job(
SiteSFTP.objects.select_related("account__customer__user"),
request_id,
apply_web_sftp,
"Could not contact the local SFTP service. "
"Check its socket and try again.",
)
def apply_web_sftp(request):
account = request.account
if request.requested_customer_id is not None and (
request.requested_customer_id != account.customer_id
or not account.customer.user.is_active
):
raise ValueError("The customer no longer has access to this account.")
if request.public_keys and (
request.domain != account.primary_domain or not site_is_active(account)
):
raise ValueError("Activate the site for the current domain first.")
site = WebSite(request.account_id, request.domain)
update_local_sftp(SFTPKeys(site, request.public_keys))
@shared_task(acks_late=True, reject_on_worker_lost=True)
def provision_database(provisioning_id):
if settings.LOCAL_DATABASE_PROVISIONING:
@@ -7,8 +7,15 @@
<h1>{{ account.name }}</h1>
<p class="heading-meta domain">{{ account.primary_domain }}</p>
</div>
{% if is_operator and perms.hosting.change_hostingaccount %}
<a class="button secondary" href="{% url 'panel:account_edit' account.pk %}">Edit account</a>
{% if manage_sftp or is_operator and perms.hosting.change_hostingaccount %}
<div class="form-actions">
{% if manage_sftp %}
<a class="button secondary" href="{% url 'panel:sftp_keys' account.pk %}">SFTP access</a>
{% endif %}
{% if is_operator and perms.hosting.change_hostingaccount %}
<a class="button secondary" href="{% url 'panel:account_edit' account.pk %}">Edit account</a>
{% endif %}
</div>
{% endif %}
</header>
<dl class="details surface">
@@ -0,0 +1,95 @@
{% extends "hosting/base.html" %}
{% block title %}SFTP access · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
<header class="page-heading">
<div>
<h1>SFTP access</h1>
<p class="heading-meta domain">{{ account.primary_domain }}</p>
</div>
{% if account.sftp and not account.sftp.finished_at %}
<a class="button secondary" href="{% url 'panel:sftp_keys' account.pk %}">Refresh status</a>
{% endif %}
</header>
{% with request_status=account.sftp %}
{% if request_status %}
<p class="notice">
{% if request_status.state == "configured" %}
{% if request_status.public_keys %}SSH keys installed.{% else %}SFTP access revoked.{% endif %}
{% elif request_status.state == "failed" %}
{{ request_status.problem }}
{% elif request_status.state == "running" %}
Applying SSH keys.
{% else %}
SSH key request queued.
{% endif %}
</p>
{% endif %}
<section class="surface editor-surface" aria-labelledby="key-instructions">
<div class="editor">
<h2 id="key-instructions">Generate an SSH key</h2>
<p>Run this command on your computer.</p>
<pre><code>ssh-keygen -t ed25519</code></pre>
<p>Choose a passphrase when prompted. Use a different filename if you already have a key. With the default filename, upload <code>~/.ssh/id_ed25519.pub</code>. Keep the private key on your computer.</p>
<p>Use the web node's SSH hostname and port with the username <code>coulobre-{{ account.pk }}</code>. The SFTP session starts in <code>/public</code>.</p>
</div>
</section>
{{ form.non_field_errors }}
{{ form.operation.errors }}
{{ form.fingerprint.errors }}
{% if ssh_keys %}
<section class="surface" aria-labelledby="ssh-keys-heading">
<header class="section-heading">
<div>
<h2 id="ssh-keys-heading">SSH keys</h2>
<p class="heading-meta">Run <code>ssh-keygen -lf ~/.ssh/id_ed25519.pub</code> to check a key's fingerprint.</p>
</div>
</header>
<div class="table-scroll">
<table>
<thead>
<tr>
<th scope="col">Key type</th>
<th scope="col">Fingerprint</th>
{% if can_edit_keys %}<th scope="col">Actions</th>{% endif %}
</tr>
</thead>
<tbody>
{% for key_type, fingerprint in ssh_keys %}
<tr>
<td>{{ key_type }}</td>
<td class="domain">{{ fingerprint }}</td>
{% if can_edit_keys %}
<td>
<form method="post">
{% csrf_token %}
<input type="hidden" name="fingerprint" value="{{ fingerprint }}">
<button class="button secondary" type="submit" name="operation" value="remove" aria-label="Remove SSH key {{ fingerprint }}">Remove key</button>
</form>
</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
</section>
{% endif %}
{% if can_edit_keys or can_revoke_keys %}
<section class="surface editor-surface" aria-label="SSH key management">
<form class="editor" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% if can_edit_keys %}
{{ form.public_keys.as_field_group }}
{% endif %}
<div class="form-actions">
{% if can_edit_keys %}<button class="button primary" type="submit" name="operation" value="add">Upload SSH keys</button>{% endif %}
{% if can_revoke_keys %}
<button class="button secondary" type="submit" name="operation" value="revoke">Revoke SFTP access</button>
{% endif %}
</div>
</form>
</section>
{% endif %}
{% endwith %}
{% endblock %}
+164
View File
@@ -0,0 +1,164 @@
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from coulobre.sftp_keys import public_key_fingerprint
from .models import (
Customer,
HostingAccount,
SiteSFTP,
WebActivation,
WebProvisioningPlan,
)
from .tasks import update_web_sftp
from .test_sftp_keys import public_key
@override_settings(LOCAL_WEB_SFTP=True)
class SiteSFTPTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.alice = users.create_user("alice")
cls.customer = Customer.objects.create(user=cls.alice)
cls.account = HostingAccount.objects.create(
name="Alice site",
primary_domain="alice.example",
customer=cls.customer,
)
plan = WebProvisioningPlan.for_account(cls.account)
plan.save()
WebActivation.objects.create(plan=plan, finished_at=timezone.now())
def setUp(self):
self.client.force_login(self.alice)
self.url = reverse("panel:sftp_keys", args=[self.account.pk])
def upload(self, key, url=None):
return self.client.post(
url or self.url,
{
"operation": "add",
"public_keys": SimpleUploadedFile("site.pub", key.encode()),
},
)
def test_customer_can_upload_a_public_key_and_track_installation(self):
self.assertContains(
self.client.get(self.account.get_absolute_url()), "SFTP access"
)
page = self.client.get(self.url)
self.assertContains(page, "ssh-keygen -t ed25519")
self.assertContains(page, f"coulobre-{self.account.pk}")
key = public_key()
self.assertRedirects(self.upload(key), self.url)
job = SiteSFTP.objects.get(account=self.account)
self.assertEqual(job.requested_customer_id, self.customer.pk)
self.assertContains(
self.client.get(self.url), "SSH key request queued."
)
with patch("coulobre.hosting.tasks.update_local_sftp") as apply:
update_web_sftp(job.pk)
self.assertEqual(apply.call_args.args[0].public_keys, f"{key}\n")
self.assertContains(self.client.get(self.url), "SSH keys installed.")
def test_adds_separate_uploads_and_removes_only_the_selected_key(self):
first, second, third = (public_key(number) for number in (1, 2, 3))
self.assertRedirects(self.upload(first), self.url)
job = SiteSFTP.objects.get(account=self.account)
with patch("coulobre.hosting.tasks.update_local_sftp"):
update_web_sftp(job.pk)
response = self.client.post(
self.url,
{
"operation": "add",
"public_keys": [
SimpleUploadedFile("second.pub", second.encode()),
SimpleUploadedFile(
"third.pub", f"{third}\n{first}".encode()
),
],
},
)
self.assertRedirects(response, self.url)
job.refresh_from_db()
self.assertEqual(job.public_keys.splitlines(), [first, second, third])
with patch("coulobre.hosting.tasks.update_local_sftp"):
update_web_sftp(job.pk)
fingerprint = public_key_fingerprint(second)
self.assertContains(self.client.get(self.url), fingerprint)
self.assertRedirects(
self.client.post(
self.url, {"operation": "remove", "fingerprint": fingerprint}
),
self.url,
)
with patch("coulobre.hosting.tasks.update_local_sftp") as apply:
update_web_sftp(job.pk)
self.assertEqual(
apply.call_args.args[0].public_keys.splitlines(), [first, third]
)
def test_customer_cannot_upload_to_another_account(self):
other = HostingAccount.objects.create(
name="Other site", primary_domain="other.example"
)
url = reverse("panel:sftp_keys", args=[other.pk])
self.assertEqual(self.client.get(url).status_code, 404)
self.assertEqual(self.upload(public_key(), url).status_code, 404)
self.assertFalse(SiteSFTP.objects.exists())
def test_rejects_private_keys_before_queueing(self):
response = self.upload("-----BEGIN OPENSSH PRIVATE KEY-----\n")
self.assertContains(response, "Expected a supported SSH public key")
self.assertNotContains(response, "BEGIN OPENSSH PRIVATE KEY")
self.assertFalse(SiteSFTP.objects.exists())
def test_customer_preview_can_read_instructions_and_cannot_upload(self):
operator = get_user_model().objects.create_superuser("operator")
self.client.force_login(operator)
start = reverse("panel:impersonation_start", args=[self.customer.pk])
self.client.post(start)
response = self.client.get(self.url)
self.assertContains(response, "ssh-keygen -t ed25519")
self.assertNotContains(response, "Upload SSH keys")
self.assertEqual(self.upload(public_key()).status_code, 403)
self.assertFalse(SiteSFTP.objects.exists())
def test_worker_checks_customer_assignment_before_installing_keys(self):
self.upload(public_key())
job = SiteSFTP.objects.get(account=self.account)
HostingAccount.objects.filter(pk=self.account.pk).update(customer=None)
with patch("coulobre.hosting.tasks.update_local_sftp") as apply:
update_web_sftp(job.pk)
apply.assert_not_called()
job.refresh_from_db()
self.assertEqual(job.state, "failed")
self.assertIn("no longer has access", job.problem)
def test_revokes_at_the_original_node_after_a_domain_change(self):
self.upload(public_key())
job = SiteSFTP.objects.get(account=self.account)
with patch("coulobre.hosting.tasks.update_local_sftp"):
update_web_sftp(job.pk)
HostingAccount.objects.filter(pk=self.account.pk).update(
primary_domain="new.example"
)
self.assertContains(self.client.get(self.url), "Revoke SFTP access")
self.assertRedirects(
self.client.post(self.url, {"operation": "revoke"}), self.url
)
with patch("coulobre.hosting.tasks.update_local_sftp") as apply:
update_web_sftp(job.pk)
keys = apply.call_args.args[0]
self.assertEqual(keys.site.domain, "alice.example")
self.assertEqual(keys.public_keys, "")
self.assertContains(self.client.get(self.url), "SFTP access revoked.")
+5
View File
@@ -20,6 +20,11 @@ urlpatterns = [
"accounts/new/", views.AccountCreate.as_view(), name="account_create"
),
path("accounts/<int:pk>/", views.AccountDetail.as_view(), name="account"),
path(
"accounts/<int:pk>/sftp/",
views.SiteSFTPKeys.as_view(),
name="sftp_keys",
),
path(
"accounts/<int:pk>/edit/",
views.AccountEdit.as_view(),
+74
View File
@@ -28,6 +28,7 @@ from django.views.generic.detail import SingleObjectMixin
from coulobre.dns_node import MAX_SOA_SERIAL
from coulobre.mail_node import INVALID_LOCAL_PART
from coulobre.sftp_keys import public_key_fingerprint
from .access import (
OperatorOnlyMixin,
@@ -60,6 +61,12 @@ from .models import (
)
from .reseller_accounts import create_reseller_account
from .resource_requests import create_database_request, create_mailbox_request
from .sftp import (
SFTPKeyUploadForm,
can_manage_sftp,
queue_sftp_keys,
site_is_active,
)
from .web_node import build_web_smoke_bundle, serialize_deployment_manifest
VIEW_ACCOUNTS = "hosting.view_hostingaccount"
@@ -222,6 +229,11 @@ 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
context["manage_sftp"] = (
settings.LOCAL_WEB_SFTP
and can_manage_sftp(user)
and (site_is_active(self.object) or hasattr(self.object, "sftp"))
)
if reseller is not None or (
customer is None and user.has_perm(VIEW_PLANS)
):
@@ -264,6 +276,68 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
return context
class SiteSFTPKeys(PermissionRequiredMixin, FormView):
form_class = SFTPKeyUploadForm
template_name = "hosting/sftp_keys.html"
def dispatch(self, request, *args, **kwargs):
if not settings.LOCAL_WEB_SFTP:
raise Http404
return super().dispatch(request, *args, **kwargs)
def has_permission(self):
return can_manage_sftp(self.request.user)
@cached_property
def account(self):
accounts = HostingAccount.objects.select_related("sftp")
customer = customer_for_user(self.request.user)
if customer is not None:
accounts = accounts.filter(customer=customer)
return get_object_or_404(accounts, pk=self.kwargs["pk"])
def get_context_data(self, **kwargs):
status = getattr(self.account, "sftp", None)
editable = getattr(self.request, "impersonation", None) is None
idle = status is None or status.finished_at is not None
keys = () if status is None else status.public_keys.splitlines()
return super().get_context_data(
account=self.account,
ssh_keys=[
(key.split(" ", 1)[0], public_key_fingerprint(key))
for key in keys
],
can_edit_keys=editable and idle and site_is_active(self.account),
can_revoke_keys=editable
and idle
and status is not None
and bool(status.public_keys or status.problem),
**kwargs,
)
def get_success_url(self):
return reverse("panel:sftp_keys", args=[self.account.pk])
def form_valid(self, form):
customer = customer_for_user(self.request.user)
try:
queue_sftp_keys(
self.account.pk,
form.cleaned_data["operation"],
public_keys=form.cleaned_data["public_keys"],
fingerprint=form.cleaned_data["fingerprint"],
customer_id=customer.pk if customer is not None else None,
)
except HostingAccount.DoesNotExist as error:
raise Http404 from error
except ValidationError as error:
form.add_error(None, error)
return self.render_to_response(
self.get_context_data(form=form), status=409
)
return super().form_valid(form)
class CustomerList(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
queryset = Customer.objects.select_related(
"user__hosting_reseller"
+7
View File
@@ -120,6 +120,7 @@ CELERY_TASK_DEFAULT_QUEUE = "coulobre"
CELERY_TASK_IGNORE_RESULT = True
LOCAL_WEB_ACTIVATION = os.environ.get("COULOBRE_LOCAL_WEB_ACTIVATION") == "1"
LOCAL_WEB_HTTPS = os.environ.get("COULOBRE_LOCAL_WEB_HTTPS") == "1"
LOCAL_WEB_SFTP = os.environ.get("COULOBRE_LOCAL_WEB_SFTP") == "1"
LOCAL_DATABASE_PROVISIONING = (
os.environ.get("COULOBRE_LOCAL_DATABASE_PROVISIONING") == "1"
)
@@ -146,6 +147,12 @@ if LOCAL_WEB_HTTPS:
"schedule": 5.0,
"options": {"expires": 4.0},
}
if LOCAL_WEB_SFTP:
CELERY_BEAT_SCHEDULE["dispatch-web-sftp"] = {
"task": "coulobre.hosting.tasks.dispatch_web_sftp",
"schedule": 5.0,
"options": {"expires": 4.0},
}
if LOCAL_DATABASE_PROVISIONING:
CELERY_BEAT_SCHEDULE["dispatch-database-provisioning"] = {
"task": "coulobre.hosting.tasks.dispatch_database_provisioning",