Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
9 changes: 7 additions & 2 deletions .github/workflows/mysql-proxy-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,13 @@ permissions: {}

jobs:
test:
name: MySQL Proxy Tests
name: MySQL Proxy Tests (PHP ${{ matrix.php }})
runs-on: ubuntu-latest
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
php: ['7.2', '8.5']
permissions:
contents: read # Required to clone the repo.

Expand All @@ -25,7 +29,8 @@ jobs:
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: '7.2'
php-version: ${{ matrix.php }}
extensions: sockets, pdo_mysql, pdo_sqlite, mysqli
coverage: none

- name: Configure monorepo package repository
Expand Down
36 changes: 32 additions & 4 deletions packages/mysql-proxy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,32 +32,60 @@ composer require wordpress/mysql-proxy wordpress/mysql-on-sqlite:^3.0
### CLI:

```bash
$ ./vendor/bin/wp-mysql-proxy.php [--port <port>] [--database <path/to/db.sqlite>] [--log-level <log_level>]
$ ./vendor/bin/wp-mysql-proxy.php --user <username> [--password-file <path>] [--bind-address <address>] [--auth-plugin <name>] [--port <port>] [--database <path/to/db.sqlite>] [--log-level <log_level>]

Options:
-h, --help Show this help message and exit.
-p, --port=<port> The port to listen on. Default: 3306
-u, --user=<username> The proxy account name. Required.
--password-file=<path> Read the password from a file instead of WP_MYSQL_PROXY_PASSWORD.
--bind-address=<ip> The IPv4 or IPv6 address to listen on. Default: 127.0.0.1
--auth-plugin=<name> The account's authentication plugin, either
caching_sha2_password or mysql_native_password.
Use the latter only for clients that need it.
Default: caching_sha2_password
-P, --port=<port> The port to listen on. Default: 3306
-d, --database=<path> The path to the SQLite database file. Default: :memory:
-l, --log-level=<level> The log level to use. One of 'error', 'warning', 'info', 'debug'. Default: info

A nonempty password is required via WP_MYSQL_PROXY_PASSWORD or --password-file.
Password files are read verbatim, including any trailing newline.
Connections are not encrypted (no TLS). For remote clients, use an SSH tunnel.
```

When working from a checked-out repository, Composer does not create a proxy for
the root package's own binary. Run it directly from the package directory:

```bash
php bin/wp-mysql-proxy.php [--port <port>] [--database <path/to/db.sqlite>] [--log-level <log_level>]
php bin/wp-mysql-proxy.php --user <username> [--password-file <path>] [--bind-address <address>] [--auth-plugin <name>] [--port <port>] [--database <path/to/db.sqlite>] [--log-level <log_level>]
```

### PHP:
```php
use WP_MySQL_Proxy\MySQL_Authentication;
use WP_MySQL_Proxy\MySQL_Proxy;
use WP_MySQL_Proxy\Adapter\SQLite_Adapter;

require_once __DIR__ . '/vendor/autoload.php';

$proxy = new MySQL_Proxy(
new SQLite_Adapter( $db_path ),
array( 'port' => $port, 'log_level' => $log_level )
array(
'authentication' => new MySQL_Authentication( 'proxy', getenv( 'WP_MYSQL_PROXY_PASSWORD' ) ),
'port' => $port,
'log_level' => $log_level,
)
);
$proxy->start();
```

The account uses `caching_sha2_password` by default, which PDO and MySQLi on PHP
below 7.4.4 can't use. For those clients, set `--auth-plugin=mysql_native_password`,
or pass `mysql_native_password` as the third `MySQL_Authentication` argument.

The proxy listens on `127.0.0.1` by default. Set `--bind-address` (or the PHP
`bind_address` option) to an IPv4 or IPv6 address to change the listener. Binding
to `0.0.0.0` or `::` explicitly exposes the proxy on all interfaces.

The proxy doesn't support TLS. Queries, results, and logins travel unencrypted,
and anyone who records a login can try to guess the password offline. For remote
clients, keep the default address and connect through an SSH tunnel.
141 changes: 128 additions & 13 deletions packages/mysql-proxy/bin/wp-mysql-proxy.php
Original file line number Diff line number Diff line change
@@ -1,50 +1,163 @@
<?php declare( strict_types = 1 );

use WP_MySQL_Proxy\MySQL_Authentication;
use WP_MySQL_Proxy\MySQL_Protocol;
use WP_MySQL_Proxy\MySQL_Proxy;
use WP_MySQL_Proxy\Adapter\SQLite_Adapter;
use WP_MySQL_Proxy\Logger;

require_once $_composer_autoload_path ?? __DIR__ . '/../vendor/autoload.php';

