Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
153 changes: 143 additions & 10 deletions includes/class-opentrust-admin-tools.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,110 @@ private function __construct() {
add_action('admin_post_opentrust_export', [$this, 'handle_export']);
add_action('admin_post_opentrust_import_preview', [$this, 'handle_import_preview']);
add_action('admin_post_opentrust_import_apply', [$this, 'handle_import_apply']);
add_action('opentrust_io_preview_cleanup', [$this, 'cleanup_preview_file'], 10, 2);
}

/**
* Absolute path to the private stash directory used for import-preview ZIPs.
*
* Sits under wp-content/uploads/opentrust-tmp/. Returns the canonical (realpath)
* directory when it exists so callers can compare paths safely.
*/
private function stash_dir(): string {
$upload_dir = wp_upload_dir();
$base = isset($upload_dir['basedir']) ? rtrim((string) $upload_dir['basedir'], '/\\') : '';
return $base === '' ? '' : $base . '/opentrust-tmp';
}

/**
* Ensure the private stash directory exists with deny-all protection,
* then redirect wp_handle_upload() into it via a scoped upload_dir filter.
*
* Returns the filter closure so the caller can remove it immediately after
* wp_handle_upload() returns — the redirection MUST NOT leak into any other
* upload code paths in the same request.
*/
private function install_stash_upload_filter(): ?\Closure {
$stash_dir = $this->stash_dir();
if ($stash_dir === '') {
return null;
}

if (!wp_mkdir_p($stash_dir)) {
return null;
}

// Deny-all protections. .htaccess covers Apache; index.html covers
// directory-listing fallback when web servers don't honour .htaccess.
$htaccess = $stash_dir . '/.htaccess';
if (!file_exists($htaccess)) {
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- Hardening file for a plugin-private dir; WP_Filesystem is disproportionate for a one-time write of a 36-byte deny rule.
@file_put_contents($htaccess, "Require all denied\nDeny from all\n");
}
$index = $stash_dir . '/index.html';
if (!file_exists($index)) {
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- Empty index for directory-listing defence; WP_Filesystem is disproportionate for a one-time zero-byte write.
@file_put_contents($index, '');
}

$upload_dir = wp_upload_dir();
$base_url = isset($upload_dir['baseurl']) ? rtrim((string) $upload_dir['baseurl'], '/\\') : '';
$upload_url = $base_url === '' ? '' : $base_url . '/opentrust-tmp';

$filter = static function (array $dirs) use ($stash_dir, $upload_url): array {
$dirs['path'] = $stash_dir;
$dirs['url'] = $upload_url;
$dirs['subdir'] = '';
return $dirs;
};

add_filter('upload_dir', $filter);
return $filter;
}

/**
* Scheduled handler — wp_cron fires this 30 minutes after preview creation.
*
* Deletes the stashed ZIP if (a) it still lives inside the canonical stash
* directory and (b) the user's preview transient no longer references it
* (handle_import_apply has already cleaned up the active preview path).
*/
public function cleanup_preview_file(string $path, int $user_id): void {
if ($path === '') {
return;
}

$stash_dir = $this->stash_dir();
if ($stash_dir === '') {
return;
}

$canonical_stash = realpath($stash_dir);
$canonical_path = realpath($path);
if ($canonical_stash === false || $canonical_path === false) {
return;
}

// Strict containment check: canonical path must start with the canonical
// stash dir + separator. Substring-only matches (str_contains) would let
// a path like /var/uploads/opentrust-tmp-evil/foo.zip slip through.
$stash_prefix = rtrim($canonical_stash, '/\\') . DIRECTORY_SEPARATOR;
if (!str_starts_with($canonical_path, $stash_prefix)) {
return;
}

// If the user's preview transient still points at this exact file, an
// import is mid-flight — defer to handle_import_apply()'s wp_delete_file().
if ($user_id > 0) {
$preview = get_transient('opentrust_io_preview_' . $user_id);
if (is_array($preview) && isset($preview['zip_path']) && (string) $preview['zip_path'] === $path) {
return;
}
}

if (is_file($canonical_path)) {
wp_delete_file($canonical_path);
}
}

// ──────────────────────────────────────────────
Expand Down Expand Up @@ -318,21 +422,40 @@ public function handle_import_preview(): void {
return;
}

