 .../block/src/Tests/BlockViewBuilderTest.php       |  5 +-
 .../MenuLinkContentCacheabilityBubblingTest.php    |  3 +-
 core/modules/node/node.module                      |  8 +++
 .../Tests/NodeAccessCacheabilitySafeguardTest.php  | 72 ++++++++++++++++++++++
 .../modules/node/src/Tests/NodeListBuilderTest.php |  4 +-
 .../node_access_test_auto_bubbling.info.yml        |  6 ++
 .../node_access_test_auto_bubbling.routing.yml     |  6 ++
 .../NodeAccessTestAutoBubblingController.php       | 62 +++++++++++++++++++
 .../src/Tests/Entity/EntityViewBuilderTest.php     |  9 +--
 9 files changed, 164 insertions(+), 11 deletions(-)

diff --git a/core/modules/block/src/Tests/BlockViewBuilderTest.php b/core/modules/block/src/Tests/BlockViewBuilderTest.php
index 331db82..9b5def3 100644
--- a/core/modules/block/src/Tests/BlockViewBuilderTest.php
+++ b/core/modules/block/src/Tests/BlockViewBuilderTest.php
@@ -9,7 +9,6 @@
 
 use Drupal\Component\Utility\Html;
 use Drupal\Core\Cache\Cache;
-use Drupal\Core\Language\LanguageInterface;
 use Drupal\simpletest\KernelTestBase;
 use Drupal\block\Entity\Block;
 
