Add user_requirements to check for missing anonymous user

Created on 27 May 2019, over 4 years ago
Updated 12 February 2024, 13 days ago

Problem/Motivation

After updating my site from 8.6.x -> 8.7.x, all anonymous user traffic gets the following error:

The 'entity:user' context is required and not present.

All updates preformed as expected and I don't know why I am seeing these errors. I pulled down a version of 8.7.x and compared the two stack traces between the working 8.7.x and my updated site and found that ContentEntityStorageBase::getFromPersistentCache() returns null on my site while in 8.7.x it returns an anonymous user object. Here is the stack trace:

* `EntityConverter::convert()`
* `LazyContextRepository::getAvailableContexts()`
* `CurrentUserContext::getRuntimeContexts()`
* `EntityStorageBase::load()`
* `SqlContentEntityStorage::doLoadMultiple()`
* `ContentEntityStorageBase::getFromPersistentCache()`

This is due to no record in the users table for the anonymous user.

Proposed resolution

Add a hook_requirements() to check that there's a record for user 0 and warn the site administrator if not. There's already a page on Drupal.org with instructions on how to update: Restore the anonymous (user ID 0) user record โ†’

Remaining tasks

Write a patch
Review
Commit

User interface changes

When anonymous exists

No status message

Doesn't exist

API changes

Data model changes

Release notes snippet

๐Ÿ“Œ Task
Status

RTBC

Version

11.0 ๐Ÿ”ฅ

Component
User systemย  โ†’

Last updated 3 days ago

Created by

๐Ÿ‡บ๐Ÿ‡ธUnited States robpowell Boston

Live updates comments and jobs are added and updated live.

Missing content requested by

๐Ÿ‡ฆ๐Ÿ‡บAustralia dpi
about 2 months ago
Sign in to follow issues

Merge Requests

