Repository navigation
Expand file tree
/
Copy pathWP_MySQL_Session_Command_Test.php
More file actions
304 lines (265 loc) · 13.4 KB
/
Copy pathWP_MySQL_Session_Command_Test.php
File metadata and controls
304 lines (265 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
<?php
use PHPUnit\Framework\TestCase;
use WP_MySQL_Proxy\Adapter\Adapter;
use WP_MySQL_Proxy\Incomplete_Input_Exception;
use WP_MySQL_Proxy\Logger;
use WP_MySQL_Proxy\MySQL_Authentication;
use WP_MySQL_Proxy\MySQL_Protocol;
use WP_MySQL_Proxy\MySQL_Result;
use WP_MySQL_Proxy\MySQL_Session;
class WP_MySQL_Session_Command_Test extends TestCase {
/** @dataProvider database_names */
public function test_init_db_quotes_the_database_name( string $database, string $expected ): void {
$adapter = $this->createMock( Adapter::class );
$adapter->expects( $this->once() )->method( 'handle_query' )->with( $expected )->willReturn( MySQL_Result::from_data( 0, 0, array(), array() ) );
$session = $this->authenticated_session( $adapter );
$response = $session->receive_bytes( MySQL_Protocol::build_packet( 0, chr( MySQL_Protocol::COM_INIT_DB ) . $database ) );
$this->assertSame( 0, ord( $response[4] ) );
}
public function database_names(): array {
return array(
array( 'sqlite_database', 'USE `sqlite_database`' ),
array( 'my db', 'USE `my db`' ),
array( 'a`; DROP TABLE wp_users', 'USE `a``; DROP TABLE wp_users`' ),
);
}
/** @dataProvider init_db_failures */
public function test_init_db_reports_an_unknown_database( bool $throws ): void {
$adapter = $this->createMock( Adapter::class );
$expectation = $adapter->expects( $this->once() )->method( 'handle_query' )->with( 'USE `missing`' );
if ( $throws ) {
$expectation->willThrowException( new RuntimeException( 'Private adapter error' ) );
} else {
$expectation->willReturn( MySQL_Result::from_error( 'HY000', 1105, 'Private adapter error' ) );
}
// The adapter's reason goes to the log, not to the client.
$logger = $this->createMock( Logger::class );
$logger->expects( $this->once() )->method( $throws ? 'error' : 'warning' )->with(
$this->anything(),
$this->callback(
function ( array $context ): bool {
return 'Private adapter error' === $context['error'];
}
)
);
$session = $this->authenticated_session( $adapter, $logger );
$response = $session->receive_bytes( MySQL_Protocol::build_packet( 0, chr( MySQL_Protocol::COM_INIT_DB ) . 'missing' ) );
$this->assertSame( 0xff, ord( $response[4] ) );
$this->assertSame( 1049, unpack( 'v', substr( $response, 5, 2 ) )[1] );
$this->assertSame( "#42000Unknown database 'missing'", substr( $response, 7 ) );
$this->assertFalse( $session->is_closed(), 'Unlike the login, a failed COM_INIT_DB keeps the connection.' );
}
public function init_db_failures(): array {
return array(
'adapter error' => array( false ),
'adapter throws' => array( true ),
);
}
public function test_init_db_refuses_an_empty_name(): void {
$adapter = $this->createMock( Adapter::class );
$adapter->expects( $this->never() )->method( 'handle_query' );
$session = $this->authenticated_session( $adapter );
$response = $session->receive_bytes( MySQL_Protocol::build_packet( 0, chr( MySQL_Protocol::COM_INIT_DB ) ) );
$this->assertSame( 0xff, ord( $response[4] ) );
$this->assertSame( 1046, unpack( 'v', substr( $response, 5, 2 ) )[1] );
$this->assertSame( '#3D000No database selected', substr( $response, 7 ) );
$this->assertFalse( $session->is_closed() );
}
public function test_split_message_is_assembled(): void {
$this->iniSet( 'memory_limit', '512M' );
$queries = array();
$adapter = $this->createMock( Adapter::class );
$adapter->expects( $this->once() )->method( 'handle_query' )->willReturnCallback(
function ( string $query ) use ( &$queries ): MySQL_Result {
$queries[] = $query;
return MySQL_Result::from_data( 0, 0, array(), array() );
}
);
$session = $this->authenticated_session( $adapter );
// A packet with a full payload continues in the next packet.
$prefix = chr( MySQL_Protocol::COM_QUERY ) . 'SELECT 1 -- ';
$packet = MySQL_Protocol::build_packet( 0, $prefix . str_repeat( 'x', MySQL_Protocol::MAX_PACKET_LENGTH - strlen( $prefix ) ) );
try {
$session->receive_bytes( $packet );
$this->fail( 'A split message must wait for the next packet.' );
} catch ( Incomplete_Input_Exception $e ) {
$this->assertSame( array(), $queries, 'The first packet must not run on its own.' );
}
unset( $packet );
// One more byte makes the message exactly 16 MB, the limit.
$response = $session->receive_bytes( MySQL_Protocol::build_packet( 1, '1' ) );
$this->assertSame( 0, ord( $response[4] ) );
$this->assertSame( 2, ord( $response[3] ), 'The response continues the client sequence.' );
$this->assertCount( 1, $queries );
$this->assertSame( MySQL_Session::MAX_MESSAGE_SIZE - 1, strlen( $queries[0] ) );
$this->assertStringEndsWith( 'xx1', $queries[0] );
$this->assertFalse( $session->is_closed() );
}
public function test_oversized_message_is_refused(): void {
$this->iniSet( 'memory_limit', '512M' );
$adapter = $this->createMock( Adapter::class );
$adapter->expects( $this->never() )->method( 'handle_query' );
$session = $this->authenticated_session( $adapter );
$packet = MySQL_Protocol::build_packet( 0, chr( MySQL_Protocol::COM_QUERY ) . str_repeat( 'x', MySQL_Protocol::MAX_PACKET_LENGTH - 1 ) );
try {
$session->receive_bytes( $packet );
$this->fail( 'A split message must wait for the next packet.' );
} catch ( Incomplete_Input_Exception $e ) {
$this->assertFalse( $session->is_closed() );
}
unset( $packet );
// One byte past the limit, which is checked before the payload is buffered.
$response = $session->receive_bytes( MySQL_Protocol::build_packet( 1, '12' ) );
$this->assertSame( 0xff, ord( $response[4] ) );
$this->assertSame( 1153, unpack( 'v', substr( $response, 5, 2 ) )[1] );
$this->assertSame( '#08S01', substr( $response, 7, 6 ) );
$this->assertSame( MySQL_Session::CLOSE_PACKET_TOO_LARGE, $session->get_close_reason() );
$this->assertFalse( $session->has_buffered_data() );
}
public function test_internal_error_is_not_sent_to_the_client(): void {
$adapter = $this->createMock( Adapter::class );
$adapter->expects( $this->once() )->method( 'handle_query' )->willThrowException(
new RuntimeException( 'Private detail from /srv/secret/path.php' )
);
$session = $this->authenticated_session( $adapter );
// The detail goes to the log, which the test runner shows on stderr.
$response = $session->receive_bytes( MySQL_Protocol::build_packet( 0, chr( MySQL_Protocol::COM_QUERY ) . 'SELECT 1' ) );
$this->assertSame( 0xff, ord( $response[4] ) );
$this->assertSame( 1105, unpack( 'v', substr( $response, 5, 2 ) )[1] );
$this->assertSame( 'Unknown error', substr( $response, 13 ) );
$this->assertStringNotContainsString( '/srv/secret/path.php', $response );
}
public function test_internal_error_is_logged_where_it_was_raised(): void {
$cause = new TypeError( 'Private detail' );
$line = __LINE__ - 1;
$adapter = $this->createMock( Adapter::class );
$adapter->expects( $this->once() )->method( 'handle_query' )->willThrowException( new RuntimeException( 'Wrapper', 0, $cause ) );
// The log names the wrapped PHP error, not the wrapper.
$logger = $this->createMock( Logger::class );
$logger->expects( $this->once() )->method( 'error' )->with(
'Client [{client_id}]: internal error: {class}: {error} in {file}:{line}',
array(
'client_id' => 1,
'class' => TypeError::class,
'error' => 'Private detail',
'file' => __FILE__,
'line' => $line,
)
);
$session = $this->authenticated_session( $adapter, $logger );
$session->receive_bytes( MySQL_Protocol::build_packet( 0, chr( MySQL_Protocol::COM_QUERY ) . 'SELECT 1' ) );
}
public function test_result_without_an_insert_id_is_an_ok_packet(): void {
$adapter = $this->createMock( Adapter::class );
$adapter->expects( $this->once() )->method( 'handle_query' )->willReturn( new MySQL_Result() );
$session = $this->authenticated_session( $adapter );
$response = $session->receive_bytes( MySQL_Protocol::build_packet( 0, chr( MySQL_Protocol::COM_QUERY ) . 'DELETE FROM t' ) );
$this->assertSame( 0, ord( $response[4] ) );
$this->assertFalse( $session->is_closed() );
}
public function test_empty_command_packet_is_refused(): void {
$adapter = $this->createMock( Adapter::class );
$adapter->expects( $this->never() )->method( 'handle_query' );
$session = $this->authenticated_session( $adapter );
$response = $session->receive_bytes( MySQL_Protocol::build_packet( 0, '' ) );
$this->assertSame( 0xff, ord( $response[4] ) );
$this->assertSame( 1835, unpack( 'v', substr( $response, 5, 2 ) )[1] );
$this->assertSame( MySQL_Session::CLOSE_MALFORMED_PACKET, $session->get_close_reason() );
}
public function test_quit_closes_the_session(): void {
$adapter = $this->createMock( Adapter::class );
$adapter->expects( $this->never() )->method( 'handle_query' );
$session = $this->authenticated_session( $adapter );
// A pipelined command after COM_QUIT must not run.
$quit = MySQL_Protocol::build_packet( 0, chr( MySQL_Protocol::COM_QUIT ) );
$query = MySQL_Protocol::build_packet( 1, chr( MySQL_Protocol::COM_QUERY ) . 'DELETE FROM wp_users' );
$this->assertSame( '', $session->receive_bytes( $quit . $query ) );
$this->assertTrue( $session->is_closed() );
$this->assertSame( MySQL_Session::CLOSE_CLIENT_QUIT, $session->get_close_reason() );
$this->assertFalse( $session->has_buffered_data() );
$this->assertNull( $session->receive_bytes( $query ) );
}
public function test_failed_login_reports_its_close_reason(): void {
$session = new MySQL_Session( $this->createMock( Adapter::class ), 1, new MySQL_Authentication( 'user', 'password' ) );
$session->get_initial_handshake();
$session->receive_bytes( MySQL_Protocol::build_packet( 1, str_repeat( "\0", 40 ) ) );
$this->assertSame( MySQL_Session::CLOSE_LOGIN_FAILED, $session->get_close_reason() );
}
public function test_large_result_rows_are_split_across_packets(): void {
$this->iniSet( 'memory_limit', '512M' );
// 16,777,211 bytes + 4-byte 0xfd length prefix = 16,777,215 (exact MAX_PACKET_LENGTH).
$exact_value = str_repeat( 'a', MySQL_Protocol::MAX_PACKET_LENGTH - 4 );
// 16,777,212 bytes + 4-byte 0xfd length prefix = 16,777,216 (MAX_PACKET_LENGTH + 1).
$over_value = str_repeat( 'b', MySQL_Protocol::MAX_PACKET_LENGTH - 4 ) . 'Z';
$column = array(
'name' => 'v',
'length' => MySQL_Protocol::MAX_PACKET_LENGTH + 16,
'type' => MySQL_Protocol::FIELD_TYPE_LONG_BLOB,
'flags' => 0,
'decimals' => 0,
);
$rows = array(
(object) array( 'v' => $exact_value ),
(object) array( 'v' => $over_value ),
);
$result = MySQL_Result::from_data( 0, 0, array( $column ), $rows );
$adapter = new class( $result ) implements Adapter {
/** @var MySQL_Result */
private $result;
public function __construct( MySQL_Result $result ) {
$this->result = $result;
}
public function handle_query( string $query ): MySQL_Result {
return $this->result;
}
};
$session = $this->authenticated_session( $adapter );
$response = $session->receive_bytes(
MySQL_Protocol::build_packet( 0, chr( MySQL_Protocol::COM_QUERY ) . 'SELECT v FROM t' )
);
// Reassemble split MySQL logical messages from the wire stream.
$messages = array();
$wire_sequence_ids = array();
$offset = 0;
$total = strlen( $response );
$current_message = '';
$expected_sequence = 1;
while ( $offset < $total ) {
$length = unpack( 'V', substr( $response, $offset, 3 ) . "\0" )[1];
$sequence_id = ord( $response[ $offset + 3 ] );
$this->assertSame( $expected_sequence, $sequence_id );
$expected_sequence = ( $expected_sequence + 1 ) & 0xff;
$wire_sequence_ids[] = $sequence_id;
$current_message .= substr( $response, $offset + 4, $length );
$offset += 4 + $length;
if ( MySQL_Protocol::MAX_PACKET_LENGTH !== $length ) {
$messages[] = $current_message;
$current_message = '';
}
}
// Wire packets without CLIENT_DEPRECATE_EOF:
// 1=column count, 2=column def, 3=columns EOF, 4+5=row 1 (0xffffff + 0), 6+7=row 2 (0xffffff + 1), 8=rows EOF.
$this->assertSame( array( 1, 2, 3, 4, 5, 6, 7, 8 ), $wire_sequence_ids );
$this->assertCount( 6, $messages );
$this->assertSame( MySQL_Protocol::EOF_PACKET_HEADER, ord( $messages[2][0] ) );
$row1_offset = 0;
$this->assertSame( $exact_value, MySQL_Protocol::read_length_encoded_string( $messages[3], $row1_offset ) );
$this->assertSame( strlen( $messages[3] ), $row1_offset );
$row2_offset = 0;
$this->assertSame( $over_value, MySQL_Protocol::read_length_encoded_string( $messages[4], $row2_offset ) );
$this->assertSame( strlen( $messages[4] ), $row2_offset );
// Trailing packet is the EOF terminator (0xfe), not swallowed into row 1 or row 2.
$this->assertSame( MySQL_Protocol::EOF_PACKET_HEADER, ord( $messages[5][0] ) );
// A subsequent command on the same session remains synchronized.
$ping_response = $session->receive_bytes( MySQL_Protocol::build_packet( 0, chr( MySQL_Protocol::COM_PING ) ) );
$this->assertSame( 1, ord( $ping_response[3] ) );
$this->assertSame( MySQL_Protocol::OK_PACKET_HEADER, ord( $ping_response[4] ) );
}
private function authenticated_session( Adapter $adapter, ?Logger $logger = null ): MySQL_Session {
$session = new MySQL_Session( $adapter, 1, new MySQL_Authentication( 'user', 'password' ), $logger );
$challenge = MySQL_Test_Client::challenge( $session->get_initial_handshake() );
$session->receive_bytes( MySQL_Test_Client::handshake_response( $challenge ) );
$this->assertTrue( $session->is_authenticated() );
return $session;
}
}