You are here

function drupal_generate_test_ua in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/includes/bootstrap.inc \drupal_generate_test_ua()

Generates a user agent string with a HMAC and timestamp for simpletest.

4 calls to drupal_generate_test_ua()
BrowserTestBase::prepareRequest in core/modules/simpletest/src/BrowserTestBase.php
Prepare for a request to testing site.
SimpleTestBrowserTest::testUserAgentValidation in core/modules/simpletest/src/Tests/SimpleTestBrowserTest.php
Test validation of the User-Agent header we use to perform test requests.
TestHttpClientMiddleware::__invoke in core/lib/Drupal/Core/Test/HttpClientMiddleware/TestHttpClientMiddleware.php
HTTP middleware that replaces the user agent for simpletest requests.
WebTestBase::curlInitialize in core/modules/simpletest/src/WebTestBase.php
Initializes the cURL connection.

File

core/includes/bootstrap.inc, line 651
Functions that need to be loaded on every Drupal request.

Code

function drupal_generate_test_ua($prefix) {
  static $key, $last_prefix;
  if (!isset($key) || $last_prefix != $prefix) {
    $last_prefix = $prefix;
    $key_file = DRUPAL_ROOT . '/sites/simpletest/' . substr($prefix, 10) . '/.htkey';

    // When issuing an outbound HTTP client request from within an inbound test
    // request, then the outbound request has to use the same User-Agent header
    // as the inbound request. A newly generated private key for the same test
    // prefix would invalidate all subsequent inbound requests.
    // @see \Drupal\Core\Http\Plugin\SimpletestHttpRequestSubscriber
    if (DRUPAL_TEST_IN_CHILD_SITE && ($parent_prefix = drupal_valid_test_ua())) {
      if ($parent_prefix != $prefix) {
        throw new \RuntimeException("Malformed User-Agent: Expected '{$parent_prefix}' but got '{$prefix}'.");
      }

      // If the file is not readable, a PHP warning is expected in this case.
      $private_key = file_get_contents($key_file);
    }
    else {

      // Generate and save a new hash salt for a test run.
      // Consumed by drupal_valid_test_ua() before settings.php is loaded.
      $private_key = Crypt::randomBytesBase64(55);
      file_put_contents($key_file, $private_key);
    }

    // The file properties add more entropy not easily accessible to others.
    $key = $private_key . filectime(__FILE__) . fileinode(__FILE__);
  }

  // Generate a moderately secure HMAC based on the database credentials.
  $salt = uniqid('', TRUE);
  $check_string = $prefix . ';' . time() . ';' . $salt;
  return $check_string . ';' . Crypt::hmacBase64($check_string, $key);
}