@@ -158,7 +157,7 @@ protected function verifyRenderCacheHandling() {
 
     // Test that a cache entry is created.
     $build = $this->getBlockRenderArray();
-    $cid = 'entity_view:block:test_block:' . implode(':', \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:' . LanguageInterface::TYPE_INTERFACE, 'theme', 'user.permissions'])->getKeys());
+    $cid = 'entity_view:block:test_block:' . implode(':', \Drupal::service('cache_contexts_manager')->convertTokensToKeys($this->container->getParameter('renderer.config')['required_cache_contexts'])->getKeys());
     $this->renderer->renderRoot($build);
     $this->assertTrue($this->container->get('cache.render')->get($cid), 'The block render element has been cached.');
 
@@ -292,7 +291,7 @@ public function testBlockViewBuilderBuildAlter() {
    *   The expected max-age.
    */
   protected function assertBlockRenderedWithExpectedCacheability(array $expected_keys, array $expected_contexts, array $expected_tags, $expected_max_age) {
-    $required_cache_contexts = ['languages:' . LanguageInterface::TYPE_INTERFACE, 'theme', 'user.permissions'];
+    $required_cache_contexts = $this->container->getParameter('renderer.config')['required_cache_contexts'];
 
     // Check that the expected cacheability metadata is present in:
     // - the built render array;
diff --git a/core/modules/menu_link_content/src/Tests/MenuLinkContentCacheabilityBubblingTest.php b/core/modules/menu_link_content/src/Tests/MenuLinkContentCacheabilityBubblingTest.php
index 825f493..22fd283 100644
--- a/core/modules/menu_link_content/src/Tests/MenuLinkContentCacheabilityBubblingTest.php
+++ b/core/modules/menu_link_content/src/Tests/MenuLinkContentCacheabilityBubblingTest.php
@@ -8,7 +8,6 @@
 namespace Drupal\menu_link_content\Tests;
 
 use Drupal\Core\Cache\Cache;
-use Drupal\Core\Language\LanguageInterface;
 use Drupal\Core\Menu\MenuTreeParameters;
 use Drupal\Core\Render\BubbleableMetadata;
 use Drupal\menu_link_content\Entity\MenuLinkContent;
@@ -69,7 +68,7 @@ public function testOutboundPathAndRouteProcessing() {
     $default_menu_cacheability = (new BubbleableMetadata())
       ->setCacheMaxAge(Cache::PERMANENT)
       ->setCacheTags(['config:system.menu.tools'])
-      ->setCacheContexts(['languages:' . LanguageInterface::TYPE_INTERFACE, 'theme', 'user.permissions']);
+      ->setCacheContexts($this->container->getParameter('renderer.config')['required_cache_contexts']);
 
     User::create(['uid' => 1, 'name' => $this->randomString()])->save();
     User::create(['uid' => 2, 'name' => $this->randomString()])->save();
diff --git a/core/modules/node/node.module b/core/modules/node/node.module
index 896c4f8..a54fc0a 100644
--- a/core/modules/node/node.module
+++ b/core/modules/node/node.module
@@ -1064,6 +1064,14 @@ function node_query_node_access_alter(AlterableInterface $query) {
 
   // Update the query for the given storage method.
   \Drupal::service('node.grant_storage')->alterQuery($query, $tables, $op, $account, $base_table);
+
+  // Bubble the 'user.node_grants:$op' cache context to the current render
+  // context.
+  $renderer = \Drupal::service('renderer');
+  if ($renderer->hasRenderContext()) {
+    $build = ['#cache' => ['contexts' => ['user.node_grants:' . $op]]];
+    $renderer->render($build);
+  }
 }
 
 /**
diff --git a/core/modules/node/src/Tests/NodeAccessCacheabilitySafeguardTest.php b/core/modules/node/src/Tests/NodeAccessCacheabilitySafeguardTest.php
new file mode 100644
index 0000000..b2f930e
--- /dev/null
+++ b/core/modules/node/src/Tests/NodeAccessCacheabilitySafeguardTest.php
@@ -0,0 +1,72 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\node\Tests\NodeAccessCacheabilitySafeguardTest.
+ */
+
+namespace Drupal\node\Tests;
+
+use Drupal\Core\Url;
+
+/**
+ * Tests the node access cacheability safeguard.
+ *
+ * @group node
+ * @group Cache
+ * @group cacheability_safeguards
+ */
+class NodeAccessCacheabilitySafeguardTest extends NodeTestBase {
+
+  /**
+   * Modules to enable.
+   *
+   * @var array
+   */
+  public static $modules = ['node_access_test', 'node_access_test_auto_bubbling'];
+
+  /**
+   * {@inheritdoc}
+   */
+  protected function setUp() {
+    parent::setUp();
+
+    node_access_rebuild();
+
+    // Create some content.
+    $this->drupalCreateNode();
+    $this->drupalCreateNode();
+    $this->drupalCreateNode();
+    $this->drupalCreateNode();
+  }
+
+  /**
+   * Tests that the node grants cache context is auto-added, only when needed.
+   *
+   * @see \Drupal\cacheability_safeguards\CacheabilityBubblingNodeGrantStorage
+   */
+  public function testNodeAccessCacheabilitySafeguard() {
+    $this->dumpHeaders = TRUE;
+
+    // The node grants cache context should be added automatically.
+    $this->drupalGet(new Url('node_access_test_auto_bubbling'));
+    $this->assertCacheContext('user.node_grants:view');
+
+    // The root user has the 'bypass node access' permission, which means the
+    // node grants cache context is not necessary.
+    $this->drupalLogin($this->rootUser);
+    $this->drupalGet(new Url('node_access_test_auto_bubbling'));
+    $this->assertNoCacheContext('user.node_grants:view');
+    $this->drupalLogout();
+
+    // Uninstall the module with the only hook_node_grants() implementation.
+    $this->container->get('module_installer')->uninstall(['node_access_test']);
+    $this->rebuildContainer();
+
+    // Because there are no node grants defined, there also is no need for the
+    // node grants cache context to be bubbled.
+    $this->drupalGet(new Url('node_access_test_auto_bubbling'));
+    $this->assertNoCacheContext('user.node_grants:view');
+  }
+
+}
diff --git a/core/modules/node/src/Tests/NodeListBuilderTest.php b/core/modules/node/src/Tests/NodeListBuilderTest.php
index 2d23604..c62e048 100644
--- a/core/modules/node/src/Tests/NodeListBuilderTest.php
+++ b/core/modules/node/src/Tests/NodeListBuilderTest.php
@@ -7,7 +7,7 @@
 
 namespace Drupal\node\Tests;
 
-use Drupal\Core\Language\LanguageInterface;
+use Drupal\Core\Cache\Cache;
 use Drupal\simpletest\KernelTestBase;
 
 /**
@@ -39,7 +39,7 @@ public function testCacheContexts() {
     $build = $list_builder->render();
     $this->container->get('renderer')->renderRoot($build);
 
-    $this->assertEqual(['languages:' . LanguageInterface::TYPE_INTERFACE, 'theme', 'url.query_args.pagers:0', 'user.node_grants:view', 'user.permissions'], $build['#cache']['contexts']);
+    $this->assertEqual(Cache::mergeContexts($this->container->getParameter('renderer.config')['required_cache_contexts'], ['url.query_args.pagers:0', 'user.node_grants:view']), $build['#cache']['contexts']);
   }
 
 }
diff --git a/core/modules/node/tests/node_access_test_auto_bubbling/node_access_test_auto_bubbling.info.yml b/core/modules/node/tests/node_access_test_auto_bubbling/node_access_test_auto_bubbling.info.yml
new file mode 100644
index 0000000..49a990d
--- /dev/null
+++ b/core/modules/node/tests/node_access_test_auto_bubbling/node_access_test_auto_bubbling.info.yml
@@ -0,0 +1,6 @@
+name: 'Node module access automatic cacheability bubbling tests'
+type: module
+description: 'Support module for node permission testing. Provides a route which does a node access query without explicitly specifying the corresponding cache context.'
+package: Testing
+version: VERSION
+core: 8.x
diff --git a/core/modules/node/tests/node_access_test_auto_bubbling/node_access_test_auto_bubbling.routing.yml b/core/modules/node/tests/node_access_test_auto_bubbling/node_access_test_auto_bubbling.routing.yml
new file mode 100644
index 0000000..34fd420
--- /dev/null
+++ b/core/modules/node/tests/node_access_test_auto_bubbling/node_access_test_auto_bubbling.routing.yml
@@ -0,0 +1,6 @@
+node_access_test_auto_bubbling:
+  path: '/node_access_test_auto_bubbling'
+  defaults:
+    _controller: '\Drupal\node_access_test_auto_bubbling\Controller\NodeAccessTestAutoBubblingController::latest'
+  requirements:
+    _access: 'TRUE'
diff --git a/core/modules/node/tests/node_access_test_auto_bubbling/src/Controller/NodeAccessTestAutoBubblingController.php b/core/modules/node/tests/node_access_test_auto_bubbling/src/Controller/NodeAccessTestAutoBubblingController.php
new file mode 100644
index 0000000..89e7ce4
--- /dev/null
+++ b/core/modules/node/tests/node_access_test_auto_bubbling/src/Controller/NodeAccessTestAutoBubblingController.php
@@ -0,0 +1,62 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\node_access_test_auto_bubbling\Controller\NodeAccessTestAutoBubblingController.
+ */
+
+namespace Drupal\node_access_test_auto_bubbling\Controller;
+
+use Drupal\Core\Controller\ControllerBase;
+use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
+use Drupal\Core\Entity\Query\QueryFactory;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+
+/**
+ * Returns a node ID listing.
+ */
+class NodeAccessTestAutoBubblingController extends ControllerBase implements ContainerInjectionInterface {
+
+  /**
+   * The entity query factory service.
+   *
+   * @var \Drupal\Core\Entity\Query\QueryFactory
+   */
+  protected $entityQuery;
+
+  /**
+   * Constructs a new NodeAccessTestAutoBubblingController.
+   *
+   * @param \Drupal\Core\Entity\Query\QueryFactory $entity_query
+   *   The entity query factory.
+   */
+  public function __construct(QueryFactory $entity_query) {
+    $this->entityQuery = $entity_query;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function create(ContainerInterface $container) {
+    return new static(
+      $container->get('entity.query')
+    );
+  }
+
+  /**
+   * Lists the three latest published node IDs.
+   *
+   * @return array
+   *   A render array.
+   */
+  public function latest() {
+    $nids = $this->entityQuery->get('node')
+      ->condition('status', NODE_PUBLISHED)
+      ->sort('created', 'DESC')
+      ->range(0, 3)
+      ->addTag('node_access')
+      ->execute();
+    return ['#markup' => $this->t('The three latest nodes are: @nids.', ['@nids' => implode(', ', $nids)])];
+  }
+
+}
diff --git a/core/modules/system/src/Tests/Entity/EntityViewBuilderTest.php b/core/modules/system/src/Tests/Entity/EntityViewBuilderTest.php
index a3e6cd1..4fb8448 100644
--- a/core/modules/system/src/Tests/Entity/EntityViewBuilderTest.php
+++ b/core/modules/system/src/Tests/Entity/EntityViewBuilderTest.php
@@ -7,7 +7,6 @@
 
 namespace Drupal\system\Tests\Entity;
 
-use Drupal\Core\Language\LanguageInterface;
 use Drupal\field\Tests\EntityReference\EntityReferenceTestTrait;
 use Drupal\Core\Cache\Cache;
 use Drupal\user\Entity\Role;
@@ -59,7 +58,7 @@ public function testEntityViewBuilderCache() {
     // Get a fully built entity view render array.
     $entity_test->save();
     $build = $this->container->get('entity.manager')->getViewBuilder('entity_test')->view($entity_test, 'full');
-    $cid_parts = array_merge($build['#cache']['keys'], $cache_contexts_manager->convertTokensToKeys(['languages:' . LanguageInterface::TYPE_INTERFACE, 'theme', 'user.permissions'])->getKeys());
+    $cid_parts = array_merge($build['#cache']['keys'], $cache_contexts_manager->convertTokensToKeys($this->container->getParameter('renderer.config')['required_cache_contexts'])->getKeys());
     $cid = implode(':', $cid_parts);
     $bin = $build['#cache']['bin'];
 
@@ -93,6 +92,8 @@ public function testEntityViewBuilderCache() {
    * Tests entity render cache with references.
    */
   public function testEntityViewBuilderCacheWithReferences() {
+    $required_cache_contexts = $this->container->getParameter('renderer.config')['required_cache_contexts'];
+
     /** @var \Drupal\Core\Render\RendererInterface $renderer */
     $renderer = $this->container->get('renderer');
     $cache_contexts_manager = \Drupal::service("cache_contexts_manager");
@@ -113,7 +114,7 @@ public function testEntityViewBuilderCacheWithReferences() {
 
     // Get a fully built entity view render array for the referenced entity.
     $build = $this->container->get('entity.manager')->getViewBuilder('entity_test')->view($entity_test_reference, 'full');
-    $cid_parts = array_merge($build['#cache']['keys'], $cache_contexts_manager->convertTokensToKeys(['languages:' . LanguageInterface::TYPE_INTERFACE, 'theme', 'user.permissions'])->getKeys());
+    $cid_parts = array_merge($build['#cache']['keys'], $cache_contexts_manager->convertTokensToKeys($required_cache_contexts)->getKeys());
     $cid_reference = implode(':', $cid_parts);
     $bin_reference = $build['#cache']['bin'];
 
@@ -132,7 +133,7 @@ public function testEntityViewBuilderCacheWithReferences() {
 
     // Get a fully built entity view render array.
     $build = $this->container->get('entity.manager')->getViewBuilder('entity_test')->view($entity_test, 'full');
-    $cid_parts = array_merge($build['#cache']['keys'], $cache_contexts_manager->convertTokensToKeys(['languages:' . LanguageInterface::TYPE_INTERFACE, 'theme', 'user.permissions'])->getKeys());
+    $cid_parts = array_merge($build['#cache']['keys'], $cache_contexts_manager->convertTokensToKeys($required_cache_contexts)->getKeys());
     $cid = implode(':', $cid_parts);
     $bin = $build['#cache']['bin'];
 