// Process CLI arguments:
$shortopts = 'hd:p:l:';
$longopts = array( 'help', 'database:', 'port:', 'log-level:' );
$opts = getopt( $shortopts, $longopts );
// Parse every argument: getopt() silently discards unknown or incomplete options.
$aliases = array(
'h' => 'help',
'd' => 'database',
'P' => 'port',
'l' => 'log-level',
'u' => 'user',
);
$options = array( 'help', 'database', 'port', 'log-level', 'bind-address', 'user', 'password-file', 'auth-plugin' );
$args = array_slice( $argv, 1 );
$opts = array();

// Never include argument values in errors: an unknown option may contain a password.
$option_error = "Error: Invalid command-line options. Use --help for supported options and required values.\n";

for ( $i = 0; $i < count( $args ); $i++ ) {
$arg = $args[ $i ];
$name = '';
$value = null;
if ( 0 === strpos( $arg, '--' ) ) {
$parts = explode( '=', substr( $arg, 2 ), 2 );
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
$name = $parts[0];
$value = $parts[1] ?? null;
} elseif ( '-' === substr( $arg, 0, 1 ) && strlen( $arg ) > 1 ) {
$name = $aliases[ $arg[1] ] ?? '';
if ( strlen( $arg ) > 2 ) {
if ( 'help' === $name ) {
array_splice( $args, $i + 1, 0, array( '-' . substr( $arg, 2 ) ) );
} else {
$value = substr( $arg, 2 );
}
}
}

if ( ! in_array( $name, $options, true ) || array_key_exists( $name, $opts )
|| ( 'help' === $name && null !== $value )
) {
fwrite( STDERR, $option_error );
exit( 1 );
}
if ( 'help' === $name ) {
$opts[ $name ] = true;
continue;
}
// A separate value can't look like an option, so a missing value isn't
// filled with the next option. Use --option=-value for such a value.
if ( null === $value && isset( $args[ $i + 1 ] ) && 0 !== strpos( $args[ $i + 1 ], '-' ) ) {
$value = $args[ ++$i ];
}
if ( null === $value ) {
fwrite( STDERR, $option_error );
exit( 1 );
}
$opts[ $name ] = $value;
}

$help = <<<USAGE
Usage: wp-mysql-proxy.php [--port <port>] [--database <path/to/db.sqlite>] [--log-level <log_level>]
Usage: wp-mysql-proxy.php --user <username> [--password-file <path>] [--bind-address <address>] [--auth-plugin <name>] [--port <port>] [--database <path/to/db.sqlite>] [--log-level <log_level>]

Options:
-h, --help Show this help message and exit.
-p, --port=<port> The port to listen on. Default: 3306
-u, --user=<username> The proxy account name. Required.
--password-file=<path> Read the password from a file instead of WP_MYSQL_PROXY_PASSWORD.
--bind-address=<ip> The IPv4 or IPv6 address to listen on. Default: 127.0.0.1
--auth-plugin=<name> The account's authentication plugin, either
caching_sha2_password or mysql_native_password.
Use the latter only for clients that need it.
Default: caching_sha2_password
-P, --port=<port> The port to listen on. Default: 3306
-d, --database=<path> The path to the SQLite database file. Default: :memory:
-l, --log-level=<level> The log level to use. One of 'error', 'warning', 'info', 'debug'. Default: info

A nonempty password is required via WP_MYSQL_PROXY_PASSWORD or --password-file.
Password files are read verbatim, including any trailing newline.
Connections are not encrypted (no TLS). For remote clients, use an SSH tunnel.

USAGE;

