Plugin Directory

Changeset 3692234


Ignore:
Timestamp:
09/12/2026 01:02:39 AM (2 months ago)
Author:
kazmij
Message:

Release 1.0.2: harden object key integrity and concurrent upserts

Location:
kazcode-universal-storage
Files:
16 edited
1 copied

Legend:

Unmodified
Added
Removed
  • kazcode-universal-storage/tags/1.0.2/includes/Infrastructure/ObjectRepository.php

    r3685222 r3692234  
    4444    }
    4545    /**
    46      * Upsert by UNIQUE(storage_profile_id, object_key).
     46     * Upsert by UNIQUE(storage_profile_id, object_key_hash).
    4747     *
    4848     * @param array<string, mixed> $data Row fields.
    … …  
    5656            throw new \InvalidArgumentException('storage_profile_id and object_key are required.');
    5757        }
    58         // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- plugin-owned table, see class docblock.
    59         $existing_id = $wpdb->get_var($wpdb->prepare("SELECT id FROM {$this->table()} WHERE storage_profile_id = %d AND object_key = %s", $profile_id, $key));
    6058        $now = gmdate('Y-m-d H:i:s');
    6159        $data['updated_at'] = $now;
    … …  
    6361            $data['created_at'] = $now;
    6462        }
    65         if ($existing_id) {
    66             $id = (int) $existing_id;
    67             unset($data['created_at']);
    68             // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin-owned table, see class docblock; $wpdb->update() already parameterizes values.
    69             $wpdb->update($this->table(), $data, array('id' => $id));
    70             return $id;
    71         }
    72         // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin-owned table, see class docblock; $wpdb->insert() already parameterizes values.
    73         $wpdb->insert($this->table(), $data);
    74         return (int) $wpdb->insert_id;
     63        $data['object_key_hash'] = hash('sha256', $key);
     64        $columns = array('attachment_id', 'storage_profile_id', 'local_relative_path', 'object_key', 'object_key_hash', 'variant_type', 'mime_type', 'size_bytes', 'etag', 'checksum', 'local_status', 'remote_status', 'attempt_count', 'last_error_code', 'last_error_message', 'offloaded_at', 'verified_at', 'created_at', 'updated_at');
     65        $integer_columns = array('attachment_id', 'storage_profile_id', 'size_bytes', 'attempt_count');
     66        $insert_columns = array();
     67        $placeholders = array();
     68        $values = array();
     69        foreach ($columns as $column) {
     70            if (!array_key_exists($column, $data)) {
     71                continue;
     72            }
     73            $insert_columns[] = $column;
     74            $placeholders[] = in_array($column, $integer_columns, \true) && $data[$column] !== null ? '%d' : '%s';
     75            $values[] = $data[$column];
     76        }
     77        $update_columns = array_values(array_diff($insert_columns, array('created_at', 'storage_profile_id', 'object_key', 'object_key_hash')));
     78        $updates = array_map(static fn(string $column): string => "{$column} = VALUES({$column})", $update_columns);
     79        $updates[] = 'id = LAST_INSERT_ID(id)';
     80        $sql = sprintf('INSERT INTO %s (%s) VALUES (%s) ON DUPLICATE KEY UPDATE %s', $this->table(), implode(', ', $insert_columns), implode(', ', $placeholders), implode(', ', $updates));
     81        // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- SQL is assembled from a fixed column allowlist above; all values are placeholders.
     82        $result = $wpdb->query($wpdb->prepare($sql, ...$values));
     83        if ($result === \false) {
     84            throw new \RuntimeException('Object upsert failed.');
     85        }
     86        $id = (int) $wpdb->insert_id;
     87        if ($id <= 0) {
     88            throw new \RuntimeException('Object upsert failed: database did not return an object id.');
     89        }
     90        $row = $this->find_by_id($id);
     91        if (!is_array($row) || (int) ($row['storage_profile_id'] ?? 0) !== $profile_id || (string) ($row['object_key'] ?? '') !== $key) {
     92            throw new \RuntimeException('Object upsert returned a mismatched object key.');
     93        }
     94        return $id;
    7595    }
    7696    public function count_for_attachment(int $attachment_id): int
  • kazcode-universal-storage/tags/1.0.2/includes/Infrastructure/SchemaMigrator.php

    r3685222 r3692234  
    1616{
    1717    public const OPTION_KEY = 's3ms_schema_version';
    18     public const VERSION = 1;
     18    public const VERSION = 2;
    1919    /**
    2020     * Run pending schema upgrades.
    … …  
    2626            return;
    2727        }
    28         $this->install_v1();
     28        if ($current < 1) {
     29            $this->install_v1();
     30        }
     31        if ($current < 2) {
     32            $this->install_v2();
     33        }
    2934        update_option(self::OPTION_KEY, self::VERSION, \false);
    3035    }
    … …  
    3540    {
    3641        global $wpdb;
    37         require_once ABSPATH . 'wp-admin/includes/upgrade.php';
     42        $dbdelta = 'db' . 'Delta';
     43        if (!function_exists($dbdelta)) {
     44            require_once ABSPATH . 'wp-admin/includes/upgrade.php';
     45        }
    3846        $charset = $wpdb->get_charset_collate();
    3947        $profiles = $wpdb->prefix . 's3ms_storage_profiles';
    4048        $objects = $wpdb->prefix . 's3ms_objects';
    4149        $sql_profiles = "CREATE TABLE {$profiles} (\n\t\t\tid bigint(20) unsigned NOT NULL AUTO_INCREMENT,\n\t\t\tuuid char(36) NOT NULL,\n\t\t\tname varchar(191) NOT NULL,\n\t\t\tprovider_type varchar(32) NOT NULL,\n\t\t\tbucket varchar(255) NOT NULL DEFAULT '',\n\t\t\tregion varchar(64) NOT NULL DEFAULT '',\n\t\t\tendpoint varchar(255) NOT NULL DEFAULT '',\n\t\t\tpath_style tinyint(1) NOT NULL DEFAULT 0,\n\t\t\tprefix varchar(255) NOT NULL DEFAULT '',\n\t\t\tdelivery_type varchar(16) NOT NULL DEFAULT 'storage',\n\t\t\tdelivery_base_url text NULL,\n\t\t\tcdn_includes_prefix tinyint(1) NOT NULL DEFAULT 0,\n\t\t\tcredential_mode varchar(16) NOT NULL DEFAULT 'keys',\n\t\t\tcredentials_ref varchar(64) NOT NULL DEFAULT '',\n\t\t\tis_default_upload_target tinyint(1) NOT NULL DEFAULT 0,\n\t\t\tis_read_only tinyint(1) NOT NULL DEFAULT 0,\n\t\t\tlocation_locked tinyint(1) NOT NULL DEFAULT 0,\n\t\t\tcreated_at datetime NOT NULL,\n\t\t\tupdated_at datetime NOT NULL,\n\t\t\tPRIMARY KEY  (id),\n\t\t\tUNIQUE KEY uuid (uuid),\n\t\t\tKEY provider_type (provider_type),\n\t\t\tKEY is_default_upload_target (is_default_upload_target)\n\t\t) {$charset};";
    42         $sql_objects = "CREATE TABLE {$objects} (\n\t\t\tid bigint(20) unsigned NOT NULL AUTO_INCREMENT,\n\t\t\tattachment_id bigint(20) unsigned NOT NULL,\n\t\t\tstorage_profile_id bigint(20) unsigned NOT NULL,\n\t\t\tlocal_relative_path varchar(512) NOT NULL,\n\t\t\tobject_key varchar(1024) NOT NULL,\n\t\t\tvariant_type varchar(32) NOT NULL DEFAULT 'size',\n\t\t\tmime_type varchar(100) NOT NULL DEFAULT '',\n\t\t\tsize_bytes bigint(20) unsigned DEFAULT NULL,\n\t\t\tetag varchar(128) DEFAULT NULL,\n\t\t\tchecksum varchar(128) DEFAULT NULL,\n\t\t\tlocal_status varchar(16) NOT NULL DEFAULT 'unknown',\n\t\t\tremote_status varchar(16) NOT NULL DEFAULT 'pending',\n\t\t\tattempt_count int(10) unsigned NOT NULL DEFAULT 0,\n\t\t\tlast_error_code varchar(64) DEFAULT NULL,\n\t\t\tlast_error_message text,\n\t\t\toffloaded_at datetime DEFAULT NULL,\n\t\t\tverified_at datetime DEFAULT NULL,\n\t\t\tcreated_at datetime NOT NULL,\n\t\t\tupdated_at datetime NOT NULL,\n\t\t\tPRIMARY KEY  (id),\n\t\t\tUNIQUE KEY profile_object_key (storage_profile_id, object_key(191)),\n\t\t\tKEY attachment_id (attachment_id),\n\t\t\tKEY remote_status (remote_status),\n\t\t\tKEY updated_at (updated_at),\n\t\t\tKEY attachment_remote (attachment_id, remote_status),\n\t\t\tKEY profile_attachment (storage_profile_id, attachment_id)\n\t\t) {$charset};";
     50        $sql_objects = "CREATE TABLE {$objects} (\n\t\t\tid bigint(20) unsigned NOT NULL AUTO_INCREMENT,\n\t\t\tattachment_id bigint(20) unsigned NOT NULL,\n\t\t\tstorage_profile_id bigint(20) unsigned NOT NULL,\n\t\t\tlocal_relative_path varchar(512) NOT NULL,\n\t\t\tobject_key varchar(1024) NOT NULL,\n\t\t\tobject_key_hash char(64) NOT NULL,\n\t\t\tvariant_type varchar(32) NOT NULL DEFAULT 'size',\n\t\t\tmime_type varchar(100) NOT NULL DEFAULT '',\n\t\t\tsize_bytes bigint(20) unsigned DEFAULT NULL,\n\t\t\tetag varchar(128) DEFAULT NULL,\n\t\t\tchecksum varchar(128) DEFAULT NULL,\n\t\t\tlocal_status varchar(16) NOT NULL DEFAULT 'unknown',\n\t\t\tremote_status varchar(16) NOT NULL DEFAULT 'pending',\n\t\t\tattempt_count int(10) unsigned NOT NULL DEFAULT 0,\n\t\t\tlast_error_code varchar(64) DEFAULT NULL,\n\t\t\tlast_error_message text,\n\t\t\toffloaded_at datetime DEFAULT NULL,\n\t\t\tverified_at datetime DEFAULT NULL,\n\t\t\tcreated_at datetime NOT NULL,\n\t\t\tupdated_at datetime NOT NULL,\n\t\t\tPRIMARY KEY  (id),\n\t\t\tUNIQUE KEY profile_object_key_hash (storage_profile_id, object_key_hash),\n\t\t\tKEY attachment_id (attachment_id),\n\t\t\tKEY remote_status (remote_status),\n\t\t\tKEY updated_at (updated_at),\n\t\t\tKEY attachment_remote (attachment_id, remote_status),\n\t\t\tKEY profile_attachment (storage_profile_id, attachment_id)\n\t\t) {$charset};";
    4351        dbDelta($sql_profiles);
    4452        dbDelta($sql_objects);
    4553    }
     54    /**
     55     * Replace prefix-based object-key uniqueness with full-key hash fencing.
     56     */
     57    private function install_v2(): void
     58    {
     59        global $wpdb;
     60        $objects = $wpdb->prefix . 's3ms_objects';
     61        // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- plugin-owned table schema inspection; table name is fixed from $wpdb->prefix.
     62        $hash_column = $wpdb->get_var($wpdb->prepare("SHOW COLUMNS FROM {$objects} LIKE %s", 'object_key_hash'));
     63        if (!$hash_column) {
     64            // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- versioned plugin-owned schema migration.
     65            $result = $wpdb->query("ALTER TABLE {$objects} ADD object_key_hash char(64) NOT NULL DEFAULT '' AFTER object_key");
     66            if ($result === \false) {
     67                throw new \RuntimeException('Unable to add s3ms_objects.object_key_hash.');
     68            }
     69        }
     70        // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- versioned plugin-owned data backfill; SHA2 is provided by supported MySQL/MariaDB variants.
     71        $result = $wpdb->query("UPDATE {$objects} SET object_key_hash = SHA2(object_key, 256) WHERE object_key_hash = '' OR object_key_hash IS NULL");
     72        if ($result === \false) {
     73            throw new \RuntimeException('Unable to backfill s3ms_objects.object_key_hash.');
     74        }
     75        // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- fail-safe duplicate detection before adding the authoritative unique key.
     76        $duplicates = $wpdb->get_results("SELECT storage_profile_id, object_key_hash, COUNT(*) AS cnt, COUNT(DISTINCT object_key) AS distinct_keys FROM {$objects} GROUP BY storage_profile_id, object_key_hash HAVING cnt > 1", ARRAY_A);
     77        if (is_array($duplicates) && $duplicates !== array()) {
     78            throw new \RuntimeException('Duplicate s3ms_objects storage profile/object key hashes prevent safe schema upgrade.');
     79        }
     80        $this->drop_index_if_exists($objects, 'profile_object_key');
     81        $this->add_unique_index_if_missing($objects, 'profile_object_key_hash', 'storage_profile_id, object_key_hash');
     82    }
     83    private function drop_index_if_exists(string $table, string $index_name): void
     84    {
     85        global $wpdb;
     86        // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- plugin-owned schema inspection.
     87        $exists = $wpdb->get_var($wpdb->prepare("SHOW INDEX FROM {$table} WHERE Key_name = %s", $index_name));
     88        if (!$exists) {
     89            return;
     90        }
     91        // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- versioned plugin-owned schema migration.
     92        $result = $wpdb->query("ALTER TABLE {$table} DROP INDEX {$index_name}");
     93        if ($result === \false) {
     94            throw new \RuntimeException('Unable to drop s3ms_objects index.');
     95        }
     96    }
     97    private function add_unique_index_if_missing(string $table, string $index_name, string $columns): void
     98    {
     99        global $wpdb;
     100        // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- plugin-owned schema inspection.
     101        $exists = $wpdb->get_var($wpdb->prepare("SHOW INDEX FROM {$table} WHERE Key_name = %s", $index_name));
     102        if ($exists) {
     103            return;
     104        }
     105        // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- versioned plugin-owned schema migration.
     106        $result = $wpdb->query("ALTER TABLE {$table} ADD UNIQUE KEY {$index_name} ({$columns})");
     107        if ($result === \false) {
     108            throw new \RuntimeException('Unable to add s3ms_objects unique index.');
     109        }
     110    }
    46111}
  • kazcode-universal-storage/tags/1.0.2/kazcode-universal-storage.php

    r3685222 r3692234  
    44 * Plugin URI:        https://kazcode.net/universal-storage/
    55 * Description:       Offload your WordPress Media Library to Amazon S3, Cloudflare R2, or S3-compatible object storage while keeping the native Media Library UX and attachment metadata in WordPress.
    6  * Version:           1.0.1
     6 * Version:           1.0.2
    77 * Requires at least: 6.7
    88 * Requires PHP:      8.3
    … …  
    2222}
    2323
    24 define('KAZUS_VERSION', '1.0.1');
     24define('KAZUS_VERSION', '1.0.2');
    2525define('KAZUS_PLUGIN_FILE', __FILE__);
    2626define('KAZUS_PLUGIN_DIR', plugin_dir_path(__FILE__));
  • kazcode-universal-storage/tags/1.0.2/readme.txt

    r3685222 r3692234  
    55Tested up to: 7.1
    66Requires PHP: 8.3
    7 Stable tag: 1.0.1
     7Stable tag: 1.0.2
    88License: GPLv2 or later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    … …  
    106106== Changelog ==
    107107
     108= 1.0.2 =
     109* Improved object-key integrity for long storage paths.
     110* Improved database safety during concurrent media operations.
     111
    108112= 1.0.1 =
    109113* Strengthened remote verification before local media cleanup.
    … …  
    128132== Upgrade Notice ==
    129133
     134= 1.0.2 =
     135Object-key integrity and concurrent database safety hotfix. Update recommended for all sites.
     136
    130137= 1.0.1 =
    131138Reliability, data-integrity, and compatibility hotfix. Update recommended for all sites.
  • kazcode-universal-storage/tags/1.0.2/vendor/autoload.php

    r3686527 r3692234  
    1919}
    2020require_once __DIR__ . '/composer/autoload_real.php';
    21 return \ComposerAutoloaderInita5a66945f99b3894987692852b3e7c38::getLoader();
     21return \ComposerAutoloaderInit8cdd760b077ab5b8842437bb000793cb::getLoader();
  • kazcode-universal-storage/tags/1.0.2/vendor/composer/autoload_real.php

    r3686527 r3692234  
    44
    55// autoload_real.php @generated by Composer
    6 class ComposerAutoloaderInita5a66945f99b3894987692852b3e7c38
     6class ComposerAutoloaderInit8cdd760b077ab5b8842437bb000793cb
    77{
    88    private static $loader;
    … …  
    2222        }
    2323        require __DIR__ . '/platform_check.php';
    24         \spl_autoload_register(array('ComposerAutoloaderInita5a66945f99b3894987692852b3e7c38', 'loadClassLoader'), \true, \true);
     24        \spl_autoload_register(array('ComposerAutoloaderInit8cdd760b077ab5b8842437bb000793cb', 'loadClassLoader'), \true, \true);
    2525        self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
    26         \spl_autoload_unregister(array('ComposerAutoloaderInita5a66945f99b3894987692852b3e7c38', 'loadClassLoader'));
     26        \spl_autoload_unregister(array('ComposerAutoloaderInit8cdd760b077ab5b8842437bb000793cb', 'loadClassLoader'));
    2727        require __DIR__ . '/autoload_static.php';
    28         \call_user_func(\Composer\Autoload\ComposerStaticInita5a66945f99b3894987692852b3e7c38::getInitializer($loader));
     28        \call_user_func(\Composer\Autoload\ComposerStaticInit8cdd760b077ab5b8842437bb000793cb::getInitializer($loader));
    2929        $loader->register(\true);
    30         $filesToLoad = \Composer\Autoload\ComposerStaticInita5a66945f99b3894987692852b3e7c38::$files;
     30        $filesToLoad = \Composer\Autoload\ComposerStaticInit8cdd760b077ab5b8842437bb000793cb::$files;
    3131        $requireFile = \Closure::bind(static function ($fileIdentifier, $file) {
    3232            if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
    … …  
    4242}
    4343// autoload_real.php @generated by Composer
    44 \class_alias('Kazcode\WpStorage\Vendor\ComposerAutoloaderInita5a66945f99b3894987692852b3e7c38', 'ComposerAutoloaderInita5a66945f99b3894987692852b3e7c38', \false);
     44\class_alias('Kazcode\WpStorage\Vendor\ComposerAutoloaderInit8cdd760b077ab5b8842437bb000793cb', 'ComposerAutoloaderInit8cdd760b077ab5b8842437bb000793cb', \false);
  • kazcode-universal-storage/tags/1.0.2/vendor/composer/autoload_static.php

    r3686527 r3692234  
    44namespace Composer\Autoload;
    55
    6 class ComposerStaticInita5a66945f99b3894987692852b3e7c38
     6class ComposerStaticInit8cdd760b077ab5b8842437bb000793cb
    77{
    88    public static $files = array(
    … …  
    8080    {
    8181        return \Closure::bind(function () use ($loader) {
    82             $loader->prefixLengthsPsr4 = \Composer\Autoload\ComposerStaticInita5a66945f99b3894987692852b3e7c38::$prefixLengthsPsr4;
    83             $loader->prefixDirsPsr4 = \Composer\Autoload\ComposerStaticInita5a66945f99b3894987692852b3e7c38::$prefixDirsPsr4;
    84             $loader->classMap = \Composer\Autoload\ComposerStaticInita5a66945f99b3894987692852b3e7c38::$classMap;
     82            $loader->prefixLengthsPsr4 = \Composer\Autoload\ComposerStaticInit8cdd760b077ab5b8842437bb000793cb::$prefixLengthsPsr4;
     83            $loader->prefixDirsPsr4 = \Composer\Autoload\ComposerStaticInit8cdd760b077ab5b8842437bb000793cb::$prefixDirsPsr4;
     84            $loader->classMap = \Composer\Autoload\ComposerStaticInit8cdd760b077ab5b8842437bb000793cb::$classMap;
    8585        }, null, \Composer\Autoload\ClassLoader::class);
    8686    }
  • kazcode-universal-storage/tags/1.0.2/vendor/scoper-autoload.php

    r3686527 r3692234  
    3030    }
    3131}
    32 humbug_phpscoper_expose_class('ComposerAutoloaderInita5a66945f99b3894987692852b3e7c38', 'Kazcode\WpStorage\Vendor\ComposerAutoloaderInita5a66945f99b3894987692852b3e7c38');
     32humbug_phpscoper_expose_class('ComposerAutoloaderInit8cdd760b077ab5b8842437bb000793cb', 'Kazcode\WpStorage\Vendor\ComposerAutoloaderInit8cdd760b077ab5b8842437bb000793cb');
    3333humbug_phpscoper_expose_class('Attribute', 'Kazcode\WpStorage\Vendor\Attribute');
    3434humbug_phpscoper_expose_class('PhpToken', 'Kazcode\WpStorage\Vendor\PhpToken');
  • kazcode-universal-storage/trunk/includes/Infrastructure/ObjectRepository.php

    r3685222 r3692234  
    4444    }
    4545    /**
    46      * Upsert by UNIQUE(storage_profile_id, object_key).
     46     * Upsert by UNIQUE(storage_profile_id, object_key_hash).
    4747     *
    4848     * @param array<string, mixed> $data Row fields.
    … …  
    5656            throw new \InvalidArgumentException('storage_profile_id and object_key are required.');
    5757        }
    58         // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- plugin-owned table, see class docblock.
    59         $existing_id = $wpdb->get_var($wpdb->prepare("SELECT id FROM {$this->table()} WHERE storage_profile_id = %d AND object_key = %s", $profile_id, $key));
    6058        $now = gmdate('Y-m-d H:i:s');
    6159        $data['updated_at'] = $now;
    … …  
    6361            $data['created_at'] = $now;
    6462        }
    65         if ($existing_id) {
    66             $id = (int) $existing_id;
    67             unset($data['created_at']);
    68             // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin-owned table, see class docblock; $wpdb->update() already parameterizes values.
    69             $wpdb->update($this->table(), $data, array('id' => $id));
    70             return $id;
    71         }
    72         // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin-owned table, see class docblock; $wpdb->insert() already parameterizes values.
    73         $wpdb->insert($this->table(), $data);
    74         return (int) $wpdb->insert_id;
     63        $data['object_key_hash'] = hash('sha256', $key);
     64        $columns = array('attachment_id', 'storage_profile_id', 'local_relative_path', 'object_key', 'object_key_hash', 'variant_type', 'mime_type', 'size_bytes', 'etag', 'checksum', 'local_status', 'remote_status', 'attempt_count', 'last_error_code', 'last_error_message', 'offloaded_at', 'verified_at', 'created_at', 'updated_at');
     65        $integer_columns = array('attachment_id', 'storage_profile_id', 'size_bytes', 'attempt_count');
     66        $insert_columns = array();
     67        $placeholders = array();
     68        $values = array();
     69        foreach ($columns as $column) {
     70            if (!array_key_exists($column, $data)) {
     71                continue;
     72            }
     73            $insert_columns[] = $column;
     74            $placeholders[] = in_array($column, $integer_columns, \true) && $data[$column] !== null ? '%d' : '%s';
     75            $values[] = $data[$column];
     76        }
     77        $update_columns = array_values(array_diff($insert_columns, array('created_at', 'storage_profile_id', 'object_key', 'object_key_hash')));
     78        $updates = array_map(static fn(string $column): string => "{$column} = VALUES({$column})", $update_columns);
     79        $updates[] = 'id = LAST_INSERT_ID(id)';
     80        $sql = sprintf('INSERT INTO %s (%s) VALUES (%s) ON DUPLICATE KEY UPDATE %s', $this->table(), implode(', ', $insert_columns), implode(', ', $placeholders), implode(', ', $updates));
     81        // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- SQL is assembled from a fixed column allowlist above; all values are placeholders.
     82        $result = $wpdb->query($wpdb->prepare($sql, ...$values));
     83        if ($result === \false) {
     84            throw new \RuntimeException('Object upsert failed.');
     85        }
     86        $id = (int) $wpdb->insert_id;
     87        if ($id <= 0) {
     88            throw new \RuntimeException('Object upsert failed: database did not return an object id.');
     89        }
     90        $row = $this->find_by_id($id);
     91        if (!is_array($row) || (int) ($row['storage_profile_id'] ?? 0) !== $profile_id || (string) ($row['object_key'] ?? '') !== $key) {
     92            throw new \RuntimeException('Object upsert returned a mismatched object key.');
     93        }
     94        return $id;
    7595    }
    7696    public function count_for_attachment(int $attachment_id): int
  • kazcode-universal-storage/trunk/includes/Infrastructure/SchemaMigrator.php

    r3685222 r3692234  
    1616{
    1717    public const OPTION_KEY = 's3ms_schema_version';
    18     public const VERSION = 1;
     18    public const VERSION = 2;
    1919    /**
    2020     * Run pending schema upgrades.
    … …  
    2626            return;
    2727        }
    28         $this->install_v1();
     28        if ($current < 1) {
     29            $this->install_v1();
     30        }
     31        if ($current < 2) {
     32            $this->install_v2();
     33        }
    2934        update_option(self::OPTION_KEY, self::VERSION, \false);
    3035    }
    … …  
    3540    {
    3641        global $wpdb;
    37         require_once ABSPATH . 'wp-admin/includes/upgrade.php';
     42        $dbdelta = 'db' . 'Delta';
     43        if (!function_exists($dbdelta)) {
     44            require_once ABSPATH . 'wp-admin/includes/upgrade.php';
     45        }
    3846        $charset = $wpdb->get_charset_collate();
    3947        $profiles = $wpdb->prefix . 's3ms_storage_profiles';
    4048        $objects = $wpdb->prefix . 's3ms_objects';
    4149        $sql_profiles = "CREATE TABLE {$profiles} (\n\t\t\tid bigint(20) unsigned NOT NULL AUTO_INCREMENT,\n\t\t\tuuid char(36) NOT NULL,\n\t\t\tname varchar(191) NOT NULL,\n\t\t\tprovider_type varchar(32) NOT NULL,\n\t\t\tbucket varchar(255) NOT NULL DEFAULT '',\n\t\t\tregion varchar(64) NOT NULL DEFAULT '',\n\t\t\tendpoint varchar(255) NOT NULL DEFAULT '',\n\t\t\tpath_style tinyint(1) NOT NULL DEFAULT 0,\n\t\t\tprefix varchar(255) NOT NULL DEFAULT '',\n\t\t\tdelivery_type varchar(16) NOT NULL DEFAULT 'storage',\n\t\t\tdelivery_base_url text NULL,\n\t\t\tcdn_includes_prefix tinyint(1) NOT NULL DEFAULT 0,\n\t\t\tcredential_mode varchar(16) NOT NULL DEFAULT 'keys',\n\t\t\tcredentials_ref varchar(64) NOT NULL DEFAULT '',\n\t\t\tis_default_upload_target tinyint(1) NOT NULL DEFAULT 0,\n\t\t\tis_read_only tinyint(1) NOT NULL DEFAULT 0,\n\t\t\tlocation_locked tinyint(1) NOT NULL DEFAULT 0,\n\t\t\tcreated_at datetime NOT NULL,\n\t\t\tupdated_at datetime NOT NULL,\n\t\t\tPRIMARY KEY  (id),\n\t\t\tUNIQUE KEY uuid (uuid),\n\t\t\tKEY provider_type (provider_type),\n\t\t\tKEY is_default_upload_target (is_default_upload_target)\n\t\t) {$charset};";
    42         $sql_objects = "CREATE TABLE {$objects} (\n\t\t\tid bigint(20) unsigned NOT NULL AUTO_INCREMENT,\n\t\t\tattachment_id bigint(20) unsigned NOT NULL,\n\t\t\tstorage_profile_id bigint(20) unsigned NOT NULL,\n\t\t\tlocal_relative_path varchar(512) NOT NULL,\n\t\t\tobject_key varchar(1024) NOT NULL,\n\t\t\tvariant_type varchar(32) NOT NULL DEFAULT 'size',\n\t\t\tmime_type varchar(100) NOT NULL DEFAULT '',\n\t\t\tsize_bytes bigint(20) unsigned DEFAULT NULL,\n\t\t\tetag varchar(128) DEFAULT NULL,\n\t\t\tchecksum varchar(128) DEFAULT NULL,\n\t\t\tlocal_status varchar(16) NOT NULL DEFAULT 'unknown',\n\t\t\tremote_status varchar(16) NOT NULL DEFAULT 'pending',\n\t\t\tattempt_count int(10) unsigned NOT NULL DEFAULT 0,\n\t\t\tlast_error_code varchar(64) DEFAULT NULL,\n\t\t\tlast_error_message text,\n\t\t\toffloaded_at datetime DEFAULT NULL,\n\t\t\tverified_at datetime DEFAULT NULL,\n\t\t\tcreated_at datetime NOT NULL,\n\t\t\tupdated_at datetime NOT NULL,\n\t\t\tPRIMARY KEY  (id),\n\t\t\tUNIQUE KEY profile_object_key (storage_profile_id, object_key(191)),\n\t\t\tKEY attachment_id (attachment_id),\n\t\t\tKEY remote_status (remote_status),\n\t\t\tKEY updated_at (updated_at),\n\t\t\tKEY attachment_remote (attachment_id, remote_status),\n\t\t\tKEY profile_attachment (storage_profile_id, attachment_id)\n\t\t) {$charset};";
     50        $sql_objects = "CREATE TABLE {$objects} (\n\t\t\tid bigint(20) unsigned NOT NULL AUTO_INCREMENT,\n\t\t\tattachment_id bigint(20) unsigned NOT NULL,\n\t\t\tstorage_profile_id bigint(20) unsigned NOT NULL,\n\t\t\tlocal_relative_path varchar(512) NOT NULL,\n\t\t\tobject_key varchar(1024) NOT NULL,\n\t\t\tobject_key_hash char(64) NOT NULL,\n\t\t\tvariant_type varchar(32) NOT NULL DEFAULT 'size',\n\t\t\tmime_type varchar(100) NOT NULL DEFAULT '',\n\t\t\tsize_bytes bigint(20) unsigned DEFAULT NULL,\n\t\t\tetag varchar(128) DEFAULT NULL,\n\t\t\tchecksum varchar(128) DEFAULT NULL,\n\t\t\tlocal_status varchar(16) NOT NULL DEFAULT 'unknown',\n\t\t\tremote_status varchar(16) NOT NULL DEFAULT 'pending',\n\t\t\tattempt_count int(10) unsigned NOT NULL DEFAULT 0,\n\t\t\tlast_error_code varchar(64) DEFAULT NULL,\n\t\t\tlast_error_message text,\n\t\t\toffloaded_at datetime DEFAULT NULL,\n\t\t\tverified_at datetime DEFAULT NULL,\n\t\t\tcreated_at datetime NOT NULL,\n\t\t\tupdated_at datetime NOT NULL,\n\t\t\tPRIMARY KEY  (id),\n\t\t\tUNIQUE KEY profile_object_key_hash (storage_profile_id, object_key_hash),\n\t\t\tKEY attachment_id (attachment_id),\n\t\t\tKEY remote_status (remote_status),\n\t\t\tKEY updated_at (updated_at),\n\t\t\tKEY attachment_remote (attachment_id, remote_status),\n\t\t\tKEY profile_attachment (storage_profile_id, attachment_id)\n\t\t) {$charset};";
    4351        dbDelta($sql_profiles);
    4452        dbDelta($sql_objects);
    4553    }
     54    /**
     55     * Replace prefix-based object-key uniqueness with full-key hash fencing.
     56     */
     57    private function install_v2(): void
     58    {
     59        global $wpdb;
     60        $objects = $wpdb->prefix . 's3ms_objects';
     61        // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- plugin-owned table schema inspection; table name is fixed from $wpdb->prefix.
     62        $hash_column = $wpdb->get_var($wpdb->prepare("SHOW COLUMNS FROM {$objects} LIKE %s", 'object_key_hash'));
     63        if (!$hash_column) {
     64            // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- versioned plugin-owned schema migration.
     65            $result = $wpdb->query("ALTER TABLE {$objects} ADD object_key_hash char(64) NOT NULL DEFAULT '' AFTER object_key");
     66            if ($result === \false) {
     67                throw new \RuntimeException('Unable to add s3ms_objects.object_key_hash.');
     68            }
     69        }
     70        // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- versioned plugin-owned data backfill; SHA2 is provided by supported MySQL/MariaDB variants.
     71        $result = $wpdb->query("UPDATE {$objects} SET object_key_hash = SHA2(object_key, 256) WHERE object_key_hash = '' OR object_key_hash IS NULL");
     72        if ($result === \false) {
     73            throw new \RuntimeException('Unable to backfill s3ms_objects.object_key_hash.');
     74        }
     75        // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- fail-safe duplicate detection before adding the authoritative unique key.
     76        $duplicates = $wpdb->get_results("SELECT storage_profile_id, object_key_hash, COUNT(*) AS cnt, COUNT(DISTINCT object_key) AS distinct_keys FROM {$objects} GROUP BY storage_profile_id, object_key_hash HAVING cnt > 1", ARRAY_A);
     77        if (is_array($duplicates) && $duplicates !== array()) {
     78            throw new \RuntimeException('Duplicate s3ms_objects storage profile/object key hashes prevent safe schema upgrade.');
     79        }
     80        $this->drop_index_if_exists($objects, 'profile_object_key');
     81        $this->add_unique_index_if_missing($objects, 'profile_object_key_hash', 'storage_profile_id, object_key_hash');
     82    }
     83    private function drop_index_if_exists(string $table, string $index_name): void
     84    {
     85        global $wpdb;
     86        // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- plugin-owned schema inspection.
     87        $exists = $wpdb->get_var($wpdb->prepare("SHOW INDEX FROM {$table} WHERE Key_name = %s", $index_name));
     88        if (!$exists) {
     89            return;
     90        }
     91        // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- versioned plugin-owned schema migration.
     92        $result = $wpdb->query("ALTER TABLE {$table} DROP INDEX {$index_name}");
     93        if ($result === \false) {
     94            throw new \RuntimeException('Unable to drop s3ms_objects index.');
     95        }
     96    }
     97    private function add_unique_index_if_missing(string $table, string $index_name, string $columns): void
     98    {
     99        global $wpdb;
     100        // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- plugin-owned schema inspection.
     101        $exists = $wpdb->get_var($wpdb->prepare("SHOW INDEX FROM {$table} WHERE Key_name = %s", $index_name));
     102        if ($exists) {
     103            return;
     104        }
     105        // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- versioned plugin-owned schema migration.
     106        $result = $wpdb->query("ALTER TABLE {$table} ADD UNIQUE KEY {$index_name} ({$columns})");
     107        if ($result === \false) {
     108            throw new \RuntimeException('Unable to add s3ms_objects unique index.');
     109        }
     110    }
    46111}
  • kazcode-universal-storage/trunk/kazcode-universal-storage.php

    r3685222 r3692234  
    44 * Plugin URI:        https://kazcode.net/universal-storage/
    55 * Description:       Offload your WordPress Media Library to Amazon S3, Cloudflare R2, or S3-compatible object storage while keeping the native Media Library UX and attachment metadata in WordPress.
    6  * Version:           1.0.1
     6 * Version:           1.0.2
    77 * Requires at least: 6.7
    88 * Requires PHP:      8.3
    … …  
    2222}
    2323
    24 define('KAZUS_VERSION', '1.0.1');
     24define('KAZUS_VERSION', '1.0.2');
    2525define('KAZUS_PLUGIN_FILE', __FILE__);
    2626define('KAZUS_PLUGIN_DIR', plugin_dir_path(__FILE__));
  • kazcode-universal-storage/trunk/readme.txt

    r3685222 r3692234  
    55Tested up to: 7.1
    66Requires PHP: 8.3
    7 Stable tag: 1.0.1
     7Stable tag: 1.0.2
    88License: GPLv2 or later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    … …  
    106106== Changelog ==
    107107
     108= 1.0.2 =
     109* Improved object-key integrity for long storage paths.
     110* Improved database safety during concurrent media operations.
     111
    108112= 1.0.1 =
    109113* Strengthened remote verification before local media cleanup.
    … …  
    128132== Upgrade Notice ==
    129133
     134= 1.0.2 =
     135Object-key integrity and concurrent database safety hotfix. Update recommended for all sites.
     136
    130137= 1.0.1 =
    131138Reliability, data-integrity, and compatibility hotfix. Update recommended for all sites.
  • kazcode-universal-storage/trunk/vendor/autoload.php

    r3686527 r3692234  
    1919}
    2020require_once __DIR__ . '/composer/autoload_real.php';
    21 return \ComposerAutoloaderInita5a66945f99b3894987692852b3e7c38::getLoader();
     21return \ComposerAutoloaderInit8cdd760b077ab5b8842437bb000793cb::getLoader();
  • kazcode-universal-storage/trunk/vendor/composer/autoload_real.php

    r3686527 r3692234  
    44
    55// autoload_real.php @generated by Composer
    6 class ComposerAutoloaderInita5a66945f99b3894987692852b3e7c38
     6class ComposerAutoloaderInit8cdd760b077ab5b8842437bb000793cb
    77{
    88    private static $loader;
    … …  
    2222        }
    2323        require __DIR__ . '/platform_check.php';
    24         \spl_autoload_register(array('ComposerAutoloaderInita5a66945f99b3894987692852b3e7c38', 'loadClassLoader'), \true, \true);
     24        \spl_autoload_register(array('ComposerAutoloaderInit8cdd760b077ab5b8842437bb000793cb', 'loadClassLoader'), \true, \true);
    2525        self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
    26         \spl_autoload_unregister(array('ComposerAutoloaderInita5a66945f99b3894987692852b3e7c38', 'loadClassLoader'));
     26        \spl_autoload_unregister(array('ComposerAutoloaderInit8cdd760b077ab5b8842437bb000793cb', 'loadClassLoader'));
    2727        require __DIR__ . '/autoload_static.php';
    28         \call_user_func(\Composer\Autoload\ComposerStaticInita5a66945f99b3894987692852b3e7c38::getInitializer($loader));
     28        \call_user_func(\Composer\Autoload\ComposerStaticInit8cdd760b077ab5b8842437bb000793cb::getInitializer($loader));
    2929        $loader->register(\true);
    30         $filesToLoad = \Composer\Autoload\ComposerStaticInita5a66945f99b3894987692852b3e7c38::$files;
     30        $filesToLoad = \Composer\Autoload\ComposerStaticInit8cdd760b077ab5b8842437bb000793cb::$files;
    3131        $requireFile = \Closure::bind(static function ($fileIdentifier, $file) {
    3232            if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
    … …  
    4242}
    4343// autoload_real.php @generated by Composer
    44 \class_alias('Kazcode\WpStorage\Vendor\ComposerAutoloaderInita5a66945f99b3894987692852b3e7c38', 'ComposerAutoloaderInita5a66945f99b3894987692852b3e7c38', \false);
     44\class_alias('Kazcode\WpStorage\Vendor\ComposerAutoloaderInit8cdd760b077ab5b8842437bb000793cb', 'ComposerAutoloaderInit8cdd760b077ab5b8842437bb000793cb', \false);
  • kazcode-universal-storage/trunk/vendor/composer/autoload_static.php

    r3686527 r3692234  
    44namespace Composer\Autoload;
    55
    6 class ComposerStaticInita5a66945f99b3894987692852b3e7c38
     6class ComposerStaticInit8cdd760b077ab5b8842437bb000793cb
    77{
    88    public static $files = array(
    … …  
    8080    {
    8181        return \Closure::bind(function () use ($loader) {
    82             $loader->prefixLengthsPsr4 = \Composer\Autoload\ComposerStaticInita5a66945f99b3894987692852b3e7c38::$prefixLengthsPsr4;
    83             $loader->prefixDirsPsr4 = \Composer\Autoload\ComposerStaticInita5a66945f99b3894987692852b3e7c38::$prefixDirsPsr4;
    84             $loader->classMap = \Composer\Autoload\ComposerStaticInita5a66945f99b3894987692852b3e7c38::$classMap;
     82            $loader->prefixLengthsPsr4 = \Composer\Autoload\ComposerStaticInit8cdd760b077ab5b8842437bb000793cb::$prefixLengthsPsr4;
     83            $loader->prefixDirsPsr4 = \Composer\Autoload\ComposerStaticInit8cdd760b077ab5b8842437bb000793cb::$prefixDirsPsr4;
     84            $loader->classMap = \Composer\Autoload\ComposerStaticInit8cdd760b077ab5b8842437bb000793cb::$classMap;
    8585        }, null, \Composer\Autoload\ClassLoader::class);
    8686    }
  • kazcode-universal-storage/trunk/vendor/scoper-autoload.php

    r3686527 r3692234  
    3030    }
    3131}
    32 humbug_phpscoper_expose_class('ComposerAutoloaderInita5a66945f99b3894987692852b3e7c38', 'Kazcode\WpStorage\Vendor\ComposerAutoloaderInita5a66945f99b3894987692852b3e7c38');
     32humbug_phpscoper_expose_class('ComposerAutoloaderInit8cdd760b077ab5b8842437bb000793cb', 'Kazcode\WpStorage\Vendor\ComposerAutoloaderInit8cdd760b077ab5b8842437bb000793cb');
    3333humbug_phpscoper_expose_class('Attribute', 'Kazcode\WpStorage\Vendor\Attribute');
    3434humbug_phpscoper_expose_class('PhpToken', 'Kazcode\WpStorage\Vendor\PhpToken');
Note: See TracChangeset for help on using the changeset viewer.