Skip to content
Snippets Groups Projects

Only set User-Agent for requests to the correct host.

1 unresolved thread
Files
6
@@ -7,12 +7,29 @@
use Psr\Http\Message\ResponseInterface;
/**
* Overrides the User-Agent HTTP header for outbound HTTP requests.
* Blocks unknown external hosts and replaces the user agent for test requests.
*/
class TestHttpClientMiddleware {
/**
* HTTP middleware that replaces the user agent for test requests.
* List of external host names that tests can make HTTP requests to.
*
* @var string[]
*/
protected static array $allowedHosts = ['ftp.drupal.org', 'oembed.com'];
/**
* Adds a host name to the allow list for the remainder of this test run.
*
* @param string $host
* The hostname to allow.
*/
public static function allowHost(string $host): void {
static::$allowedHosts[] = $host;
}
/**
* Block unknown external hosts and replace the user agent.
*/
public function __invoke() {
// If the database prefix is being used to run the tests in a copied
@@ -26,6 +43,18 @@ public function __invoke() {
if ($user_agent = drupal_generate_test_ua(drupal_valid_test_ua())) {
$request = $request->withHeader('User-Agent', $user_agent);
}
// Allow specific hosts with no alterations.
if (in_array($request->getUri()->getHost(), static::$allowedHosts, TRUE)) {
return $handler($request, $options);
}
// Disallow other external hosts.
$host = parse_url(getenv('SIMPLETEST_BASE_URL'), PHP_URL_HOST);
if ($host !== $request->getUri()->getHost()) {
throw new \RuntimeException(sprintf('Tests should only make requests to the SIMPLETEST_BASE_URL host of %s, but a request to %s was made.', $host, $request->getUri()->getHost()));
}
return $handler($request, $options)
->then(function (ResponseInterface $response) {
if (!drupal_valid_test_ua()) {
Loading