// Park the upload between preview and apply. Path goes in a per-user transient.
$upload_dir = wp_upload_dir();
$stash_dir = rtrim((string) $upload_dir['basedir'], '/') . '/opentrust-tmp';
wp_mkdir_p($stash_dir);
if (!file_exists($stash_dir . '/.htaccess')) {
@file_put_contents($stash_dir . '/.htaccess', "Require all denied\n");
// wp_handle_upload() lives here; idempotent require for WP-CLI / alt call paths.
require_once ABSPATH . 'wp-admin/includes/file.php';

// Scope an upload_dir filter to redirect wp_handle_upload() into our
// plugin-private stash dir (wp-content/uploads/opentrust-tmp/ with a
// deny-all .htaccess + blank index.html). The filter is added immediately
// before wp_handle_upload() and removed immediately after so no other
// upload code path in this request is affected.
$upload_filter = $this->install_stash_upload_filter();

// test_form=false because our admin-post action is opentrust_import_preview,
// not the 'wp_handle_upload' token wp_handle_upload() checks for by default.
// mimes is narrowed to ZIP only — finfo magic-byte detection promotes Safari's
// application/x-zip-compressed to application/zip, so one entry covers all
// browsers without tripping the get_allowed_mime_types() global allowlist.
$upload = wp_handle_upload(
$_FILES['ot_import_file'],
[
'test_form' => false,
'mimes' => ['zip' => 'application/zip'],
]
);

if ($upload_filter !== null) {
remove_filter('upload_dir', $upload_filter);
}
$stash_path = $stash_dir . '/import-' . wp_generate_password(12, false) . '.zip';

// phpcs:ignore Generic.PHP.ForbiddenFunctions.Found -- Required for $_FILES handling. Higher-level WP wrappers impose a MIME allowlist that rejects file types we deliberately accept (admin-only, nonce + size cap + is_uploaded_file already gate this path).
if (!move_uploaded_file((string) $_FILES['ot_import_file']['tmp_name'], $stash_path)) {
$this->bounce_error(__('Could not store uploaded file.', 'opentrust'));
if (isset($upload['error'])) {
$this->bounce_error((string) $upload['error']);
return;
}

$stash_path = (string) $upload['file'];

try {
$read = OpenTrust_IO::read_zip($stash_path);
$manifest = $read['manifest'];
Expand All @@ -357,6 +480,16 @@ public function handle_import_preview(): void {
}

set_transient('opentrust_io_preview_' . get_current_user_id(), $preview, 30 * MINUTE_IN_SECONDS);

// Belt-and-suspenders cleanup: schedule a single-event deletion of the
// stashed ZIP keyed to the transient TTL. Covers the abandon-the-preview
// case where the admin never returns to confirm or cancel. The handler
// re-checks containment and skips if an import is mid-flight.
wp_schedule_single_event(
time() + 30 * MINUTE_IN_SECONDS,
'opentrust_io_preview_cleanup',
[$stash_path, get_current_user_id()]
);
} catch (\Throwable $e) {
wp_delete_file($stash_path);
$this->bounce_error($e->getMessage());
Expand Down
26 changes: 11 additions & 15 deletions languages/opentrust.pot
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ msgstr ""
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"POT-Creation-Date: 2026-05-11T15:00:11+00:00\n"
"POT-Creation-Date: 2026-05-12T20:24:14+00:00\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"X-Generator: WP-CLI 2.12.0\n"
"X-Domain: opentrust\n"
Expand Down Expand Up @@ -322,7 +322,7 @@ msgstr ""
#: includes/class-opentrust-admin-questions.php:219
#: includes/class-opentrust-admin-questions.php:260
#: includes/class-opentrust-admin-questions.php:277
#: includes/class-opentrust-admin-tools.php:432
#: includes/class-opentrust-admin-tools.php:440
msgid "You do not have permission to perform this action."
msgstr ""

Expand Down Expand Up @@ -760,7 +760,7 @@ msgid "Certifications & Compliance"
msgstr ""

#: includes/class-opentrust-admin-settings.php:323
#: includes/class-opentrust-admin-tools.php:459
#: includes/class-opentrust-admin-tools.php:467
#: includes/class-opentrust-cpt.php:151
#: includes/class-opentrust-cpt.php:161
#: templates/chat.php:45
Expand All @@ -770,7 +770,7 @@ msgid "Policies"
msgstr ""

#: includes/class-opentrust-admin-settings.php:324
#: includes/class-opentrust-admin-tools.php:461
#: includes/class-opentrust-admin-tools.php:469
#: includes/class-opentrust-cpt.php:218
#: includes/class-opentrust-cpt.php:227
#: templates/chat.php:47
Expand All @@ -781,7 +781,7 @@ msgid "Subprocessors"
msgstr ""

#: includes/class-opentrust-admin-settings.php:325
#: includes/class-opentrust-admin-tools.php:462
#: includes/class-opentrust-admin-tools.php:470
#: includes/class-opentrust-cpt.php:251
#: includes/class-opentrust-cpt.php:260
#: templates/chat.php:48
Expand All @@ -791,7 +791,7 @@ msgid "Data Practices"
msgstr ""

#: includes/class-opentrust-admin-settings.php:326
#: includes/class-opentrust-admin-tools.php:463
#: includes/class-opentrust-admin-tools.php:471
#: includes/class-opentrust-cpt.php:284
#: includes/class-opentrust-cpt.php:294
msgid "FAQs"
Expand Down Expand Up @@ -952,29 +952,25 @@ msgstr ""
msgid "Upload exceeds size limit."
msgstr ""

#: includes/class-opentrust-admin-tools.php:332
msgid "Could not store uploaded file."
msgstr ""

#: includes/class-opentrust-admin-tools.php:381
#: includes/class-opentrust-admin-tools.php:389
msgid "Import cancelled."
msgstr ""

#: includes/class-opentrust-admin-tools.php:386
#: includes/class-opentrust-admin-tools.php:394
msgid "Import has unresolved errors."
msgstr ""

#. translators: %1$d: created, %2$d: updated, %3$d: skipped
#: includes/class-opentrust-admin-tools.php:406
#: includes/class-opentrust-admin-tools.php:414
#, php-format
msgid "Imported: %1$d created, %2$d updated, %3$d skipped."
msgstr ""

#: includes/class-opentrust-admin-tools.php:414
#: includes/class-opentrust-admin-tools.php:422
msgid "Errors:"
msgstr ""

#: includes/class-opentrust-admin-tools.php:460
#: includes/class-opentrust-admin-tools.php:468
#: includes/class-opentrust-cpt.php:185
#: includes/class-opentrust-cpt.php:194
#: templates/chat.php:46
Expand Down
38 changes: 38 additions & 0 deletions uninstall.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@
// gone — wp_clear_scheduled_hook() removes every scheduled occurrence.
wp_clear_scheduled_hook('opentrust_generate_policy_summary');

// Clear any pending import-preview cleanup single-events. The handler lives on
// OpenTrust_Admin_Tools, which won't load post-uninstall.
wp_clear_scheduled_hook('opentrust_io_preview_cleanup');

// Delete plugin options.
delete_option('opentrust_settings');
delete_option('opentrust_provider_keys');
Expand All @@ -64,5 +68,39 @@
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- Bulk cleanup of plugin transients on uninstall, no user input
$wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_opentrust_%' OR option_name LIKE '_transient_timeout_opentrust_%'");

// Sweep the import-stash directory. Pre-1.1.0 installs created files directly
// under wp-content/uploads/opentrust-tmp/. From 1.1.0 onward wp_handle_upload()
// (scoped via an upload_dir filter) also lands here, so the runtime path is
// the same as the legacy path. Walk depth-first to cover any nested layout —
// the legacy structure was flat in practice but we cannot rely on that, and
// orphaned import-preview ZIPs may have collected here over time.
$ot_uploads = wp_upload_dir();
if (!empty($ot_uploads['basedir'])) {
$ot_stash = rtrim((string) $ot_uploads['basedir'], '/') . '/opentrust-tmp';
if (is_dir($ot_stash)) {
try {
$ot_iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($ot_stash, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($ot_iterator as $ot_entry) {
/** @var SplFileInfo $ot_entry */
$ot_path = (string) $ot_entry->getPathname();
if ($ot_entry->isDir()) {
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir -- one-shot uninstall cleanup; WP_Filesystem is disproportionate for tearing down a plugin-private temp dir.
@rmdir($ot_path);
} else {
wp_delete_file($ot_path);
}
}
} catch (\Throwable $ot_e) {
// Best-effort cleanup; never fatal during uninstall.
unset($ot_e);
}
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir -- one-shot uninstall cleanup; WP_Filesystem is disproportionate here.
@rmdir($ot_stash);
}
}

// Flush rewrite rules.
flush_rewrite_rules();
Loading