 core/core.services.yml                             |   2 +-
 .../cacheability_safeguards.info.yml               |   7 ++
 .../src/CacheabilityBubblingNodeGrantStorage.php   | 124 +++++++++++++++++++++
 .../src/CacheabilitySafeguardsServiceProvider.php  |  45 ++++++++
 .../Tests/NodeAccessCacheabilitySafeguardTest.php  |  73 ++++++++++++
 .../node_access_test_auto_bubbling.info.yml        |   6 +
 .../node_access_test_auto_bubbling.routing.yml     |   6 +
 .../NodeAccessTestAutoBubblingController.php       |  62 +++++++++++
 core/modules/system/system.install                 |   7 ++
 9 files changed, 331 insertions(+), 1 deletion(-)

diff --git a/core/core.services.yml b/core/core.services.yml
index ed1341c..b3f4195 100644
--- a/core/core.services.yml
+++ b/core/core.services.yml
@@ -9,7 +9,7 @@ parameters:
     auto_reload: null
     cache: true
   renderer.config:
-    required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions']
+    required_cache_contexts: ['languages:language_interface', 'theme']
     auto_placeholder_conditions:
       max-age: 0
       contexts: ['session', 'user']
diff --git a/core/modules/cacheability_safeguards/cacheability_safeguards.info.yml b/core/modules/cacheability_safeguards/cacheability_safeguards.info.yml
new file mode 100644
index 0000000..94f3498
--- /dev/null
+++ b/core/modules/cacheability_safeguards/cacheability_safeguards.info.yml
@@ -0,0 +1,7 @@
+name: Cacheability Safeguards
+type: module
+package: Core
+core: 8.x
+required: true
+hidden: true
+version: VERSION
diff --git a/core/modules/cacheability_safeguards/src/CacheabilityBubblingNodeGrantStorage.php b/core/modules/cacheability_safeguards/src/CacheabilityBubblingNodeGrantStorage.php
new file mode 100644
index 0000000..890e968
--- /dev/null
+++ b/core/modules/cacheability_safeguards/src/CacheabilityBubblingNodeGrantStorage.php
@@ -0,0 +1,124 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\cacheability_safeguards\CacheabilityBubblingNodeGrantStorage.
+ */
+
+namespace Drupal\cacheability_safeguards;
+
+use Drupal\Core\DependencyInjection\DependencySerializationTrait;
+use Drupal\Core\Session\AccountInterface;
+use Drupal\node\NodeGrantDatabaseStorageInterface;
+use Drupal\node\NodeInterface;
+use Symfony\Component\DependencyInjection\ContainerAwareInterface;
+use Symfony\Component\DependencyInjection\ContainerAwareTrait;
+
+/**
+ * Decorator for node grants storage, which bubbles access grants cacheability.
+ *
+ * Code that performs a node_access query should explicitly add the
+ * 'user.node_grants:$op' cache context to the render element or
+ * \Drupal\Core\Cache\CacheableDependencyInterface object that is affected by
+ * the query. Doing so ensures that the context is attached to the most
+ * appropriate element or object. However, since cache contexts are new to
+ * Drupal 8, to safeguard route controllers or other code that forget to do
+ * this, this decorator also adds it to the current render context.
+ *
+ * The renderer is not injected to avoid initializing the render and theme
+ * system for REST routes. Instead, this service is container-aware.
+ *
+ * @see \Drupal\Core\Render\MetadataBubblingUrlGenerator
+ *
+ * @todo Remove before Drupal 9.0.0.
+ *
+ * @ingroup node_access
+ */
+class CacheabilityBubblingNodeGrantStorage implements NodeGrantDatabaseStorageInterface, ContainerAwareInterface {
+
+  use ContainerAwareTrait;
+  use DependencySerializationTrait;
+
+  /**
+   * The non-bubbling node grant storage.
+   *
+   * @var \Drupal\node\NodeGrantDatabaseStorageInterface
+   */
+  protected $nodeGrantStorage;
+
+  /**
+   * Constructs a CacheabilityBubblingNodeGrantStorage object.
+   *
+   * @param \Drupal\node\NodeGrantDatabaseStorageInterface $node_grant_storage
+   *   The non-bubbling node grant storage.
+   */
+  public function __construct(NodeGrantDatabaseStorageInterface $node_grant_storage) {
+    $this->nodeGrantStorage = $node_grant_storage;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function access(NodeInterface $node, $operation, $langcode, AccountInterface $account) {
+    return $this->nodeGrantStorage->access($node, $operation, $langcode, $account);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function checkAll(AccountInterface $account) {
+    return $this->nodeGrantStorage->checkAll($account);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function alterQuery($query, array $tables, $op, AccountInterface $account, $base_table) {
+    // Bubble the 'user.node_grants:$op' cache context to the current render
+    // context.
+    /** @var \Drupal\Core\Render\RendererInterface $renderer */
+    $renderer = $this->container->get('renderer');
+    if ($renderer->hasRenderContext()) {
+      $build = ['#cache' => ['contexts' => ['user.node_grants:' . $op]]];
+      $renderer->render($build);
+    }
+
+    return $this->nodeGrantStorage->alterQuery($query, $tables, $op, $account, $base_table);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function write(NodeInterface $node, array $grants, $realm = NULL, $delete = TRUE) {
+    return $this->nodeGrantStorage->write($node, $grants, $realm, $delete);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function delete() {
+    return $this->nodeGrantStorage->delete();
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function writeDefault() {
+    return $this->nodeGrantStorage->writeDefault();
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function count() {
+    return $this->nodeGrantStorage->count();
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function deleteNodeRecords(array $nids) {
+    return $this->nodeGrantStorage->deleteNodeRecords($nids);
+  }
+
+}
diff --git a/core/modules/cacheability_safeguards/src/CacheabilitySafeguardsServiceProvider.php b/core/modules/cacheability_safeguards/src/CacheabilitySafeguardsServiceProvider.php
new file mode 100644
index 0000000..83d69be
--- /dev/null
+++ b/core/modules/cacheability_safeguards/src/CacheabilitySafeguardsServiceProvider.php
@@ -0,0 +1,45 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\cacheability_safeguards\CacheContextSafeguardsServiceProvider.
+ */
+
+namespace Drupal\cacheability_safeguards;
+
+use Drupal\Core\DependencyInjection\ContainerBuilder;
+use Drupal\Core\DependencyInjection\ServiceModifierInterface;
+use Symfony\Component\DependencyInjection\Reference;
+
+/**
+ * …
+ */
+class CacheabilitySafeguardsServiceProvider implements ServiceModifierInterface {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function alter(ContainerBuilder $container) {
+    // Also make the 'user.permissions' cache context required.
+    if ($container->hasParameter('renderer.config')) {
+      $renderer_config = $container->getParameter('renderer.config');
+      if (!in_array('user.permissions', $renderer_config['required_cache_contexts'])) {
+        $renderer_config['required_cache_contexts'][] = 'user.permissions';
+        sort($renderer_config['required_cache_contexts']);
+      }
+      $container->setParameter('renderer.config', $renderer_config);
+    }
+
+    // Automatically bubble the 'user.node_grants:$op' cache context.
+    if ($container->has('node.grant_storage')) {
+      $container->setDefinition('node.grant_storage.non_bubbling', $container->getDefinition('node.grant_storage'))
+        ->setPublic(FALSE);
+      $container->register('node.grant_storage')
+        ->setClass('\Drupal\cacheability_safeguards\CacheabilityBubblingNodeGrantStorage')
+        ->addArgument(new Reference('node.grant_storage.non_bubbling'))
+        ->addMethodCall('setContainer', [new Reference('service_container')]);
+    }
+  }
+
+}
+
diff --git a/core/modules/cacheability_safeguards/src/Tests/NodeAccessCacheabilitySafeguardTest.php b/core/modules/cacheability_safeguards/src/Tests/NodeAccessCacheabilitySafeguardTest.php
new file mode 100644
index 0000000..97628f1
--- /dev/null
+++ b/core/modules/cacheability_safeguards/src/Tests/NodeAccessCacheabilitySafeguardTest.php
@@ -0,0 +1,73 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\cacheability_safeguards\Tests\NodeAccessCacheabilitySafeguardTest.
+ */
+
+namespace Drupal\cacheability_safeguards\Tests;
+
+use Drupal\Core\Url;
+use Drupal\node\Tests\NodeTestBase;
+
+/**
+ * Tests the node access cacheability safeguard.
+ *
+ * @group cacheability_safeguards
+ * @group node
+ * @group Cache
+ */
+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/cacheability_safeguards/tests/node_access_test_auto_bubbling/node_access_test_auto_bubbling.info.yml b/core/modules/cacheability_safeguards/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/cacheability_safeguards/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/cacheability_safeguards/tests/node_access_test_auto_bubbling/node_access_test_auto_bubbling.routing.yml b/core/modules/cacheability_safeguards/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/cacheability_safeguards/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/cacheability_safeguards/tests/node_access_test_auto_bubbling/src/Controller/NodeAccessTestAutoBubblingController.php b/core/modules/cacheability_safeguards/tests/node_access_test_auto_bubbling/src/Controller/NodeAccessTestAutoBubblingController.php
new file mode 100644
index 0000000..c7788d0
--- /dev/null
+++ b/core/modules/cacheability_safeguards/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/system.install b/core/modules/system/system.install
index ce06b7a..29a28c7 100644
--- a/core/modules/system/system.install
+++ b/core/modules/system/system.install
@@ -1268,3 +1268,10 @@ function system_update_8004() {
     $manager->updateEntityType($manager->getEntityType($entity_type_id));
   }
 }
+
+/**
+ * Install the cache_context_safeguards module.
+ */
+function system_update_8005() {
+  \Drupal::service('module_installer')->install(['cache_context_safeguards']);
+}
