Add the WordPress workspace and safe archive previews
This commit is contained in:
1 parent
2eada0fd65
commit
040b70fd60
5 files changed
+424
-9
No files matched your search
@@ -76,7 +76,15 @@
|
|||||||
<input type="hidden" name="selection" value="{{ update.kind }}:{{ update.slug }}:{{ update.installed }}:{{ update.version }}">
|
<input type="hidden" name="selection" value="{{ update.kind }}:{{ update.slug }}:{{ update.installed }}:{{ update.version }}">
|
||||||
<button class="button secondary" name="action" value="update" type="submit"{% if jobs and not jobs.0.finished_at %} disabled{% endif %}>Back up and update</button>
|
<button class="button secondary" name="action" value="update" type="submit"{% if jobs and not jobs.0.finished_at %} disabled{% endif %}>Back up and update</button>
|
||||||
</form>
|
</form>
|
||||||
{% else %}—{% endif %}
|
{% endif %}
|
||||||
|
{% if staging %}
|
||||||
|
<form method="post">
|
||||||
|
{% csrf_token %}
|
||||||
|
<input type="hidden" name="site" value="{{ site.domain }}">
|
||||||
|
<input type="hidden" name="selection" value="{{ update.kind }}:{{ update.slug }}:{{ update.installed }}:{{ update.version }}">
|
||||||
|
<button class="button secondary" name="action" value="stage-update" type="submit"{% if jobs and not jobs.0.finished_at %} disabled{% endif %}>Test on staging</button>
|
||||||
|
</form>
|
||||||
|
{% endif %}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
@@ -95,7 +103,7 @@
|
|||||||
<tbody>
|
<tbody>
|
||||||
{% for job in jobs %}
|
{% for job in jobs %}
|
||||||
<tr>
|
<tr>
|
||||||
<th scope="row">{% if job.action == "add-admin" %}Add administrator{% elif job.action == "install" %}Install{% elif job.action == "check-updates" %}Check for updates{% elif job.action == "update" %}Update {{ job.details.update.slug }} to {{ job.details.update.version }}{% else %}Detect{% endif %}</th>
|
<th scope="row">{% if job.action == "add-admin" %}Add administrator{% elif job.action == "install" %}Install{% elif job.action == "check-updates" %}Check for updates{% elif job.action == "update" %}Update {{ job.details.update.slug }} to {{ job.details.update.version }}{% elif job.action == "stage" %}Refresh staging{% elif job.action == "stage-update" %}Test {{ job.details.update.slug }} {{ job.details.update.version }} on staging{% else %}Detect{% endif %}</th>
|
||||||
<td>{{ job.requested_at }}</td>
|
<td>{{ job.requested_at }}</td>
|
||||||
<td>
|
<td>
|
||||||
{% if job.problem %}{{ job.problem }}
|
{% if job.problem %}{{ job.problem }}
|
||||||
@@ -107,6 +115,7 @@
|
|||||||
{% if job.report.password_email == "accepted" %}<br>WordPress accepted the password setup email.
|
{% 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>.
|
{% 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 %}
|
{% endif %}
|
||||||
|
{% if job.report.cleanup_pending %}<br>Staging was updated, but the old revision still needs cleanup on the web node.{% endif %}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
@@ -115,6 +124,22 @@
|
|||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</section>
|
</section>
|
||||||
|
{% if version or staging_form.is_bound or staging %}
|
||||||
|
<section class="surface editor-surface">
|
||||||
|
<header class="section-heading">
|
||||||
|
<h2>WordPress staging</h2>
|
||||||
|
{% if staging %}<a class="button secondary" href="https://{{ staging.report.staging_domain }}/">Open staging</a>{% endif %}
|
||||||
|
</header>
|
||||||
|
<p class="section-text">Refresh the protected staging copy at <strong>staging.{{ site.domain }}</strong>. Changes to an existing staging copy are replaced. The live site is not changed.</p>
|
||||||
|
<p class="section-text">Ask your server operator to prepare DNS, HTTPS and the staging login before the first refresh.</p>
|
||||||
|
<form method="post" class="editor">
|
||||||
|
{% csrf_token %}
|
||||||
|
<input type="hidden" name="site" value="{{ site.domain }}">
|
||||||
|
{{ staging_form.as_div }}
|
||||||
|
<button class="button primary" name="action" value="stage" type="submit"{% if jobs and not jobs.0.finished_at %} disabled{% endif %}>Refresh from live</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
{% endif %}
|
||||||
{% if version or admin_form.is_bound %}
|
{% if version or admin_form.is_bound %}
|
||||||
<section class="surface editor-surface">
|
<section class="surface editor-surface">
|
||||||
<header class="section-heading"><h2>Add a WordPress administrator</h2></header>
|
<header class="section-heading"><h2>Add a WordPress administrator</h2></header>
|
||||||
@@ -138,6 +163,24 @@
|
|||||||
</form>
|
</form>
|
||||||
</section>
|
</section>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
<section class="surface editor-surface">
|
||||||
|
<header class="section-heading"><h2>Preview a WordPress import</h2></header>
|
||||||
|
<p class="section-text">Upload a ZIP or TAR export with the full WordPress installation in <code>files/</code> and one <code>database.sql</code> at the archive root. Preview does not change any files or databases.</p>
|
||||||
|
<form method="post" class="editor" enctype="multipart/form-data">
|
||||||
|
{% csrf_token %}
|
||||||
|
<input type="hidden" name="site" value="{{ site.domain }}">
|
||||||
|
{{ import_form.as_div }}
|
||||||
|
<button class="button secondary" name="action" value="import-preview" type="submit">Preview import</button>
|
||||||
|
</form>
|
||||||
|
{% if import_summary %}
|
||||||
|
<dl class="details" aria-label="Import preview">
|
||||||
|
<div><dt>Destination</dt><dd>{{ site.domain }}</dd></div>
|
||||||
|
<div><dt>Archive</dt><dd>{{ import_summary.format }}</dd></div>
|
||||||
|
<div><dt>Site files</dt><dd>{{ import_summary.file_count }} · {{ import_summary.site_bytes|filesizeformat }}</dd></div>
|
||||||
|
<div><dt>Database dump</dt><dd>{{ import_summary.sql_bytes|filesizeformat }}</dd></div>
|
||||||
|
</dl>
|
||||||
|
{% endif %}
|
||||||
|
</section>
|
||||||
{% else %}
|
{% else %}
|
||||||
<p class="notice">Activate a website on this hosting account first.</p>
|
<p class="notice">Activate a website on this hosting account first.</p>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ from uuid import uuid4
|
|||||||
from zipfile import ZipFile
|
from zipfile import ZipFile
|
||||||
|
|
||||||
from django.contrib.auth import get_user_model
|
from django.contrib.auth import get_user_model
|
||||||
|
from django.core.files.uploadedfile import SimpleUploadedFile
|
||||||
from django.test import SimpleTestCase, TestCase, override_settings
|
from django.test import SimpleTestCase, TestCase, override_settings
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
@@ -24,12 +25,15 @@ from coulobre.wordpress_updates import WordPressUpdate
|
|||||||
|
|
||||||
from .models import (
|
from .models import (
|
||||||
Customer,
|
Customer,
|
||||||
|
DatabaseProvisioning,
|
||||||
HostingAccount,
|
HostingAccount,
|
||||||
|
HostingDatabase,
|
||||||
WebActivation,
|
WebActivation,
|
||||||
WebProvisioningPlan,
|
WebProvisioningPlan,
|
||||||
WordPressJob,
|
WordPressJob,
|
||||||
)
|
)
|
||||||
from .tasks import dispatch_web_activations, run_wordpress_job
|
from .tasks import dispatch_web_activations, run_wordpress_job
|
||||||
|
from .test_wordpress_import import export_zip
|
||||||
|
|
||||||
|
|
||||||
class InstallRequestTests(SimpleTestCase):
|
class InstallRequestTests(SimpleTestCase):
|
||||||
@@ -240,6 +244,92 @@ class WordPressWorkflowTests(TestCase):
|
|||||||
self.assertEqual(next_job.state, "failed")
|
self.assertEqual(next_job.state, "failed")
|
||||||
self.assertEqual(self.client.get(self.url).status_code, 404)
|
self.assertEqual(self.client.get(self.url).status_code, 404)
|
||||||
|
|
||||||
|
def test_import_preview_reports_destination_without_a_write(self):
|
||||||
|
response = self.client.post(
|
||||||
|
self.url,
|
||||||
|
{
|
||||||
|
"site": self.account.primary_domain,
|
||||||
|
"action": "import-preview",
|
||||||
|
"archive": SimpleUploadedFile(
|
||||||
|
"wordpress.zip", export_zip().getvalue()
|
||||||
|
),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
self.assertContains(response, "Import preview")
|
||||||
|
self.assertContains(response, self.account.primary_domain)
|
||||||
|
self.assertEqual(response.context["import_summary"]["sql_bytes"], 9)
|
||||||
|
self.assertFalse(self.account.wordpress_jobs.exists())
|
||||||
|
self.assertFalse(self.account.databases.exists())
|
||||||
|
|
||||||
|
@patch("coulobre.hosting.node_client.apply_on_local_node")
|
||||||
|
def test_stage_refresh_and_test_update_use_separate_revision(self, apply):
|
||||||
|
database = HostingDatabase.objects.create(
|
||||||
|
account=self.account, suffix="wordpress"
|
||||||
|
)
|
||||||
|
DatabaseProvisioning.objects.create(
|
||||||
|
database=database, finished_at=timezone.now()
|
||||||
|
)
|
||||||
|
data = self.data | {
|
||||||
|
"action": "stage",
|
||||||
|
"database_id": database.pk,
|
||||||
|
"confirmed": "",
|
||||||
|
}
|
||||||
|
self.assertContains(
|
||||||
|
self.client.post(self.url, data), "This field is required"
|
||||||
|
)
|
||||||
|
self.assertFalse(self.account.wordpress_jobs.exists())
|
||||||
|
self.assertEqual(
|
||||||
|
self.client.post(self.url, data | {"confirmed": "on"}).status_code,
|
||||||
|
302,
|
||||||
|
)
|
||||||
|
stage = self.account.wordpress_jobs.get()
|
||||||
|
candidate = stage.details["candidate"]
|
||||||
|
self.assertEqual(
|
||||||
|
candidate["domain"], f"staging.{self.account.primary_domain}"
|
||||||
|
)
|
||||||
|
report = {
|
||||||
|
"wp_version": "7.0",
|
||||||
|
"staging_domain": candidate["domain"],
|
||||||
|
"staging_revision": candidate["revision"],
|
||||||
|
}
|
||||||
|
apply.return_value = report
|
||||||
|
run_wordpress_job.run(stage.pk)
|
||||||
|
stage.refresh_from_db()
|
||||||
|
self.assertEqual(stage.state, "configured")
|
||||||
|
self.assertContains(self.client.get(self.url), "Open staging")
|
||||||
|
|
||||||
|
selection = {
|
||||||
|
"kind": "core",
|
||||||
|
"slug": "wordpress",
|
||||||
|
"installed": "7.0",
|
||||||
|
"version": "7.1",
|
||||||
|
}
|
||||||
|
self.account.wordpress_jobs.create(
|
||||||
|
action="check-updates",
|
||||||
|
actor=self.customer.user,
|
||||||
|
site=stage.site,
|
||||||
|
finished_at=timezone.now(),
|
||||||
|
report={"version": "7.0", "updates": [selection]},
|
||||||
|
)
|
||||||
|
self.assertContains(self.client.get(self.url), "Test on staging")
|
||||||
|
response = self.client.post(
|
||||||
|
self.url,
|
||||||
|
data
|
||||||
|
| {
|
||||||
|
"action": "stage-update",
|
||||||
|
"selection": "core:wordpress:7.0:7.1",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 302)
|
||||||
|
update = self.account.wordpress_jobs.latest("pk")
|
||||||
|
self.assertEqual(update.details["staging"], candidate)
|
||||||
|
self.assertFalse(self.account.backup_jobs.exists())
|
||||||
|
apply.return_value = report | {"wp_version": "7.1"}
|
||||||
|
run_wordpress_job.run(update.pk)
|
||||||
|
update.refresh_from_db()
|
||||||
|
self.assertEqual(update.state, "configured")
|
||||||
|
self.assertEqual(update.report["version"], "7.1")
|
||||||
|
|
||||||
def test_site_selection_stays_within_the_account(self):
|
def test_site_selection_stays_within_the_account(self):
|
||||||
response = self.client.post(
|
response = self.client.post(
|
||||||
self.url, self.data | {"site": "outside.test"}
|
self.url, self.data | {"site": "outside.test"}
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import stat
|
||||||
|
from io import BytesIO
|
||||||
|
from tarfile import TarFile, TarInfo
|
||||||
|
from unittest.mock import patch
|
||||||
|
from zipfile import ZipFile, ZipInfo
|
||||||
|
|
||||||
|
from django.test import SimpleTestCase
|
||||||
|
|
||||||
|
from coulobre.wordpress_import import REQUIRED_FILES, inspect_export
|
||||||
|
from coulobre.wordpress_staging_updates import package_url
|
||||||
|
from coulobre.wordpress_updates import WordPressUpdate
|
||||||
|
|
||||||
|
|
||||||
|
def export_zip(*extra):
|
||||||
|
buffer = BytesIO()
|
||||||
|
with ZipFile(buffer, "w") as archive:
|
||||||
|
for path in sorted(REQUIRED_FILES):
|
||||||
|
archive.writestr(path, b"<?php")
|
||||||
|
archive.writestr("database.sql", b"SELECT 1;")
|
||||||
|
for path, body in extra:
|
||||||
|
archive.writestr(path, body)
|
||||||
|
return buffer
|
||||||
|
|
||||||
|
|
||||||
|
class WordPressImportInspectionTests(SimpleTestCase):
|
||||||
|
def test_zip_and_compressed_tar_report_unpacked_sizes(self):
|
||||||
|
data = {
|
||||||
|
"database.sql": b"SELECT 1;",
|
||||||
|
**dict.fromkeys(REQUIRED_FILES, b"<?php"),
|
||||||
|
}
|
||||||
|
source = BytesIO()
|
||||||
|
with TarFile.open(fileobj=source, mode="w:gz") as archive:
|
||||||
|
for name, body in data.items():
|
||||||
|
member = TarInfo(name)
|
||||||
|
member.size = len(body)
|
||||||
|
archive.addfile(member, BytesIO(body))
|
||||||
|
for archive, label in ((export_zip(), "ZIP"), (source, "TAR")):
|
||||||
|
with self.subTest(format=label):
|
||||||
|
result = inspect_export(archive)
|
||||||
|
self.assertEqual(
|
||||||
|
result,
|
||||||
|
{
|
||||||
|
"format": label,
|
||||||
|
"file_count": 3,
|
||||||
|
"site_bytes": 15,
|
||||||
|
"sql_bytes": 9,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
self.assertEqual(archive.tell(), 0)
|
||||||
|
|
||||||
|
def test_rejects_traversal_links_and_conflicting_parents(self):
|
||||||
|
link = ZipInfo("files/path")
|
||||||
|
link.external_attr = (stat.S_IFLNK | 0o777) << 16
|
||||||
|
examples = (
|
||||||
|
(export_zip(("files/../../escape", b"escape")), "unsafe path"),
|
||||||
|
(export_zip((link, b"/etc/passwd")), "regular files"),
|
||||||
|
(
|
||||||
|
export_zip(("files/data", b"a"), ("files/data/entry", b"b")),
|
||||||
|
"also contain other entries",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
for source, problem in examples:
|
||||||
|
with (
|
||||||
|
self.subTest(error=problem),
|
||||||
|
self.assertRaisesRegex(ValueError, problem),
|
||||||
|
):
|
||||||
|
inspect_export(source)
|
||||||
|
|
||||||
|
def test_limits_apply_to_expanded_size_and_entry_count(self):
|
||||||
|
with (
|
||||||
|
patch("coulobre.wordpress_import.MAX_EXPANDED_BYTES", 10),
|
||||||
|
self.assertRaisesRegex(ValueError, "expanded archive"),
|
||||||
|
):
|
||||||
|
inspect_export(export_zip())
|
||||||
|
with (
|
||||||
|
patch("coulobre.wordpress_import.MAX_ARCHIVE_ENTRIES", 2),
|
||||||
|
self.assertRaisesRegex(ValueError, "too many entries"),
|
||||||
|
):
|
||||||
|
inspect_export(export_zip())
|
||||||
|
|
||||||
|
|
||||||
|
class WordPressStagingDownloadTests(SimpleTestCase):
|
||||||
|
def test_urls_have_a_fixed_provider_and_validated_path_components(self):
|
||||||
|
for kind, slug, suffix in (
|
||||||
|
("core", "wordpress", "release/wordpress-7.1-no-content.zip"),
|
||||||
|
("theme", "example", "theme/example.7.1.zip"),
|
||||||
|
("plugin", "example", "plugin/example.7.1.zip"),
|
||||||
|
):
|
||||||
|
with self.subTest(kind=kind):
|
||||||
|
update = WordPressUpdate(kind, slug, "7.0", "7.1")
|
||||||
|
self.assertEqual(
|
||||||
|
package_url(update),
|
||||||
|
f"https://downloads.wordpress.org/{suffix}",
|
||||||
|
)
|
||||||
@@ -10,6 +10,7 @@ from django.views.decorators.cache import never_cache
|
|||||||
from django.views.generic.detail import SingleObjectMixin
|
from django.views.generic.detail import SingleObjectMixin
|
||||||
|
|
||||||
from coulobre.wordpress import LOGIN
|
from coulobre.wordpress import LOGIN
|
||||||
|
from coulobre.wordpress_import import inspect_export
|
||||||
from coulobre.wordpress_updates import WordPressUpdate
|
from coulobre.wordpress_updates import WordPressUpdate
|
||||||
|
|
||||||
from .access import TenantScopeMixin, customer_for_user, is_tenant
|
from .access import TenantScopeMixin, customer_for_user, is_tenant
|
||||||
@@ -21,9 +22,11 @@ from .wordpress_management import (
|
|||||||
can_manage_wordpress,
|
can_manage_wordpress,
|
||||||
can_recover_updates,
|
can_recover_updates,
|
||||||
current_update_inventory,
|
current_update_inventory,
|
||||||
|
published_staging,
|
||||||
queue_wordpress_job,
|
queue_wordpress_job,
|
||||||
update_database,
|
update_database,
|
||||||
wordpress_available,
|
wordpress_available,
|
||||||
|
wordpress_staging_databases,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -54,6 +57,33 @@ class WordPressUpdateForm(forms.Form):
|
|||||||
) from None
|
) from None
|
||||||
|
|
||||||
|
|
||||||
|
class WordPressStagingForm(forms.Form):
|
||||||
|
database_id = forms.ModelChoiceField(
|
||||||
|
label="Live WordPress database", queryset=None
|
||||||
|
)
|
||||||
|
confirmed = forms.BooleanField(
|
||||||
|
label="Replace the staging copy with the current live site"
|
||||||
|
)
|
||||||
|
|
||||||
|
def __init__(self, account, *args, **kwargs):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
self.fields["database_id"].queryset = wordpress_staging_databases(
|
||||||
|
account
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class WordPressImportPreviewForm(forms.Form):
|
||||||
|
archive = forms.FileField(label="WordPress ZIP or TAR export")
|
||||||
|
|
||||||
|
def clean_archive(self):
|
||||||
|
uploaded = self.cleaned_data["archive"]
|
||||||
|
try:
|
||||||
|
self.summary = inspect_export(uploaded)
|
||||||
|
except ValueError as error:
|
||||||
|
raise ValidationError(str(error)) from error
|
||||||
|
return uploaded
|
||||||
|
|
||||||
|
|
||||||
@method_decorator(never_cache, name="dispatch")
|
@method_decorator(never_cache, name="dispatch")
|
||||||
class AccountWordPressView(
|
class AccountWordPressView(
|
||||||
TenantScopeMixin, PermissionRequiredMixin, SingleObjectMixin, View
|
TenantScopeMixin, PermissionRequiredMixin, SingleObjectMixin, View
|
||||||
@@ -92,24 +122,40 @@ class AccountWordPressView(
|
|||||||
def post(self, request, *args, **kwargs):
|
def post(self, request, *args, **kwargs):
|
||||||
self.select_site(request.POST.get("site"))
|
self.select_site(request.POST.get("site"))
|
||||||
action = request.POST.get("action")
|
action = request.POST.get("action")
|
||||||
|
if action == "import-preview" and self.site is not None:
|
||||||
|
preview = WordPressImportPreviewForm(request.POST, request.FILES)
|
||||||
|
valid = preview.is_valid()
|
||||||
|
return self.page(
|
||||||
|
action=action,
|
||||||
|
form=preview,
|
||||||
|
import_summary=preview.summary if valid else None,
|
||||||
|
)
|
||||||
forms_for_action = {
|
forms_for_action = {
|
||||||
"inspect": forms.Form,
|
"inspect": forms.Form,
|
||||||
"check-updates": forms.Form,
|
"check-updates": forms.Form,
|
||||||
"update": WordPressUpdateForm,
|
"update": WordPressUpdateForm,
|
||||||
"install": WordPressInstallForm,
|
"install": WordPressInstallForm,
|
||||||
"add-admin": AdministratorForm,
|
"add-admin": AdministratorForm,
|
||||||
|
"stage": WordPressStagingForm,
|
||||||
|
"stage-update": WordPressUpdateForm,
|
||||||
}
|
}
|
||||||
if self.site is None or action not in forms_for_action:
|
if self.site is None or action not in forms_for_action:
|
||||||
raise Http404
|
raise Http404
|
||||||
form = forms_for_action[action](request.POST)
|
form = (
|
||||||
|
WordPressStagingForm(self.account, request.POST)
|
||||||
|
if action == "stage"
|
||||||
|
else forms_for_action[action](request.POST)
|
||||||
|
)
|
||||||
if form.is_valid():
|
if form.is_valid():
|
||||||
details = {
|
details = {
|
||||||
name: value
|
name: value
|
||||||
for name, value in form.cleaned_data.items()
|
for name, value in form.cleaned_data.items()
|
||||||
if name != "confirmed"
|
if name != "confirmed"
|
||||||
}
|
}
|
||||||
if action == "update":
|
if action in ("update", "stage-update"):
|
||||||
details = {"update": details["selection"]}
|
details = {"update": details["selection"]}
|
||||||
|
if action == "stage":
|
||||||
|
details = {"database_id": details["database_id"].pk}
|
||||||
try:
|
try:
|
||||||
queue_wordpress_job(
|
queue_wordpress_job(
|
||||||
self.account, self.site, request.user, action, details
|
self.account, self.site, request.user, action, details
|
||||||
@@ -123,19 +169,23 @@ class AccountWordPressView(
|
|||||||
return redirect(f"{destination}?site={self.site.domain}")
|
return redirect(f"{destination}?site={self.site.domain}")
|
||||||
return self.page(action=action, form=form)
|
return self.page(action=action, form=form)
|
||||||
|
|
||||||
def page(self, *, action=None, form=None):
|
def page(self, *, action=None, form=None, import_summary=None):
|
||||||
jobs = ()
|
jobs = ()
|
||||||
known_version = ""
|
known_version = ""
|
||||||
inventory = {}
|
inventory = {}
|
||||||
|
staging = None
|
||||||
if self.site:
|
if self.site:
|
||||||
history = self.account.wordpress_jobs.filter(
|
history = self.account.wordpress_jobs.filter(
|
||||||
site=self.site.manifest()
|
site=self.site.manifest()
|
||||||
).order_by("-pk")
|
).order_by("-pk")
|
||||||
jobs = list(history.select_related("backup")[:10])
|
jobs = list(history.select_related("backup")[:10])
|
||||||
inventory = current_update_inventory(history)
|
inventory = current_update_inventory(history)
|
||||||
last = history.filter(
|
staging = published_staging(history)
|
||||||
finished_at__isnull=False, problem=""
|
last = (
|
||||||
).first()
|
history.exclude(action__in=("stage", "stage-update"))
|
||||||
|
.filter(finished_at__isnull=False, problem="")
|
||||||
|
.first()
|
||||||
|
)
|
||||||
if last:
|
if last:
|
||||||
known_version = last.report.get("version", "")
|
known_version = last.report.get("version", "")
|
||||||
user = self.request.user
|
user = self.request.user
|
||||||
@@ -160,9 +210,25 @@ class AccountWordPressView(
|
|||||||
"version": known_version,
|
"version": known_version,
|
||||||
"jobs": jobs,
|
"jobs": jobs,
|
||||||
"operation_errors": form.errors
|
"operation_errors": form.errors
|
||||||
if action in ("inspect", "check-updates", "update")
|
if action
|
||||||
|
in ("inspect", "check-updates", "update", "stage-update")
|
||||||
else (),
|
else (),
|
||||||
"inventory": inventory,
|
"inventory": inventory,
|
||||||
|
"import_summary": import_summary,
|
||||||
|
"import_form": form
|
||||||
|
if action == "import-preview"
|
||||||
|
else WordPressImportPreviewForm(),
|
||||||
|
"staging": staging,
|
||||||
|
"staging_form": form
|
||||||
|
if action == "stage"
|
||||||
|
else WordPressStagingForm(
|
||||||
|
self.account,
|
||||||
|
initial={
|
||||||
|
"database_id": update_database(
|
||||||
|
self.account, inventory.get("database_name")
|
||||||
|
)
|
||||||
|
},
|
||||||
|
),
|
||||||
"updates_can_recover": can_recover_updates(),
|
"updates_can_recover": can_recover_updates(),
|
||||||
"updates_has_database": update_database(
|
"updates_has_database": update_database(
|
||||||
self.account, inventory.get("database_name")
|
self.account, inventory.get("database_name")
|
||||||
|
|||||||
@@ -0,0 +1,122 @@
|
|||||||
|
"""Inspect WordPress exports without extracting them."""
|
||||||
|
|
||||||
|
import stat
|
||||||
|
from pathlib import PurePosixPath
|
||||||
|
from tarfile import TarError, TarFile
|
||||||
|
from zipfile import BadZipFile, ZipFile, is_zipfile
|
||||||
|
|
||||||
|
MAX_ARCHIVE_BYTES = 2 * 1024**3
|
||||||
|
MAX_EXPANDED_BYTES = 4 * 1024**3
|
||||||
|
MAX_ARCHIVE_ENTRIES = 100_000
|
||||||
|
REQUIRED_FILES = {
|
||||||
|
"files/wp-load.php",
|
||||||
|
"files/wp-admin/admin.php",
|
||||||
|
"files/wp-includes/version.php",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def archive_name(name):
|
||||||
|
name = name.removesuffix("/")
|
||||||
|
path = PurePosixPath(name)
|
||||||
|
if (
|
||||||
|
not name
|
||||||
|
or path.as_posix() != name
|
||||||
|
or path.is_absolute()
|
||||||
|
or ".." in path.parts
|
||||||
|
or "\\" in name
|
||||||
|
or any(ord(char) < 32 or ord(char) == 127 for char in name)
|
||||||
|
or len(name.encode("utf-8")) > 1024
|
||||||
|
or any(len(part.encode("utf-8")) > 255 for part in path.parts)
|
||||||
|
):
|
||||||
|
raise ValueError("The archive contains an unsafe path.")
|
||||||
|
if path.parts[0] != "files" and name != "database.sql":
|
||||||
|
raise ValueError(
|
||||||
|
"The archive root must contain only files/ and database.sql."
|
||||||
|
)
|
||||||
|
return name
|
||||||
|
|
||||||
|
|
||||||
|
def zip_entries(archive):
|
||||||
|
for member in archive.infolist():
|
||||||
|
kind = stat.S_IFMT(member.external_attr >> 16)
|
||||||
|
is_directory = member.is_dir()
|
||||||
|
if (
|
||||||
|
kind not in (0, stat.S_IFREG, stat.S_IFDIR)
|
||||||
|
or kind == stat.S_IFDIR
|
||||||
|
and not is_directory
|
||||||
|
or kind == stat.S_IFREG
|
||||||
|
and is_directory
|
||||||
|
or is_directory
|
||||||
|
and member.file_size != 0
|
||||||
|
):
|
||||||
|
raise ValueError("Use only regular files and directories.")
|
||||||
|
if member.flag_bits & 1:
|
||||||
|
raise ValueError("Use an archive without password protection.")
|
||||||
|
yield member.orig_filename, is_directory, member.file_size
|
||||||
|
|
||||||
|
|
||||||
|
def tar_entries(archive):
|
||||||
|
for member in archive:
|
||||||
|
if not (member.isdir() or member.isreg()) or member.issparse():
|
||||||
|
raise ValueError("Use only regular files and directories.")
|
||||||
|
if member.isdir() and member.size != 0:
|
||||||
|
raise ValueError("The TAR has an invalid directory entry.")
|
||||||
|
yield member.name, member.isdir(), member.size
|
||||||
|
|
||||||
|
|
||||||
|
def inspect_entries(entries, archive_type):
|
||||||
|
paths = {}
|
||||||
|
total = sql = files = 0
|
||||||
|
for name, directory, size in entries:
|
||||||
|
name = archive_name(name)
|
||||||
|
if name in paths:
|
||||||
|
raise ValueError(f"The archive lists {name} more than once.")
|
||||||
|
if len(paths) >= MAX_ARCHIVE_ENTRIES:
|
||||||
|
raise ValueError("The archive has too many entries.")
|
||||||
|
if size < 0 or total + size > MAX_EXPANDED_BYTES:
|
||||||
|
raise ValueError("The expanded archive exceeds 4 GiB.")
|
||||||
|
total += size
|
||||||
|
paths[name] = directory
|
||||||
|
if name == "files" and not directory:
|
||||||
|
raise ValueError("files must be a directory.")
|
||||||
|
if name == "database.sql":
|
||||||
|
if directory or size == 0:
|
||||||
|
raise ValueError("Provide a nonempty database.sql file.")
|
||||||
|
sql = size
|
||||||
|
elif not directory:
|
||||||
|
files += 1
|
||||||
|
|
||||||
|
if not sql:
|
||||||
|
raise ValueError("Add database.sql at the root of the archive.")
|
||||||
|
if any(paths.get(name, True) for name in REQUIRED_FILES):
|
||||||
|
raise ValueError("Include the full WordPress installation in files/.")
|
||||||
|
for name in paths:
|
||||||
|
for parent in PurePosixPath(name).parents:
|
||||||
|
if paths.get(parent.as_posix()) is False:
|
||||||
|
raise ValueError("A file cannot also contain other entries.")
|
||||||
|
return {
|
||||||
|
"format": archive_type,
|
||||||
|
"file_count": files,
|
||||||
|
"site_bytes": total - sql,
|
||||||
|
"sql_bytes": sql,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def inspect_export(source):
|
||||||
|
source.seek(0, 2)
|
||||||
|
if not 0 < source.tell() <= MAX_ARCHIVE_BYTES:
|
||||||
|
raise ValueError("The upload must be no larger than 2 GiB.")
|
||||||
|
source.seek(0)
|
||||||
|
try:
|
||||||
|
zip_format = is_zipfile(source)
|
||||||
|
source.seek(0)
|
||||||
|
if zip_format:
|
||||||
|
with ZipFile(source) as archive:
|
||||||
|
return inspect_entries(zip_entries(archive), "ZIP")
|
||||||
|
# Iterate so entry and size limits apply during inspection.
|
||||||
|
with TarFile.open(fileobj=source, mode="r|*") as archive:
|
||||||
|
return inspect_entries(tar_entries(archive), "TAR")
|
||||||
|
except (OSError, EOFError, BadZipFile, TarError, UnicodeError) as error:
|
||||||
|
raise ValueError("Upload a readable ZIP or TAR archive.") from error
|
||||||
|
finally:
|
||||||
|
source.seek(0)
|
||||||
Reference in new issue
Block a user