You are here

public function QueryTest::testArrayArgumentsSQLInjection in Drupal 9

Same name and namespace in other branches
  1. 8 core/tests/Drupal/KernelTests/Core/Database/QueryTest.php \Drupal\KernelTests\Core\Database\QueryTest::testArrayArgumentsSQLInjection()

Tests SQL injection via database query array arguments.

File

core/tests/Drupal/KernelTests/Core/Database/QueryTest.php, line 40

Class

QueryTest
Tests Drupal's extended prepared statement syntax..

Namespace

Drupal\KernelTests\Core\Database

Code

public function testArrayArgumentsSQLInjection() {

  // Attempt SQL injection and verify that it does not work.
  $condition = [
    "1 ;INSERT INTO {test} (name) VALUES ('test12345678'); -- " => '',
    '1' => '',
  ];
  try {
    $this->connection
      ->query("SELECT * FROM {test} WHERE [name] = :name", [
      ':name' => $condition,
    ])
      ->fetchObject();
    $this
      ->fail('SQL injection attempt via array arguments should result in a database exception.');
  } catch (\InvalidArgumentException $e) {

    // Expected exception; just continue testing.
  }

  // Test that the insert query that was used in the SQL injection attempt did
  // not result in a row being inserted in the database.
  $result = $this->connection
    ->select('test')
    ->condition('name', 'test12345678')
    ->countQuery()
    ->execute()
    ->fetchField();
  $this
    ->assertEquals(0, $result, 'SQL injection attempt did not result in a row being inserted in the database table.');
}