Comments & Activities

  • Issue created by @robpowell
  • ๐Ÿ‡ฌ๐Ÿ‡งUnited Kingdom catch

    Bumping this to critical - if it's a contrib module issue we can move it there, but given at least two people have hit this on upgrade we should narrow it down.

  • ๐Ÿ‡บ๐Ÿ‡ธUnited States jimafisk

    Here are some details about the state of things leading up to the error (before attempting the 8.7.x upgrade):

    Drupal version: 8.6.16.

    Running lando drush updb returns [success] No pending updates.

    Running lando drush entup using devel_entity_updates โ†’ returns

    The following updates are pending:
    
    comment entity type : 
    The User ID field needs to be updated.
    media entity type : 
    The Authored by field needs to be updated.
    taxonomy_term entity type : 
    The Taxonomy term entity type needs to be updated.
    The Revision ID field needs to be uninstalled.
    The Default revision field needs to be uninstalled.
    The Revision translation affected field needs to be uninstalled.
    The Revision create time field needs to be uninstalled.
    The Revision user field needs to be uninstalled.
    The Revision log message field needs to be uninstalled.
    menu_link_content entity type : 
    The Custom menu link entity type needs to be updated.
    The Revision ID field needs to be uninstalled.
    The Default revision field needs to be uninstalled.
    The Revision translation affected field needs to be uninstalled.
    The Revision create time field needs to be uninstalled.
    The Revision user field needs to be uninstalled.
    The Revision log message field needs to be uninstalled.
    

    Completing the command by typing "yes" returns the following error:

    In DevelEntityDefinitionUpdateManager.php line 169:
    The entity schema update for the taxonomy_term entity type requires a data migration.
    

    In the database there are tables that look like this:

    old_7d434ataxonomy_term__parent
    old_7d434ataxonomy_term_data
    old_7d434ataxonomy_term_field_data
    old_7eea43menu_link_content
    old_7eea43menu_link_content_data
    

    If I try to upgrade to 8.7 anyways without resolving these entity issues, after the upgrade I get the 'entity:user' context is required and not present error in the browser for anonymous users. Running lando drush updb still returns [success] No pending updates. but lando drush entup now only returns:

    The following updates are pending:
    
    comment entity type : 
    The Entity type field needs to be updated.
    The Comment field name field needs to be updated.
    

    Now I can successfully run those entity updates using devel_entity_updates โ†’ but the 'entity:user' context is required and not present error for anonymous users remains.

    I have also tried restoring a MySQL backup from mid April and re-running lando drush updb for the 8.6.16 database updates, which runs:

    ------------- ------------------- --------------- ---------------------------------------------------------------------
     Module        Update ID           Type            Description                                                         
    ------------- ------------------- --------------- ---------------------------------------------------------------------
     field_group   8301                hook_update_n   Set the `region` portion of each field group.                       
     salesforce    8005                hook_update_n   Convert legacy oauth credentials to new auth plugin config.         
     salesforce    8006                hook_update_n   Convert legacy token to new auth plugin config.                     
     system        fix_jquery_extend   post-update     Clear the library cache and ensure aggregate files are regenerated. 
    ------------- ------------------- --------------- ---------------------------------------------------------------------
    

    After that lando drush entup returns [success] No entity schema updates required [success] Finished performing updates. But I still get the same The 'entity:user' context is required and not present. error in the browser when trying to upgrade to 8.7.x with lando composer update drupal/core webflo/drupal-core-require-dev --with-dependencies.

    Running lando drush updb at this point (after the 8.7 upgrade using the backup) performs:

    ------------------- ----------------------------------------------- --------------- --------------------------------------------------------------------------- 
     Module              Update ID                                       Type            Description                                                                  
    ------------------- ----------------------------------------------- --------------- --------------------------------------------------------------------------- 
     system              8701                                            hook_update_n   Remove the unused 'system.theme.data' from state.                            
     system              8702                                            hook_update_n   Add the 'revision_translation_affected' entity key.                          
     comment             8700                                            hook_update_n   Set the 'owner' entity key and update the field.                             
     comment             8701                                            hook_update_n   Make the 'entity_type' and 'field_name' comment fields required.             
     file                8700                                            hook_update_n   Set the 'owner' entity key and update the field.                             
     media               8700                                            hook_update_n   Set the 'owner' entity key and update the field.                             
     node                8700                                            hook_update_n   Set the 'owner' entity key and update the field.                             
     taxonomy            8701                                            hook_update_n   Add an index on the 'taxonomy_term__parent' field table.                     
     comment             add_ip_address_setting                          post-update     Add comment settings.                                                        
     media               enable_standalone_url                           post-update     Keep media items viewable at media{id}.                                      
     menu_link_content   make_menu_link_content_revisionable             post-update     Update custom menu links to be revisionable.                                 
     system              add_expand_all_items_key_in_system_menu_block   post-update     Initialize 'expand_all_items' values to system_menu_block.                   
     system              clear_menu_cache                                post-update     Clear the menu cache.   @see https:www.drupal.orgprojectdrupalissues3044364  
     taxonomy            make_taxonomy_term_revisionable                 post-update     Update taxonomy terms to be revisionable.                                    
     taxonomy            remove_hierarchy_from_vocabularies              post-update     Remove the 'hierarchy' property from vocabularies.                           
     views               exposed_filter_blocks_label_display             post-update     Update exposed filter blocks label display to be disabled.                   
     views               make_placeholders_translatable                  post-update     Rebuild cache to allow placeholder texts to be translatable.                 
    ------------------- ----------------------------------------------- --------------- --------------------------------------------------------------------------- 
    

    This completes successfully, and there are no pending entity updates, but the error remains for anonymous users.

    Thank you for the help!

  • ๐Ÿ‡จ๐Ÿ‡ฆCanada Newb_Druper

    I am also having the same issue as @jimafisk. I just wanted to mention it.

    I am upgrading from 8.6.16 to 8.7.x and all seems fine with no errors, except for anonymous users get an error below

    The website encountered an unexpected error. Please try again later.Drupal\Component\Plugin\Exception\ContextException: The 'entity:user' context is required and not present.

    I am also getting strange tables similar to @jimafisk that are created in my database after the update to 8.7.x

    `old_73377etaxonomy_term__field_category_columns`
    `old_73377etaxonomy_term__field_category_layout`
    `old_73377etaxonomy_term__field_taxonomy_color`
    `old_73377etaxonomy_term__parent`
    `old_73377etaxonomy_term_data`
    `old_73377etaxonomy_term_field_data`
    `old_ee6aa4menu_link_content`
    `old_ee6aa4menu_link_content_data`

    I think I have to look deeper at all my rows in my taxonomy tables before the upgrade to 8.7.x to see if there is something out of the ordinary.

  • ๐Ÿ‡ณ๐Ÿ‡ฑNetherlands tomdewild

    We've had the same problem as @jimafisk and @Newb_Druper with one of our sites. After debugging some time we found out that User 0 was missing in the database and this caused the problem.

    Created a small update hook to fix the problem:

    /**
     * Added user 0, otherwise Drupal throws an error.
     */
    function hook_update_N() {
      $insert = \Drupal::database()->insert('users')->fields([
        'uid' => 0,
        'uuid' => '2d62a7d8-b5b6-43b2-b513-fa7b3396ec44',
        'langcode' => 'en',
      ]);
    
      $insert->execute();
    }

    Hopefully this will also solve your problems.

  • ๐Ÿ‡บ๐Ÿ‡ธUnited States jimafisk

    Thanks so much @tomdewild!! Your answer in #6 seems to have fixed our issue!

    I swapped out the UUID you listed for the one found in config/default/user.role.anonymous.yml.

  • ๐Ÿ‡จ๐Ÿ‡ฆCanada Newb_Druper

    That worked as well for me. Thanks @tomdewild

    I also made sure to use my own UUID as mentioned by @jimafisk

  • ๐Ÿ‡ฌ๐Ÿ‡งUnited Kingdom catch

    Updated the issue summary. Switching this to a major task, we can't actually fix the issue in core, but we can provide a status report message that informs site admins of the problem.

  • Drupal 8.7.9 โ†’ was released on November 6 and is the final full bugfix release for the Drupal 8.7.x series. Drupal 8.7.x will not receive any further development aside from security fixes. Sites should prepare to update to 8.8.0 on December 4, 2019. ( Drupal 8.8.0-beta1 โ†’ is available for testing.)

    Bug reports should be targeted against the 8.8.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.9.x-dev branch. For more information see the Drupal 8 and 9 minor version schedule โ†’ and the Allowed changes during the Drupal 8 and 9 release cycles โ†’ .

  • ๐Ÿ‡จ๐Ÿ‡ญSwitzerland Berdir Switzerland

    > I swapped out the UUID you listed for the one found in config/default/user.role.anonymous.yml.

    one is the UUID for the role, the other for the user, there's no reason to and you shouldn't reuse it like that.

  • Drupal 8 is end-of-life as of November 17, 2021 โ†’ . There will not be further changes made to Drupal 8. Bugfixes are now made to the 9.3.x and higher branches only. For more information see the Drupal core minor version schedule โ†’ and the Allowed changes during the Drupal core release cycle โ†’ .

  • Drupal 8.8.7 โ†’ was released on June 3, 2020 and is the final full bugfix release for the Drupal 8.8.x series. Drupal 8.8.x will not receive any further development aside from security fixes. Sites should prepare to update to Drupal 8.9.0 โ†’ or Drupal 9.0.0 โ†’ for ongoing support.

    Bug reports should be targeted against the 8.9.x-dev branch from now on, and new development or disruptive changes should be targeted against the 9.1.x-dev branch. For more information see the Drupal 8 and 9 minor version schedule โ†’ and the Allowed changes during the Drupal 8 and 9 release cycles โ†’ .

  • @Berdir

    "one is the UUID for the role, the other for the user, there's no reason to and you shouldn't reuse it like that."

    I also, after updating from 8.6.1 to 8.8.6, had same issue and seem to have fixed it by creating the user 0 row in the DB with :

    INSERT INTO users (uid, langcode, uuid) VALUES (0, "en", "");

    No error now but the user 0 has no uuid. Is it safe to leave it without a uuid ? and if not then how to create one ?

    Another weird observation, I checked the DB of the original Drupal 8.6.1 and found it missing the user 0 too but doesn't have the error of this OP !

    Thanks

  • ๐Ÿ‡ณ๐Ÿ‡ฟNew Zealand quietone New Zealand

    Is anyone still experiencing this problem?

  • Drupal 9.3.15 โ†’ was released on June 1st, 2022 and is the final full bugfix release for the Drupal 9.3.x series. Drupal 9.3.x will not receive any further development aside from security fixes. Drupal 9 bug reports should be targeted for the 9.4.x-dev branch from now on, and new development or disruptive changes should be targeted for the 9.5.x-dev branch. For more information see the Drupal core minor version schedule โ†’ and the Allowed changes during the Drupal core release cycle โ†’ .

  • ๐Ÿ‡ณ๐Ÿ‡ฟNew Zealand quietone New Zealand

    Add tag,

  • Drupal 9.4.9 โ†’ was released on December 7, 2022 and is the final full bugfix release for the Drupal 9.4.x series. Drupal 9.4.x will not receive any further development aside from security fixes. Drupal 9 bug reports should be targeted for the 9.5.x-dev branch from now on, and new development or disruptive changes should be targeted for the 10.1.x-dev branch. For more information see the Drupal core minor version schedule โ†’ and the Allowed changes during the Drupal core release cycle โ†’ .

  • ๐Ÿ‡ณ๐Ÿ‡ฟNew Zealand quietone New Zealand

    Sorry, folks I somehow missed catch's comment, #9. This is really a task.

  • ๐Ÿ‡ณ๐Ÿ‡ฟNew Zealand quietone New Zealand
  • Merge request !5466add check for anonymous user โ†’ (Open) created by quietone
  • Status changed to Needs review 3 months ago
  • ๐Ÿ‡ณ๐Ÿ‡ฟNew Zealand quietone New Zealand

    The test failure is

       1)
        Drupal\Tests\settings_tray\FunctionalJavascript\SettingsTrayBlockFormTest::testBlocks
        WebDriver\Exception\CurlExec: Curl error thrown for http POST to

    suspected cause is ๐Ÿ“Œ Stabilize FunctionalJavascript testing AJAX: add ::assertExpectedAjaxRequest() Fixed .

    Since that is unrelated I am setting to needs review.

  • Status changed to RTBC 3 months ago
  • ๐Ÿ‡บ๐Ÿ‡ธUnited States smustgrave

    Updated the title a bit to easily see what's being added

    Verified the user requirement with an anonymous user and without (manually deleted). Attached screenshots to issue summary.

  • Status changed to Needs work 3 months ago
  • ๐Ÿ‡ง๐Ÿ‡ชBelgium kristiaanvandeneynde Antwerp, Belgium

    Looks good to me.

    Found one nitpick and think we should test this as it's a big issue if you run into it and we want to make sure that user_requirements() does its job properly. The test could be as simple as:

    Case 1:

    1. Log in
    2. Visit /admin/reports/status
    3. Assert session containing text about everything being fine

    Case 2:

    1. Log in
    2. Delete user 0
    3. Visit /admin/reports/status
    4. Assert session containing text about missing user
  • Status changed to Needs review 3 months ago
  • ๐Ÿ‡ณ๐Ÿ‡ฟNew Zealand quietone New Zealand

    @kristiaanvandeneynde, thanks for the review. I have updated the MR accordingly.

    Unrelated test failure

      1)
        Drupal\Tests\settings_tray\FunctionalJavascript\SettingsTrayBlockFormTest::testBlocks
        Failed asserting that a NULL is not empty.
  • Status changed to Needs work 3 months ago
  • ๐Ÿ‡ฆ๐Ÿ‡บAustralia dpi Perth, Australia

    Small thing.

    I'd prefer ternary for description and severity rather than the giant if/else but not gonna hold up on that. Defer to author.

  • Status changed to RTBC 3 months ago
  • ๐Ÿ‡ง๐Ÿ‡ชBelgium kristiaanvandeneynde Antwerp, Belgium

    LGTM.

    I don't want to hold up this issue over personal taste between empty($result) and count($result) === 0 even though I prefer the former. Thanks for adding the test and addressing the minor nitpicks.

    Test fail indeed seems unrelated, please run that single pipeline again. For some reason that button and the resolve thread button are missing for me from this MR.

  • Pipeline finished with Failed
    3 months ago
    Total: 155s
    #54266
  • Status changed to Needs review 3 months ago
  • ๐Ÿ‡ง๐Ÿ‡ชBelgium kristiaanvandeneynde Antwerp, Belgium

    Pushed some code style changes rather than adding nitpicks and requiring others to do so:

    1. We should do a strict check vs the phase
    2. We should use a count query if we are interested in a count rather than fetch a column and run count on that in PHP.
    3. We could get rid of the else statement here as it's at the end of the function

    I would leave it at RTBC as the test that was added still goes green and these are merely nitpicks. However, now that I wrote code myself, I shouldn't RTBC it myself as prescribed in the governance docs. Please RTBC if you agree with my cleanup.

    FWIW, this is ready to go in for me now so will pass on to a committer once set back to RTBC.

  • Status changed to Needs work 3 months ago
  • ๐Ÿ‡ธ๐Ÿ‡ฐSlovakia poker10

    I have reviewed the MR and added some minor comments.

    There also seems to be a codestyle issues after changing the requirements array, see: https://git.drupalcode.org/issue/drupal-3057399/-/jobs/383838

    Thanks!

  • Status changed to Needs review 3 months ago
  • ๐Ÿ‡ง๐Ÿ‡ชBelgium kristiaanvandeneynde Antwerp, Belgium

    Good review, I missed that documentation copy/paste.

  • Pipeline finished with Failed
    3 months ago
    Total: 122s
    #54325
  • Pipeline finished with Success
    3 months ago
    Total: 219572s
    #54326
  • Status changed to RTBC 3 months ago
  • ๐Ÿ‡บ๐Ÿ‡ธUnited States smustgrave

    Believe all feedback has been added

    Also ran test-only feature

    1) Drupal\Tests\user\Functional\UserRequirementsTest::testAnonymousUser
    Behat\Mink\Exception\ResponseTextException: The text "The anonymous user exists." was not found anywhere in the text of the current page.
    /builds/issue/drupal-3057399/vendor/behat/mink/src/WebAssert.php:811
    /builds/issue/drupal-3057399/vendor/behat/mink/src/WebAssert.php:262
    /builds/issue/drupal-3057399/core/modules/user/tests/src/Functional/UserRequirementsTest.php:27
    /builds/issue/drupal-3057399/vendor/phpunit/phpunit/src/Framework/TestResult.php:728
    ERRORS!
    Tests: 1, Assertions: 5, Errors: 1
    
  • Status changed to Needs work 2 months ago
  • ๐Ÿ‡ฌ๐Ÿ‡งUnited Kingdom catch

    The count query doesn't look right to me, we usually use a range query to check for existence, counts are for counting things.

    Also the docs page should be updated to not talk about Drupal 6 any more. https://www.drupal.org/node/1029506 โ†’

  • ๐Ÿ‡ฎ๐Ÿ‡ณIndia Akhil Babu Chengannur

    Akhil Babu โ†’ made their first commit to this issueโ€™s fork.

  • Pipeline finished with Failed
    about 2 months ago
    Total: 570s
    #69094
  • Pipeline finished with Canceled
    about 2 months ago
    Total: 27s
    #69098
  • Status changed to Needs review about 2 months ago
  • ๐Ÿ‡ฎ๐Ÿ‡ณIndia Akhil Babu Chengannur

    I have replaced countQuery() with range(0, 1) as per the review comment #33. Please review

  • Pipeline finished with Success
    about 2 months ago
    Total: 523s
    #69099
  • Status changed to Needs work about 2 months ago
  • ๐Ÿ‡บ๐Ÿ‡ธUnited States smustgrave

    1 small nitpicky item.

  • Pipeline finished with Canceled
    about 2 months ago
    Total: 3s
    #69377
  • Pipeline finished with Success
    about 2 months ago
    Total: 504s
    #69378
  • ๐Ÿ‡ฎ๐Ÿ‡ณIndia Akhil Babu Chengannur

    Added void typehint.

  • Status changed to Needs review about 2 months ago
  • ๐Ÿ‡ฎ๐Ÿ‡ณIndia Akhil Babu Chengannur
  • Status changed to RTBC about 2 months ago
  • ๐Ÿ‡บ๐Ÿ‡ธUnited States smustgrave

    Feedback has been addressed.

  • Status changed to Needs review about 2 months ago
  • ๐Ÿ‡ณ๐Ÿ‡ฟNew Zealand quietone New Zealand

    I made some changes that require another review.

  • Status changed to RTBC about 2 months ago
  • ๐Ÿ‡บ๐Ÿ‡ธUnited States smustgrave

    Testing the changes believe the changes are good.

  • Status changed to Needs review 21 days ago
  • ๐Ÿ‡ฌ๐Ÿ‡งUnited Kingdom longwave UK

    Added a question to the MR. Unsure if we have a policy for things that belong in the status report.

  • ๐Ÿ‡บ๐Ÿ‡ธUnited States smustgrave

    If we remove that bit to a follow up could the rest make it?

  • ๐Ÿ‡ง๐Ÿ‡ชBelgium kristiaanvandeneynde Antwerp, Belgium

    That would be acceptable to me. We shouldn't hold up this issue over a policy discussion about what to do when nothing is wrong.

  • Status changed to Needs work 18 days ago
  • ๐Ÿ‡ฌ๐Ÿ‡งUnited Kingdom longwave UK

    Yeah the rest of it is fine, I just don't want to clutter the status report with useless messages, as I feel there are already enough of them.

  • Pipeline finished with Success
    17 days ago
    Total: 509s
    #90267
  • Status changed to Needs review 17 days ago
  • ๐Ÿ‡ณ๐Ÿ‡ฟNew Zealand quietone New Zealand

    I made the change suggested in the MR. Since that changed logic, I made a new screenshot, just to be sure.

  • Status changed to Needs work 17 days ago
  • ๐Ÿ‡ธ๐Ÿ‡ฐSlovakia poker10

    Added one comment to the MR about comment wording.

    Also, the IS states:

    check that there's a record for user 0 and warn the site administrator if not.

    However, we use REQUIREMENT_ERROR instead of REQUIREMENT_WARNING in the code. Do we need to update the IS, or change the code to use REQUIREMENT_WARNING?

    Thanks!

  • Status changed to Needs review 16 days ago
  • ๐Ÿ‡ณ๐Ÿ‡ฟNew Zealand quietone New Zealand

    Oops, yes the IS does say warning. I have made that change, made another screenshot and updated the IS.

  • Status changed to RTBC 13 days ago
  • ๐Ÿ‡บ๐Ÿ‡ธUnited States smustgrave

    Seems the extra bit discussed in #42-45 has been removed.

Production build https://api.contrib.social 0.61.6-2-g546bc20