// Help.
if ( isset( $opts['h'] ) || isset( $opts['help'] ) ) {
if ( isset( $opts['help'] ) ) {
fwrite( STDERR, $help );
exit( 0 );
}

// Database path.
$db_path = $opts['d'] ?? $opts['database'] ?? ':memory:';
$db_path = $opts['database'] ?? ':memory:';

// Validate options before SQLite_Adapter opens or creates the database file.
// MySQL_Proxy checks the bind address too, but only after that.

// Bind address.
$bind_address = $opts['bind-address'] ?? '127.0.0.1';
if ( false === filter_var( $bind_address, FILTER_VALIDATE_IP ) ) {
fwrite( STDERR, "Error: --bind-address must be a valid IPv4 or IPv6 address.\n" );
exit( 1 );
}

// Port.
$port = (int) ( $opts['p'] ?? $opts['port'] ?? 3306 );
if ( $port < 1 || $port > 65535 ) {
$port = filter_var( $opts['port'] ?? 3306, FILTER_VALIDATE_INT );
if ( false === $port || $port < 1 || $port > 65535 ) {
fwrite( STDERR, "Error: --port must be an integer between 1 and 65535. Use --help for more information.\n" );
exit( 1 );
}

// Log level.
$log_level = $opts['l'] ?? $opts['log-level'] ?? 'info';
$log_level = $opts['log-level'] ?? 'info';
if ( ! in_array( $log_level, Logger::LEVELS, true ) ) {
fwrite( STDERR, 'Error: --log-level must be one of: ' . implode( ', ', Logger::LEVELS ) . ". Use --help for more information.\n" );
exit( 1 );
}

// Account. Do not accept passwords as command-line arguments.
$password = getenv( 'WP_MYSQL_PROXY_PASSWORD' );
if ( isset( $opts['password-file'] ) ) {
$password_file = $opts['password-file'];

// Pipes, such as /dev/stdin or a process substitution, keep the password off the disk.
if ( ! is_readable( $password_file ) || is_dir( $password_file ) ) {
fwrite( STDERR, "Error: --password-file must name a readable file.\n" );
exit( 1 );
}

// On Linux, PHP can't open a pipe by its /dev/fd path, so read a descriptor of
// this process through php://fd. See https://github.com/php/php-src/issues/9551.
$source = $password_file;
if ( '/dev/stdin' === $password_file ) {
$source = 'php://fd/0';
} elseif ( preg_match( '~^/(?:dev|proc/self)/fd/(\d+)$~', $password_file, $match ) ) {
$source = 'php://fd/' . $match[1];
}

// Report a failed read without PHP's warning, which names the path.
$password = @file_get_contents( $source ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
if ( false === $password ) {
fwrite( STDERR, "Error: --password-file could not be read.\n" );
exit( 1 );
}
}
try {
$authentication = new MySQL_Authentication(
$opts['user'] ?? '',
(string) $password,
$opts['auth-plugin'] ?? MySQL_Protocol::DEFAULT_AUTH_PLUGIN
);
} catch ( InvalidArgumentException $e ) {
fwrite( STDERR, 'Error: ' . $e->getMessage() . " Use --help for more information.\n" );
exit( 1 );
}
unset( $password );

if ( ! class_exists( 'WP_MySQL_On_SQLite' ) ) {
fwrite(
STDERR,
Expand All @@ -57,8 +170,10 @@
$proxy = new MySQL_Proxy(
new SQLite_Adapter( $db_path ),
array(
'port' => $port,
'log_level' => $log_level,
'authentication' => $authentication,
'bind_address' => $bind_address,
'port' => $port,
'log_level' => $log_level,
)
);
$proxy->start();
4 changes: 4 additions & 0 deletions packages/mysql-proxy/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
},
"require": {
"php": ">=7.2",
"ext-filter": "*",
"ext-hash": "*",
"ext-sockets": "*",
"composer-runtime-api": "^2.2"
},
Expand All @@ -33,6 +35,8 @@
"bin/wp-mysql-proxy.php"
],
"require-dev": {
"ext-mysqli": "*",
"ext-pdo_mysql": "*",
"phpunit/phpunit": "^8.5",
"symfony/process": "^5.4",
"wordpress/mysql-on-sqlite": "*@dev"
Expand Down
33 changes: 26 additions & 7 deletions packages/mysql-proxy/src/Adapter/class-sqlite-adapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

namespace WP_MySQL_Proxy\Adapter;

use Error;
use PDO;
use PDOException;
use PDOStatement;
use Throwable;
use WP_MySQL_Proxy\MySQL_Result;
use WP_MySQL_On_SQLite;
use WP_MySQL_Proxy\MySQL_Protocol;
Expand All @@ -23,7 +23,7 @@ public function __construct( $sqlite_database_path ) {

public function handle_query( string $query ): MySQL_Result {
$affected_rows = 0;
$last_insert_id = null;
$last_insert_id = 0;
$columns = array();
$rows = array();

Expand All @@ -39,12 +39,13 @@ public function handle_query( string $query ): MySQL_Result {
$columns = $this->computeColumnInfo( $statement );
}
return MySQL_Result::from_data( $affected_rows, $last_insert_id, $columns, $rows ?? array() );
} catch ( Throwable $e ) {
$error_info = $e->errorInfo ?? null; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
if ( $e instanceof PDOException && $error_info ) {
return MySQL_Result::from_error( $error_info[0], $error_info[1], $error_info[2] );
} catch ( PDOException $e ) {
// Only query errors reach the client. The session logs internal errors instead.
$error_info = $e->errorInfo; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
if ( ! $error_info || $this->is_internal_error( $e ) ) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
throw $e;
}
return MySQL_Result::from_error( 'HY000', 1105, $e->getMessage() ?? 'Unknown error' );
return MySQL_Result::from_error( $error_info[0], $error_info[1], $error_info[2] );
}
}

Expand Down Expand Up @@ -101,4 +102,22 @@ public function computeColumnInfo( PDOStatement $statement ) {
}
return $columns;
}

/**
* Whether a query exception is a PHP error that the driver reported as a query error.
*
* A PHP error is a bug, not a query error, and its message can contain server
* file paths.
*
* @param PDOException $e The query exception.
* @return bool
*/
private function is_internal_error( PDOException $e ): bool {
for ( $cause = $e->getPrevious(); null !== $cause; $cause = $cause->getPrevious() ) {
if ( $cause instanceof Error ) {
return true;
}
}
return false;
}
}
Loading
Loading