Install WordPress and provision site administrators
This commit is contained in:
1 parent
ff3e39a2e1
commit
e1f1a3c86e
17 files changed
+1215
-7
No files matched your search
@@ -22,6 +22,7 @@ COULOBRE_DB_HOST=/run/mysqld/mysqld.sock
|
||||
COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre
|
||||
# COULOBRE_SERVICE_HEALTH='{"panel-01":{"local":["panel","worker","scheduler","apache","mariadb","rabbitmq"]}}'
|
||||
# COULOBRE_LOCAL_WEB_ACTIVATION=1
|
||||
# COULOBRE_WORDPRESS_MANAGEMENT=1
|
||||
# COULOBRE_LOCAL_WEB_HTTPS=1
|
||||
# COULOBRE_LOCAL_WEB_SFTP=1
|
||||
# COULOBRE_WEB_FILE_MANAGER=1
|
||||
|
||||
@@ -1390,6 +1390,33 @@ an archive containing several sites. The archive identifies each website
|
||||
by domain and site ID. Upgrade the panel and its web and backup workers
|
||||
together before enabling additional sites.
|
||||
|
||||
## Enable WordPress installation and administrator setup
|
||||
|
||||
Install the verified [WP-CLI Phar](https://make.wordpress.org/cli/handbook/guides/installing/#verifying-the-download-optional-but-recommended)
|
||||
as a root-owned regular file at `/usr/local/bin/wp` on the web node.
|
||||
Install the PHP CLI and MariaDB extension for each PHP series used by
|
||||
WordPress sites. The website user must be able to reach WordPress.org
|
||||
to download and verify the release. Use local website and database
|
||||
provisioning. Set `COULOBRE_WORDPRESS_MANAGEMENT=1` in
|
||||
`/etc/coulobre/panel.env`, apply the Django migrations, and restart
|
||||
the panel, scheduler, and web activation worker.
|
||||
|
||||
Open the hosting account's **Websites → WordPress** page and select
|
||||
an active website. **Detect WordPress** checks the document root and
|
||||
displays the installed version. For a fresh installation, enable the
|
||||
site's HTTPS configuration and use an empty document root or the
|
||||
original Coulobre starter page. Enter the site title and first
|
||||
WordPress administrator's username and email. The panel creates a
|
||||
MariaDB database within the hosting package quota before installing.
|
||||
The web node prepares WordPress under the site's Unix identity and
|
||||
publishes the new root after verification.
|
||||
|
||||
Use **Add a WordPress administrator** to create a separate administrator.
|
||||
WordPress submits a password setup email through the site's mail
|
||||
configuration. If the panel reports an email failure, correct the
|
||||
site's outbound mail and use the WordPress password reset page. The
|
||||
setup workflow keeps passwords out of panel jobs, logs and email.
|
||||
|
||||
## Enable the website file manager
|
||||
|
||||
The installer enables the file manager, scheduled website jobs and local
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
# Generated by Django 5.2.19 on 2026-12-01 23:55
|
||||
|
||||
import django.db.models.deletion
|
||||
import django.utils.timezone
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("hosting", "0087_mail_filter_check"),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="WordPressJob",
|
||||
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)),
|
||||
("actor_role", models.CharField(default="", max_length=16)),
|
||||
("site", models.JSONField()),
|
||||
("action", models.CharField(max_length=12)),
|
||||
("details", models.JSONField(default=dict)),
|
||||
("report", models.JSONField(default=dict)),
|
||||
(
|
||||
"account",
|
||||
models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name="wordpress_jobs",
|
||||
to="hosting.hostingaccount",
|
||||
),
|
||||
),
|
||||
(
|
||||
"actor",
|
||||
models.ForeignKey(
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.SET_NULL,
|
||||
to=settings.AUTH_USER_MODEL,
|
||||
),
|
||||
),
|
||||
(
|
||||
"database",
|
||||
models.ForeignKey(
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.SET_NULL,
|
||||
to="hosting.hostingdatabase",
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
"abstract": False,
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -1372,6 +1372,23 @@ class DatabaseProvisioning(ProvisioningJob):
|
||||
)
|
||||
|
||||
|
||||
class WordPressJob(ProvisioningJob):
|
||||
account = models.ForeignKey(
|
||||
HostingAccount, on_delete=models.CASCADE, related_name="wordpress_jobs"
|
||||
)
|
||||
actor = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True
|
||||
)
|
||||
actor_role = models.CharField(max_length=16, default="")
|
||||
site = models.JSONField()
|
||||
action = models.CharField(max_length=12)
|
||||
database = models.ForeignKey(
|
||||
HostingDatabase, on_delete=models.SET_NULL, null=True
|
||||
)
|
||||
details = models.JSONField(default=dict)
|
||||
report = models.JSONField(default=dict)
|
||||
|
||||
|
||||
class AccountBackupJob(ProvisioningJob):
|
||||
account = models.ForeignKey(
|
||||
HostingAccount, on_delete=models.CASCADE, related_name="backup_jobs"
|
||||
|
||||
@@ -75,6 +75,7 @@ from .models import (
|
||||
WebsiteRedirectPolicy,
|
||||
WebsiteRestoreJob,
|
||||
WebsiteScheduledJob,
|
||||
WordPressJob,
|
||||
)
|
||||
from .node_client import (
|
||||
NodeReplyError,
|
||||
@@ -186,6 +187,14 @@ def render_web_plan(plan_id):
|
||||
@shared_task
|
||||
def dispatch_web_activations():
|
||||
if settings.LOCAL_WEB_ACTIVATION:
|
||||
if settings.WORDPRESS_MANAGEMENT:
|
||||
dispatch_provisioning_jobs(
|
||||
WordPressJob,
|
||||
run_wordpress_job,
|
||||
WEB_ACTIVATION_QUEUE,
|
||||
condition=Q(database__isnull=True)
|
||||
| Q(database__provisioning__finished_at__isnull=False),
|
||||
)
|
||||
dispatch_provisioning_jobs(
|
||||
WebsiteRedirectPolicy,
|
||||
deploy_website_redirects,
|
||||
@@ -1139,6 +1148,22 @@ def run_provisioning_job(
|
||||
notify_job_outcome(job, failed=bool(problem))
|
||||
|
||||
|
||||
@shared_task(queue=WEB_ACTIVATION_QUEUE)
|
||||
def run_wordpress_job(job_id):
|
||||
from .wordpress_management import run_wordpress_operation
|
||||
|
||||
if settings.WORDPRESS_MANAGEMENT and settings.LOCAL_WEB_ACTIVATION:
|
||||
run_provisioning_job(
|
||||
WordPressJob.objects.select_related(
|
||||
"account", "actor", "database"
|
||||
),
|
||||
job_id,
|
||||
run_wordpress_operation,
|
||||
"The web node did not report a WordPress result.",
|
||||
lease=timedelta(minutes=4),
|
||||
)
|
||||
|
||||
|
||||
@shared_task
|
||||
def deliver_panel_notifications():
|
||||
if notifications_available():
|
||||
|
||||
@@ -87,7 +87,7 @@
|
||||
{% endif %}
|
||||
{% if show_website or independent_websites or add_independent_website %}
|
||||
<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 %}
|
||||
{% if show_website_usage or primary_file_access or manage_website_jobs or manage_sftp or manage_wordpress %}
|
||||
<div class="form-actions account-actions">
|
||||
{% if show_website_usage %}
|
||||
<a class="button secondary" href="{% url 'panel:website_usage' account.pk %}">Usage and logs</a>
|
||||
@@ -101,6 +101,9 @@
|
||||
{% if manage_sftp %}
|
||||
<a class="button secondary" href="{% url 'panel:sftp_keys' account.pk %}">SFTP access</a>
|
||||
{% endif %}
|
||||
{% if manage_wordpress %}
|
||||
<a class="button secondary" href="{% url 'panel:account_wordpress' account.pk %}">WordPress</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if show_website %}
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
{% extends "hosting/workspace_page.html" %}
|
||||
{% block title %}WordPress · Coulobre Panel{% endblock %}
|
||||
{% block page_title %}WordPress{% endblock %}
|
||||
{% block page_metadata %}<p class="heading-meta">{{ account.name }}</p>{% endblock %}
|
||||
{% block page_actions %}
|
||||
<a class="button secondary" href="{{ account.get_absolute_url }}#websites">Back to websites</a>
|
||||
{% endblock %}
|
||||
{% block workspace_selector %}
|
||||
{% if sites %}
|
||||
<form class="workspace-selector" method="get">
|
||||
<label for="wordpress-site">Website</label>
|
||||
<select id="wordpress-site" name="site">
|
||||
{% for option in sites %}<option value="{{ option.domain }}"{% if option == site %} selected{% endif %}>{{ option.domain }}</option>{% endfor %}
|
||||
</select>
|
||||
<button type="submit" class="button secondary">Select website</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
{% block page_content %}
|
||||
{% if site %}
|
||||
<section class="surface" id="wordpress-status" data-live-status="wordpress">
|
||||
<header class="section-heading">
|
||||
<div>
|
||||
<h2>{{ site.domain }}</h2>
|
||||
{% if version %}
|
||||
<p class="heading-meta">WordPress {{ version }}</p>
|
||||
{% else %}
|
||||
<p class="heading-meta">No WordPress installation confirmed</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% if version %}
|
||||
<a class="button secondary" href="https://{{ site.domain }}/wp-admin/">Open WordPress admin</a>
|
||||
{% endif %}
|
||||
</header>
|
||||
{{ operation_errors }}
|
||||
{% if jobs and not jobs.0.finished_at %}
|
||||
<p class="section-text" data-live-pending>WordPress operation {{ jobs.0.state }}.</p>
|
||||
{% endif %}
|
||||
<form method="post" class="form-actions">
|
||||
{% csrf_token %}
|
||||
<input type="hidden" name="site" value="{{ site.domain }}">
|
||||
<button class="button secondary" name="action" value="inspect" type="submit">Detect WordPress</button>
|
||||
</form>
|
||||
{% if jobs %}
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead><tr><th scope="col">Operation</th><th scope="col">Requested</th><th scope="col">Result</th></tr></thead>
|
||||
<tbody>
|
||||
{% for job in jobs %}
|
||||
<tr>
|
||||
<th scope="row">{% if job.action == "add-admin" %}Add administrator{% elif job.action == "install" %}Install{% else %}Detect{% endif %}</th>
|
||||
<td>{{ job.requested_at }}</td>
|
||||
<td>
|
||||
{% if job.problem %}{{ job.problem }}
|
||||
{% else %}{{ job.state|capfirst }}{% endif %}
|
||||
{% if job.report.password_email == "accepted" %}<br>WordPress accepted the password setup email.
|
||||
{% elif job.report.password_email == "failed" %}<br>WordPress could not send the setup email. Check the website's mail settings and <a href="https://{{ site.domain }}/wp-login.php?action=lostpassword">request a password reset</a>.
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% if version or admin_form.is_bound %}
|
||||
<section class="surface editor-surface">
|
||||
<header class="section-heading"><h2>Add a WordPress administrator</h2></header>
|
||||
<form method="post" class="editor">
|
||||
{% csrf_token %}
|
||||
<input type="hidden" name="site" value="{{ site.domain }}">
|
||||
{{ admin_form.as_div }}
|
||||
<button class="button primary" name="action" value="add-admin" type="submit">Add administrator</button>
|
||||
</form>
|
||||
</section>
|
||||
{% endif %}
|
||||
{% if can_install and not version or install_form.is_bound %}
|
||||
<section class="surface editor-surface">
|
||||
<header class="section-heading"><h2>Install WordPress</h2></header>
|
||||
<p class="section-text">Use a website with HTTPS and an empty document root or the Coulobre starter page. Coulobre creates a separate database for WordPress.</p>
|
||||
<form method="post" class="editor">
|
||||
{% csrf_token %}
|
||||
<input type="hidden" name="site" value="{{ site.domain }}">
|
||||
{{ install_form.as_div }}
|
||||
<button class="button primary" name="action" value="install" type="submit">Install WordPress</button>
|
||||
</form>
|
||||
</section>
|
||||
{% endif %}
|
||||
{% else %}
|
||||
<p class="notice">Activate a website on this hosting account first.</p>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,193 @@
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
from unittest.mock import patch
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import SimpleTestCase, TestCase, override_settings
|
||||
from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
|
||||
from coulobre.database_node import DatabaseSpec
|
||||
from coulobre.web_node import WebSite, parse_web_request
|
||||
from coulobre.web_node_apply import STARTER_PAGE
|
||||
from coulobre.wordpress import WordPressRequest
|
||||
from coulobre.wordpress_node import check_install_target, publish_wordpress
|
||||
|
||||
from .models import (
|
||||
Customer,
|
||||
HostingAccount,
|
||||
WebActivation,
|
||||
WebProvisioningPlan,
|
||||
WordPressJob,
|
||||
)
|
||||
from .tasks import dispatch_web_activations, run_wordpress_job
|
||||
|
||||
|
||||
class InstallRequestTests(SimpleTestCase):
|
||||
def test_database_must_belong_to_the_website_account(self):
|
||||
site = WebSite(7, "wordpress.example.test", 9)
|
||||
request = WordPressRequest(
|
||||
site,
|
||||
"install",
|
||||
DatabaseSpec(7, "wp"),
|
||||
"My website",
|
||||
"owner",
|
||||
"owner@example.test",
|
||||
)
|
||||
self.assertEqual(parse_web_request(request.manifest()), request)
|
||||
forged = request.manifest() | {
|
||||
"database": DatabaseSpec(8, "wp").manifest()
|
||||
}
|
||||
with self.assertRaisesRegex(ValueError, "managed database"):
|
||||
parse_web_request(forged)
|
||||
|
||||
def test_unrecognized_fields_and_command_options_are_refused(self):
|
||||
site = WebSite(7, "wordpress.example.test")
|
||||
request = WordPressRequest(site, "inspect")
|
||||
with self.assertRaisesRegex(ValueError, "WordPress request"):
|
||||
parse_web_request(request.manifest() | {"command": "custom"})
|
||||
with self.assertRaisesRegex(ValueError, "1–60 letters"):
|
||||
WordPressRequest(
|
||||
site,
|
||||
"add-admin",
|
||||
username="--option",
|
||||
email="owner@example.test",
|
||||
)
|
||||
|
||||
def test_install_replaces_only_the_unmodified_starter_page(self):
|
||||
with TemporaryDirectory() as work:
|
||||
root = Path(work)
|
||||
public = root / "public"
|
||||
public.mkdir()
|
||||
stage_parent = root / "staging"
|
||||
stage_parent.mkdir()
|
||||
stage = stage_parent / "public"
|
||||
stage.mkdir()
|
||||
(stage / "index.php").write_text("prepared")
|
||||
index = public / "index.html"
|
||||
index.write_text("Existing customer files")
|
||||
with self.assertRaisesRegex(
|
||||
ValueError, "original Coulobre starter"
|
||||
):
|
||||
publish_wordpress(stage, public)
|
||||
self.assertEqual(index.read_text(), "Existing customer files")
|
||||
index.unlink()
|
||||
index.symlink_to(stage / "index.php")
|
||||
with self.assertRaisesRegex(
|
||||
ValueError, "original Coulobre starter"
|
||||
):
|
||||
check_install_target(public)
|
||||
self.assertEqual((stage / "index.php").read_text(), "prepared")
|
||||
index.unlink()
|
||||
index.write_text(STARTER_PAGE)
|
||||
with (
|
||||
patch(
|
||||
"coulobre.wordpress_node.publish_empty_webroot",
|
||||
side_effect=ValueError("The destination changed."),
|
||||
),
|
||||
self.assertRaisesRegex(ValueError, "destination changed"),
|
||||
):
|
||||
publish_wordpress(stage, public)
|
||||
self.assertEqual(index.read_text(), STARTER_PAGE)
|
||||
publish_wordpress(stage, public)
|
||||
self.assertEqual((public / "index.php").read_text(), "prepared")
|
||||
|
||||
|
||||
@override_settings(
|
||||
WORDPRESS_MANAGEMENT=True,
|
||||
LOCAL_WEB_ACTIVATION=True,
|
||||
LOCAL_DATABASE_PROVISIONING=True,
|
||||
)
|
||||
class WordPressWorkflowTests(TestCase):
|
||||
def setUp(self):
|
||||
self.customer = Customer.objects.create(
|
||||
user=get_user_model().objects.create_user("wp-owner")
|
||||
)
|
||||
self.account = HostingAccount.objects.create(
|
||||
name="WordPress account",
|
||||
customer=self.customer,
|
||||
primary_domain="wp.example.test",
|
||||
)
|
||||
plan = WebProvisioningPlan.objects.create(
|
||||
account=self.account,
|
||||
primary_domain=self.account.primary_domain,
|
||||
)
|
||||
WebActivation.objects.create(plan=plan, finished_at=timezone.now())
|
||||
self.url = reverse("panel:account_wordpress", args=[self.account.pk])
|
||||
self.client.force_login(self.customer.user)
|
||||
self.data = {
|
||||
"site": self.account.primary_domain,
|
||||
"action": "install",
|
||||
"title": "My site",
|
||||
"username": "my-admin",
|
||||
"email": "my-admin@example.test",
|
||||
"confirmed": "on",
|
||||
}
|
||||
|
||||
def test_install_requires_confirmation_and_provisions_its_own_database(
|
||||
self,
|
||||
):
|
||||
self.assertContains(self.client.get(self.url), "Install WordPress")
|
||||
result = self.client.post(self.url, self.data | {"confirmed": ""})
|
||||
self.assertContains(result, "This field is required.")
|
||||
self.assertFalse(WordPressJob.objects.exists())
|
||||
response = self.client.post(self.url, self.data)
|
||||
self.assertEqual(response.status_code, 302)
|
||||
queued = self.account.wordpress_jobs.get()
|
||||
self.assertEqual(queued.database.account_id, self.account.pk)
|
||||
self.assertEqual(queued.database.provisioning.state, "queued")
|
||||
self.assertEqual(queued.details["username"], "my-admin")
|
||||
self.assertNotIn("password", queued.details)
|
||||
self.assertContains(
|
||||
self.client.post(self.url, self.data), "Wait for the current"
|
||||
)
|
||||
|
||||
@patch("coulobre.hosting.node_client.apply_on_local_node")
|
||||
def test_worker_rechecks_ownership_and_reports_the_password_setup_result(
|
||||
self, apply
|
||||
):
|
||||
self.client.post(self.url, self.data)
|
||||
job = self.account.wordpress_jobs.get()
|
||||
provisioning = job.database.provisioning
|
||||
provisioning.finished_at = timezone.now()
|
||||
provisioning.save(update_fields=["finished_at"])
|
||||
apply.return_value = {"wp_version": "7.0", "password_email": "failed"}
|
||||
run_wordpress_job.run(job.pk)
|
||||
job.refresh_from_db()
|
||||
self.assertEqual(job.state, "configured")
|
||||
self.assertEqual(job.report["version"], "7.0")
|
||||
self.assertEqual(apply.call_args.args[0].database, job.database.spec)
|
||||
response = self.client.get(self.url)
|
||||
self.assertContains(response, "Open WordPress admin")
|
||||
self.assertContains(response, "could not send the setup email")
|
||||
self.client.post(self.url, self.data | {"action": "inspect"})
|
||||
next_job = self.account.wordpress_jobs.order_by("-pk").first()
|
||||
self.account.customer = None
|
||||
self.account.save(update_fields=["customer"])
|
||||
apply.reset_mock()
|
||||
run_wordpress_job.run(next_job.pk)
|
||||
apply.assert_not_called()
|
||||
next_job.refresh_from_db()
|
||||
self.assertEqual(next_job.state, "failed")
|
||||
self.assertEqual(self.client.get(self.url).status_code, 404)
|
||||
|
||||
def test_site_selection_stays_within_the_account(self):
|
||||
response = self.client.post(
|
||||
self.url, self.data | {"site": "outside.test"}
|
||||
)
|
||||
self.assertEqual(response.status_code, 404)
|
||||
self.assertFalse(self.account.wordpress_jobs.exists())
|
||||
|
||||
@patch.object(run_wordpress_job, "apply_async")
|
||||
def test_scheduler_waits_for_the_database(self, enqueue):
|
||||
self.client.post(self.url, self.data)
|
||||
job = self.account.wordpress_jobs.get()
|
||||
dispatch_web_activations.run()
|
||||
enqueue.assert_not_called()
|
||||
provisioning = job.database.provisioning
|
||||
provisioning.finished_at = timezone.now()
|
||||
provisioning.save(update_fields=["finished_at"])
|
||||
dispatch_web_activations.run()
|
||||
enqueue.assert_called_once_with(
|
||||
args=[job.pk], queue="coulobre-web-activation", retry=False
|
||||
)
|
||||
@@ -117,6 +117,7 @@ from .update_views import ChangelogView, UpdateView
|
||||
from .website_file_views import WebsiteFilesView
|
||||
from .website_job_views import WebsiteJobEditor, WebsiteJobList
|
||||
from .website_usage_views import WebsiteUsageView
|
||||
from .wordpress_views import AccountWordPressView
|
||||
from .workspace_onboarding import (
|
||||
enable_customer_workspace,
|
||||
getting_started,
|
||||
@@ -448,6 +449,11 @@ urlpatterns = [
|
||||
name="account_retirement",
|
||||
),
|
||||
path("accounts/<int:pk>/", views.AccountDetail.as_view(), name="account"),
|
||||
path(
|
||||
"accounts/<int:pk>/wordpress/",
|
||||
AccountWordPressView.as_view(),
|
||||
name="account_wordpress",
|
||||
),
|
||||
path(
|
||||
"accounts/<int:pk>/usage/",
|
||||
WebsiteUsageView.as_view(),
|
||||
|
||||
@@ -677,6 +677,15 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
||||
and owns_customer_operations(user, self.object)
|
||||
)
|
||||
context["manage_website_files"] = manage_files
|
||||
from .wordpress_management import (
|
||||
can_manage_wordpress,
|
||||
wordpress_available,
|
||||
)
|
||||
|
||||
context["manage_wordpress"] = wordpress_available() and (
|
||||
getattr(self.request, "impersonation", None) is None
|
||||
and can_manage_wordpress(user, self.object)
|
||||
)
|
||||
context["manage_website_jobs"] = can_access_website_jobs(
|
||||
self.request
|
||||
) and owns_customer_operations(user, self.object)
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
from secrets import token_hex
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import PermissionDenied, ValidationError
|
||||
from django.db import transaction
|
||||
from django.utils import timezone
|
||||
|
||||
from coulobre.web_node import WebSite
|
||||
from coulobre.wordpress import VERSION, WordPressRequest
|
||||
|
||||
from .access import customer_for_user, manages_account, reseller_for_user
|
||||
from .installation_features import panel_feature_allowed
|
||||
from .models import WordPressJob
|
||||
from .panel_roles import assigned_roles, scoped_user
|
||||
from .resource_requests import (
|
||||
create_database_request,
|
||||
lock_hosting_account,
|
||||
require_active_services,
|
||||
)
|
||||
|
||||
PERMISSIONS = (
|
||||
"hosting.view_hostingaccount",
|
||||
"hosting.change_hostingaccount",
|
||||
)
|
||||
|
||||
|
||||
def wordpress_available():
|
||||
return settings.WORDPRESS_MANAGEMENT and panel_feature_allowed(
|
||||
"LOCAL_WEB_ACTIVATION"
|
||||
)
|
||||
|
||||
|
||||
def can_manage_wordpress(user, account):
|
||||
if not user.is_authenticated or not user.is_active:
|
||||
return False
|
||||
if customer_for_user(user) is not None:
|
||||
return manages_account(user, account)
|
||||
if manager := reseller_for_user(user):
|
||||
return manager.manage_resources and manages_account(user, account)
|
||||
return user.has_perms(PERMISSIONS)
|
||||
|
||||
|
||||
def check_wordpress_actor(actor, role, account):
|
||||
if role:
|
||||
if role not in assigned_roles(actor):
|
||||
raise PermissionDenied
|
||||
actor = scoped_user(actor, role)
|
||||
if not can_manage_wordpress(actor, account):
|
||||
raise PermissionDenied
|
||||
|
||||
|
||||
def active_sites(account):
|
||||
from .certificate_views import account_certificate_sites
|
||||
|
||||
return account_certificate_sites(account)
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def queue_wordpress_job(account, site, actor, action, details):
|
||||
account = lock_hosting_account(account.pk, customer_id=None)
|
||||
require_active_services(account)
|
||||
role = getattr(actor, "panel_role", "") or ""
|
||||
if not can_manage_wordpress(actor, account):
|
||||
raise PermissionDenied
|
||||
if active_sites(account).get(site.domain) != site:
|
||||
raise ValidationError("This website is no longer active.")
|
||||
jobs = account.wordpress_jobs.filter(site=site.manifest())
|
||||
if jobs.filter(finished_at__isnull=True).exists():
|
||||
raise ValidationError("Wait for the current WordPress operation.")
|
||||
database = None
|
||||
if action == "install":
|
||||
if not panel_feature_allowed("LOCAL_DATABASE_PROVISIONING"):
|
||||
raise ValidationError(
|
||||
"Configure local database provisioning first."
|
||||
)
|
||||
previous = jobs.filter(action="install").order_by("-pk").first()
|
||||
if previous is not None:
|
||||
if previous.state == "configured":
|
||||
raise ValidationError(
|
||||
"Coulobre already installed WordPress here."
|
||||
)
|
||||
if previous.details != details or previous.database is None:
|
||||
raise ValidationError(
|
||||
"Use the same install details to resume the pending setup."
|
||||
)
|
||||
database = previous.database
|
||||
provisioning = database.provisioning
|
||||
if provisioning.state == "failed":
|
||||
type(provisioning).objects.requeue(
|
||||
type(provisioning).objects.filter(pk=provisioning.pk)
|
||||
)
|
||||
else:
|
||||
database = create_database_request(
|
||||
account.pk, "wp_" + token_hex(4), auto_provision=True
|
||||
)
|
||||
try:
|
||||
WordPressRequest(
|
||||
site, action, database.spec if database else None, **details
|
||||
)
|
||||
except ValueError as error:
|
||||
raise ValidationError(str(error)) from error
|
||||
return WordPressJob.objects.create(
|
||||
account=account,
|
||||
site=site.manifest(),
|
||||
actor=actor,
|
||||
actor_role=role,
|
||||
action=action,
|
||||
details=details,
|
||||
database=database,
|
||||
)
|
||||
|
||||
|
||||
def run_wordpress_operation(job):
|
||||
from .node_client import apply_on_local_node
|
||||
|
||||
if job.actor is None:
|
||||
raise ValueError("The requesting user is unavailable.")
|
||||
account = job.account
|
||||
try:
|
||||
check_wordpress_actor(job.actor, job.actor_role, account)
|
||||
require_active_services(account)
|
||||
except (PermissionDenied, ValidationError):
|
||||
raise ValueError(
|
||||
"The requesting user or website is no longer eligible."
|
||||
) from None
|
||||
site = WebSite.from_manifest(job.site)
|
||||
if active_sites(account).get(site.domain) != site:
|
||||
raise ValueError("This website is no longer active.")
|
||||
database = job.database
|
||||
if job.action == "install" and (
|
||||
database is None
|
||||
or database.account_id != account.pk
|
||||
or database.provisioning.state != "configured"
|
||||
):
|
||||
raise ValueError("The WordPress database is not ready.")
|
||||
spec = WordPressRequest(
|
||||
site, job.action, database.spec if database else None, **job.details
|
||||
)
|
||||
reply = apply_on_local_node(
|
||||
spec,
|
||||
"/run/coulobre-web-apply.sock",
|
||||
"web node",
|
||||
"WordPress operation",
|
||||
timeout=175,
|
||||
)
|
||||
version = reply.get("wp_version")
|
||||
email = reply.get("password_email", "")
|
||||
if (
|
||||
not isinstance(version, str)
|
||||
or (version and not VERSION.fullmatch(version))
|
||||
or (job.action != "inspect" and not version)
|
||||
or email not in ("", "accepted", "failed")
|
||||
):
|
||||
raise ValueError("The web node returned an invalid WordPress report.")
|
||||
return {
|
||||
"report": {
|
||||
"version": version,
|
||||
"password_email": email,
|
||||
"checked_at": timezone.now().isoformat(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
from django import forms
|
||||
from django.contrib.auth.mixins import PermissionRequiredMixin
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.http import Http404
|
||||
from django.shortcuts import redirect, render
|
||||
from django.urls import reverse
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.views import View
|
||||
from django.views.decorators.cache import never_cache
|
||||
from django.views.generic.detail import SingleObjectMixin
|
||||
|
||||
from coulobre.wordpress import LOGIN
|
||||
|
||||
from .access import TenantScopeMixin
|
||||
from .installation_features import panel_feature_allowed
|
||||
from .models import HostingAccount
|
||||
from .wordpress_management import (
|
||||
PERMISSIONS,
|
||||
active_sites,
|
||||
can_manage_wordpress,
|
||||
queue_wordpress_job,
|
||||
wordpress_available,
|
||||
)
|
||||
|
||||
|
||||
class AdministratorForm(forms.Form):
|
||||
username = forms.RegexField(
|
||||
LOGIN, max_length=60, label="WordPress username"
|
||||
)
|
||||
email = forms.EmailField(max_length=100)
|
||||
confirmed = forms.BooleanField(label="Create this WordPress administrator")
|
||||
|
||||
|
||||
class WordPressInstallForm(AdministratorForm):
|
||||
title = forms.CharField(max_length=150, label="Site title")
|
||||
field_order = ("title", "username", "email", "confirmed")
|
||||
|
||||
|
||||
@method_decorator(never_cache, name="dispatch")
|
||||
class AccountWordPressView(
|
||||
TenantScopeMixin, PermissionRequiredMixin, SingleObjectMixin, View
|
||||
):
|
||||
queryset = HostingAccount.objects.filter(retired_at__isnull=True)
|
||||
customer_relation = "customer"
|
||||
permission_required = PERMISSIONS
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
if not wordpress_available():
|
||||
raise Http404
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
|
||||
def has_permission(self):
|
||||
return (
|
||||
not getattr(self.request, "impersonation", None)
|
||||
and super().has_permission()
|
||||
and can_manage_wordpress(self.request.user, self.get_object())
|
||||
)
|
||||
|
||||
def select_site(self, domain):
|
||||
self.account = self.get_object()
|
||||
self.sites = active_sites(self.account)
|
||||
self.site = (
|
||||
self.sites.get(domain)
|
||||
if domain
|
||||
else next(iter(self.sites.values()), None)
|
||||
)
|
||||
if domain and self.site is None:
|
||||
raise Http404
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
self.select_site(request.GET.get("site"))
|
||||
return self.page()
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
self.select_site(request.POST.get("site"))
|
||||
action = request.POST.get("action")
|
||||
forms_for_action = {
|
||||
"inspect": forms.Form,
|
||||
"install": WordPressInstallForm,
|
||||
"add-admin": AdministratorForm,
|
||||
}
|
||||
if self.site is None or action not in forms_for_action:
|
||||
raise Http404
|
||||
form = forms_for_action[action](request.POST)
|
||||
if form.is_valid():
|
||||
details = {
|
||||
name: value
|
||||
for name, value in form.cleaned_data.items()
|
||||
if name != "confirmed"
|
||||
}
|
||||
try:
|
||||
queue_wordpress_job(
|
||||
self.account, self.site, request.user, action, details
|
||||
)
|
||||
except ValidationError as error:
|
||||
form.add_error(None, error)
|
||||
else:
|
||||
destination = reverse(
|
||||
"panel:account_wordpress", args=[self.account.pk]
|
||||
)
|
||||
return redirect(f"{destination}?site={self.site.domain}")
|
||||
return self.page(action=action, form=form)
|
||||
|
||||
def page(self, *, action=None, form=None):
|
||||
jobs = ()
|
||||
known_version = ""
|
||||
if self.site:
|
||||
history = self.account.wordpress_jobs.filter(
|
||||
site=self.site.manifest()
|
||||
).order_by("-pk")
|
||||
jobs = list(history[:10])
|
||||
last = history.filter(
|
||||
finished_at__isnull=False, problem=""
|
||||
).first()
|
||||
if last:
|
||||
known_version = last.report.get("version", "")
|
||||
return render(
|
||||
self.request,
|
||||
"hosting/account_wordpress.html",
|
||||
{
|
||||
"account": self.account,
|
||||
"sites": self.sites.values(),
|
||||
"site": self.site,
|
||||
"version": known_version,
|
||||
"jobs": jobs,
|
||||
"operation_errors": form.non_field_errors()
|
||||
if action == "inspect"
|
||||
else (),
|
||||
"install_form": form
|
||||
if action == "install"
|
||||
else WordPressInstallForm(
|
||||
initial={"title": self.account.name},
|
||||
),
|
||||
"admin_form": form
|
||||
if action == "add-admin"
|
||||
else AdministratorForm(),
|
||||
"can_install": panel_feature_allowed(
|
||||
"LOCAL_DATABASE_PROVISIONING"
|
||||
),
|
||||
},
|
||||
)
|
||||
@@ -237,6 +237,7 @@ except ValueError as error:
|
||||
raise ImproperlyConfigured(f"COULOBRE_SERVICE_HEALTH: {error}") from None
|
||||
|
||||
LOCAL_WEB_ACTIVATION = os.environ.get("COULOBRE_LOCAL_WEB_ACTIVATION") == "1"
|
||||
WORDPRESS_MANAGEMENT = os.environ.get("COULOBRE_WORDPRESS_MANAGEMENT") == "1"
|
||||
WEBSITE_USAGE = os.environ.get("COULOBRE_WEBSITE_USAGE") == "1"
|
||||
WEBSITE_WILDCARD_CERTIFICATES = os.environ.get("COULOBRE_ACME_DNS_01") == "1"
|
||||
LOCAL_WEB_HTTPS = os.environ.get("COULOBRE_LOCAL_WEB_HTTPS") == "1"
|
||||
|
||||
@@ -261,6 +261,10 @@ class WebPhpRequest:
|
||||
|
||||
|
||||
def parse_web_request(data):
|
||||
from .wordpress import OPERATION, WordPressRequest
|
||||
|
||||
if isinstance(data, dict) and data.get("operation") == OPERATION:
|
||||
return WordPressRequest.from_manifest(data)
|
||||
if (
|
||||
isinstance(data, dict)
|
||||
and data.get("operation") == "set_website_redirects"
|
||||
@@ -374,6 +378,12 @@ class WebPhpVersionRequest:
|
||||
|
||||
def apply_web_request(request):
|
||||
from .web_redirects import RedirectConfiguration
|
||||
from .wordpress import WordPressRequest
|
||||
|
||||
if isinstance(request, WordPressRequest):
|
||||
from .wordpress_node import apply_wordpress_request
|
||||
|
||||
return apply_wordpress_request(request)
|
||||
|
||||
if isinstance(request, RedirectConfiguration):
|
||||
from .web_node_redirects import apply_redirects
|
||||
|
||||
@@ -29,6 +29,12 @@ WEB_ROOT = Path("/srv/coulobre/web")
|
||||
APACHE_AVAILABLE = Path("/etc/apache2/sites-available")
|
||||
APACHE_ENABLED = Path("/etc/apache2/sites-enabled")
|
||||
SITE_SHELL = "/usr/sbin/nologin"
|
||||
STARTER_PAGE = (
|
||||
'<!doctype html><html lang="en"><meta charset="utf-8">'
|
||||
"<title>Website ready</title><h1>Your website is ready</h1>"
|
||||
"<p>Upload your website files to replace this page.</p>"
|
||||
"</html>\n"
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -189,12 +195,7 @@ def install_starter_page(document_root, uid, gid):
|
||||
except FileExistsError:
|
||||
return
|
||||
with os.fdopen(file, "w", encoding="utf-8") as page:
|
||||
page.write(
|
||||
'<!doctype html><html lang="en"><meta charset="utf-8">'
|
||||
"<title>Website ready</title><h1>Your website is ready</h1>"
|
||||
"<p>Upload your website files to replace this page.</p>"
|
||||
"</html>\n"
|
||||
)
|
||||
page.write(STARTER_PAGE)
|
||||
page.flush()
|
||||
os.fchown(page.fileno(), uid, gid)
|
||||
os.fchmod(page.fileno(), 0o644)
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.validators import validate_email
|
||||
|
||||
from .database_node import DatabaseSpec
|
||||
from .web_node import WebSite
|
||||
|
||||
OPERATION = "manage_wordpress"
|
||||
ACTIONS = ("inspect", "install", "add-admin")
|
||||
LOGIN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,59}", re.ASCII)
|
||||
VERSION = re.compile(r"[0-9][A-Za-z0-9.-]{0,29}", re.ASCII)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WordPressRequest:
|
||||
site: WebSite
|
||||
action: str
|
||||
database: DatabaseSpec | None = None
|
||||
title: str = ""
|
||||
username: str = ""
|
||||
email: str = ""
|
||||
|
||||
def __post_init__(self):
|
||||
if self.action not in ACTIONS:
|
||||
raise ValueError("Choose a WordPress action.")
|
||||
if self.action == "inspect":
|
||||
if self.database is not None or any(
|
||||
(self.title, self.username, self.email)
|
||||
):
|
||||
raise ValueError("Inspect only accepts a website.")
|
||||
return
|
||||
if not isinstance(self.username, str) or not LOGIN.fullmatch(
|
||||
self.username
|
||||
):
|
||||
raise ValueError(
|
||||
"Use 1–60 letters, digits, periods, underscores or hyphens."
|
||||
)
|
||||
if (
|
||||
not isinstance(self.email, str)
|
||||
or len(self.email) > 100
|
||||
or self.email.startswith("-")
|
||||
):
|
||||
raise ValueError("Enter a WordPress administrator email address.")
|
||||
try:
|
||||
validate_email(self.email)
|
||||
except ValidationError:
|
||||
raise ValueError("Enter a valid administrator email.") from None
|
||||
if self.action == "add-admin":
|
||||
if self.database is not None or self.title != "":
|
||||
raise ValueError("Enter only the new administrator's details.")
|
||||
return
|
||||
if (
|
||||
self.database is None
|
||||
or self.database.account_id != self.site.account_id
|
||||
):
|
||||
raise ValueError("Choose this site's managed database.")
|
||||
if (
|
||||
not isinstance(self.title, str)
|
||||
or not self.title.strip()
|
||||
or len(self.title) > 150
|
||||
or any(ord(char) < 32 for char in self.title)
|
||||
):
|
||||
raise ValueError("Enter a WordPress site title.")
|
||||
|
||||
def manifest(self):
|
||||
manifest = {
|
||||
"operation": OPERATION,
|
||||
"site": self.site.manifest(),
|
||||
"action": self.action,
|
||||
}
|
||||
if self.action != "inspect":
|
||||
manifest.update(username=self.username, email=self.email)
|
||||
if self.action == "install":
|
||||
manifest.update(
|
||||
database=self.database.manifest(), title=self.title
|
||||
)
|
||||
return manifest
|
||||
|
||||
@classmethod
|
||||
def from_manifest(cls, data):
|
||||
if not isinstance(data, dict) or data.get("operation") != OPERATION:
|
||||
raise ValueError("Expected a WordPress request.")
|
||||
action = data.get("action")
|
||||
fields = {"operation", "site", "action"}
|
||||
if action in ("install", "add-admin"):
|
||||
fields.update(("username", "email"))
|
||||
if action == "install":
|
||||
fields.update(("database", "title"))
|
||||
if data.keys() != fields:
|
||||
raise ValueError("Expected a WordPress request.")
|
||||
return cls(
|
||||
WebSite.from_manifest(data["site"]),
|
||||
action,
|
||||
DatabaseSpec.from_manifest(data["database"])
|
||||
if action == "install"
|
||||
else None,
|
||||
data.get("title", ""),
|
||||
data.get("username", ""),
|
||||
data.get("email", ""),
|
||||
)
|
||||
@@ -0,0 +1,345 @@
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import subprocess
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory, TemporaryFile
|
||||
from uuid import uuid4
|
||||
|
||||
from . import web_node_apply as web
|
||||
from .node_files import check_root_file
|
||||
from .service_credentials import read_database_credentials
|
||||
from .web_node_access import website_suspension_path
|
||||
from .web_node_files import rename_entry
|
||||
from .web_node_restore import publish_empty_webroot
|
||||
from .web_node_tls import https_status
|
||||
from .wordpress import VERSION
|
||||
|
||||
WP_CLI = Path("/usr/local/bin/wp")
|
||||
COMMAND_TIMEOUT = 35
|
||||
REPORT_LIMIT = 65536
|
||||
SEND_SETUP_LINK = (
|
||||
"exit( is_wp_error( retrieve_password( getenv( 'COULOBRE_WP_LOGIN' ) ) ) "
|
||||
"? 1 : 0 );"
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WordPressCLI:
|
||||
runtime: str
|
||||
home: Path
|
||||
uid: int
|
||||
gid: int
|
||||
|
||||
def run(
|
||||
self,
|
||||
root,
|
||||
*arguments,
|
||||
data=None,
|
||||
login="",
|
||||
read=False,
|
||||
load_plugins=False,
|
||||
):
|
||||
command = (
|
||||
f"/usr/bin/php{self.runtime}",
|
||||
str(WP_CLI),
|
||||
f"--path={root}",
|
||||
"--skip-packages",
|
||||
"--skip-themes",
|
||||
*(() if load_plugins else ("--skip-plugins",)),
|
||||
"--no-color",
|
||||
*arguments,
|
||||
)
|
||||
if read:
|
||||
command = (
|
||||
"/usr/bin/prlimit",
|
||||
f"--fsize={REPORT_LIMIT}:{REPORT_LIMIT}",
|
||||
"--",
|
||||
*command,
|
||||
)
|
||||
with TemporaryFile() as output:
|
||||
result = subprocess.run(
|
||||
command,
|
||||
input=data,
|
||||
stdin=subprocess.DEVNULL if data is None else None,
|
||||
stdout=output if read else subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
cwd=self.home,
|
||||
env={
|
||||
"PATH": "/usr/local/bin:/usr/bin:/bin",
|
||||
"HOME": str(self.home),
|
||||
"WP_CLI_CONFIG_PATH": "/dev/null",
|
||||
"COULOBRE_WP_LOGIN": login,
|
||||
"LANG": "C.UTF-8",
|
||||
},
|
||||
user=self.uid,
|
||||
group=self.gid,
|
||||
extra_groups=[],
|
||||
umask=0o027,
|
||||
timeout=COMMAND_TIMEOUT,
|
||||
check=False,
|
||||
)
|
||||
if read:
|
||||
output.seek(0)
|
||||
result.stdout = output.read(REPORT_LIMIT)
|
||||
return result
|
||||
|
||||
def require(self, root, description, *arguments, **kwargs):
|
||||
result = self.run(root, *arguments, **kwargs)
|
||||
if result.returncode:
|
||||
raise ValueError(f"WP-CLI could not {description}.")
|
||||
return result
|
||||
|
||||
|
||||
def wordpress_version(cli, root):
|
||||
if not (root / "wp-includes" / "version.php").is_file():
|
||||
return ""
|
||||
version = (
|
||||
cli.require(
|
||||
root, "read the WordPress version", "core", "version", read=True
|
||||
)
|
||||
.stdout.decode("ascii", errors="replace")
|
||||
.strip()
|
||||
)
|
||||
if not VERSION.fullmatch(version):
|
||||
raise ValueError("WP-CLI returned an invalid WordPress version.")
|
||||
cli.require(
|
||||
root, "verify the WordPress installation", "core", "is-installed"
|
||||
)
|
||||
return version
|
||||
|
||||
|
||||
def is_starter_page(index):
|
||||
try:
|
||||
descriptor = os.open(
|
||||
index, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK
|
||||
)
|
||||
except OSError:
|
||||
return False
|
||||
with os.fdopen(descriptor, "rb") as page:
|
||||
return stat.S_ISREG(os.fstat(page.fileno()).st_mode) and page.read(
|
||||
len(web.STARTER_PAGE) + 1
|
||||
) == web.STARTER_PAGE.encode("utf-8")
|
||||
|
||||
|
||||
def check_install_target(public):
|
||||
entries = os.listdir(public)
|
||||
if entries and (
|
||||
entries != ["index.html"] or not is_starter_page(public / "index.html")
|
||||
):
|
||||
raise ValueError(
|
||||
"Use an empty website or the original Coulobre starter page."
|
||||
)
|
||||
|
||||
|
||||
def publish_wordpress(staged, public):
|
||||
check_install_target(public)
|
||||
index = public / "index.html"
|
||||
if not os.path.lexists(index):
|
||||
publish_empty_webroot(staged, public)
|
||||
return
|
||||
# Keep the actual file until the atomic rename has succeeded.
|
||||
saved = staged.parent / "previous-index"
|
||||
os.replace(index, saved)
|
||||
try:
|
||||
if not is_starter_page(saved):
|
||||
raise ValueError("The starter page changed during setup.")
|
||||
publish_empty_webroot(staged, public)
|
||||
except (OSError, ValueError, KeyboardInterrupt):
|
||||
if not staged.exists():
|
||||
raise
|
||||
folder = os.open(public.parent, os.O_RDONLY | os.O_DIRECTORY)
|
||||
try:
|
||||
rename_entry(
|
||||
folder,
|
||||
saved.relative_to(public.parent),
|
||||
index.relative_to(public.parent),
|
||||
)
|
||||
except (OSError, ValueError):
|
||||
recovery = public.parent / f".wordpress-recovery-{uuid4().hex}"
|
||||
os.replace(saved, recovery)
|
||||
raise ValueError(
|
||||
"The document root changed. "
|
||||
f"The previous index is saved at {recovery}."
|
||||
) from None
|
||||
finally:
|
||||
os.close(folder)
|
||||
raise
|
||||
|
||||
|
||||
def open_installation(request, cli, public, uid, web_gid):
|
||||
credentials = read_database_credentials(request.database)
|
||||
with TemporaryDirectory(dir=public.parent, prefix=".wordpress-") as work:
|
||||
parent = Path(work)
|
||||
parent.chmod(0o711)
|
||||
staged = parent / "public"
|
||||
staged.mkdir(mode=0o750)
|
||||
os.chown(staged, uid, web_gid)
|
||||
staged.chmod(0o2750)
|
||||
cli.require(staged, "download WordPress", "core", "download")
|
||||
cli.require(staged, "verify the download", "core", "verify-checksums")
|
||||
cli.require(
|
||||
staged,
|
||||
"configure the managed database",
|
||||
"config",
|
||||
"create",
|
||||
f"--dbname={credentials['database']}",
|
||||
f"--dbuser={credentials['user']}",
|
||||
f"--dbhost=localhost:{credentials['socket']}",
|
||||
"--prompt=dbpass",
|
||||
data=(credentials["password"] + "\n").encode(),
|
||||
)
|
||||
descriptor = os.open(
|
||||
staged / "wp-config.php",
|
||||
os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK,
|
||||
)
|
||||
with os.fdopen(descriptor, "rb") as config:
|
||||
if not stat.S_ISREG(os.fstat(config.fileno()).st_mode):
|
||||
raise ValueError(
|
||||
"WP-CLI did not create its configuration file."
|
||||
)
|
||||
os.fchmod(config.fileno(), 0o600)
|
||||
if cli.run(staged, "core", "is-installed").returncode:
|
||||
cli.require(
|
||||
staged,
|
||||
"install the WordPress site",
|
||||
"core",
|
||||
"install",
|
||||
f"--url=https://{request.site.domain}",
|
||||
f"--title={request.title}",
|
||||
f"--admin_user={request.username}",
|
||||
f"--admin_email={request.email}",
|
||||
"--skip-email",
|
||||
)
|
||||
verify_installed_admin(request, cli, staged)
|
||||
version = wordpress_version(cli, staged)
|
||||
staged.chmod(0o750)
|
||||
publish_wordpress(staged, public)
|
||||
return version
|
||||
|
||||
|
||||
def verify_installed_admin(request, cli, root):
|
||||
user = cli.require(
|
||||
root,
|
||||
"read the initial administrator",
|
||||
"user",
|
||||
"get",
|
||||
request.username,
|
||||
"--fields=user_email,roles",
|
||||
"--format=json",
|
||||
read=True,
|
||||
)
|
||||
try:
|
||||
record = json.loads(user.stdout)
|
||||
correct = (
|
||||
record["user_email"] == request.email
|
||||
and record["roles"] == "administrator"
|
||||
)
|
||||
except (ValueError, KeyError, TypeError):
|
||||
correct = False
|
||||
if not correct:
|
||||
raise ValueError(
|
||||
"The initial WordPress administrator could not be verified."
|
||||
)
|
||||
|
||||
|
||||
def wordpress_install(request, cli, public, uid, web_gid):
|
||||
if (public / "wp-config.php").is_file():
|
||||
database = (
|
||||
cli.require(
|
||||
public,
|
||||
"read the active database",
|
||||
"config",
|
||||
"get",
|
||||
"DB_NAME",
|
||||
"--type=constant",
|
||||
read=True,
|
||||
)
|
||||
.stdout.decode("ascii", errors="replace")
|
||||
.strip()
|
||||
)
|
||||
if database != request.database.name:
|
||||
raise ValueError(
|
||||
"This website already contains a WordPress configuration."
|
||||
)
|
||||
version = wordpress_version(cli, public)
|
||||
if not version:
|
||||
raise ValueError("The live WordPress installation is incomplete.")
|
||||
verify_installed_admin(request, cli, public)
|
||||
return version
|
||||
check_install_target(public)
|
||||
return open_installation(request, cli, public, uid, web_gid)
|
||||
|
||||
|
||||
def apply_wordpress_request(request):
|
||||
if os.geteuid() != 0:
|
||||
raise ValueError("Run WordPress operations on the web node.")
|
||||
try:
|
||||
check_root_file(WP_CLI)
|
||||
except FileNotFoundError:
|
||||
raise ValueError(
|
||||
"Install the verified WP-CLI launcher on the web node."
|
||||
) from None
|
||||
if (
|
||||
request.action != "inspect"
|
||||
and https_status(request.site)["state"] != "configured"
|
||||
):
|
||||
raise ValueError("Set up HTTPS for this website first.")
|
||||
|
||||
mode = fcntl.LOCK_SH if request.action == "inspect" else fcntl.LOCK_EX
|
||||
with web.locked_web_node(mode):
|
||||
if os.path.lexists(website_suspension_path(request.site)):
|
||||
raise ValueError("The website is suspended.")
|
||||
public, uid, web_gid = web.site_storage(request.site)
|
||||
user = web.current_user(request.site.service_user)
|
||||
if user is None or uid == 0 or user.pw_uid != uid:
|
||||
raise ValueError("The website user is unavailable.")
|
||||
runtime = web.SitePaths.for_site(request.site).runtime.version
|
||||
with TemporaryDirectory(prefix="coulobre-wp-cli-") as working:
|
||||
home = Path(working)
|
||||
os.chown(home, uid, user.pw_gid)
|
||||
cli = WordPressCLI(runtime, home, uid, user.pw_gid)
|
||||
try:
|
||||
return apply_site_operation(request, cli, public, uid, web_gid)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise ValueError("The WordPress command timed out.") from None
|
||||
|
||||
|
||||
def apply_site_operation(request, cli, public, uid, web_gid):
|
||||
if request.action == "inspect":
|
||||
return {"wp_version": wordpress_version(cli, public)}
|
||||
if request.action == "install":
|
||||
version = wordpress_install(request, cli, public, uid, web_gid)
|
||||
else:
|
||||
version = wordpress_version(cli, public)
|
||||
if not version:
|
||||
raise ValueError(
|
||||
"Install or import WordPress on this website first."
|
||||
)
|
||||
cli.require(
|
||||
public,
|
||||
"create the administrator. Check the username and email",
|
||||
"user",
|
||||
"create",
|
||||
request.username,
|
||||
request.email,
|
||||
"--role=administrator",
|
||||
"--porcelain",
|
||||
)
|
||||
|
||||
try:
|
||||
status = cli.run(
|
||||
public,
|
||||
"eval",
|
||||
SEND_SETUP_LINK,
|
||||
login=request.username,
|
||||
load_plugins=True,
|
||||
).returncode
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
status = 1
|
||||
return {
|
||||
"wp_version": version,
|
||||
"password_email": "failed" if status else "accepted",
|
||||
}
|
||||
Reference in new issue
Block a user