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

Issue fork drupal-3057399

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

robpowell created an issue. See original summary.

catch’s picture

Version: 8.7.2 » 8.7.x-dev
Priority: Normal » Critical

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.

jimafisk’s picture

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!

Newb_Druper’s picture

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.

tomdewild’s picture

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.

jimafisk’s picture

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.

Newb_Druper’s picture

That worked as well for me. Thanks @tomdewild

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

catch’s picture

Title: Update from 8.6.x to 8.7.2, anonymous users get "The 'entity:user' context is required and not present." error » Some sites are missing the anonymous user, exposed by 8.6.x to 8.7.x update
Category: Bug report » Task
Issue summary: View changes
Priority: Critical » Major

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.

berdir’s picture

> 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.

Version: 8.7.x-dev » 8.8.x-dev

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.

cestmoi’s picture

@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

Version: 8.8.x-dev » 8.9.x-dev

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.

Version: 8.9.x-dev » 9.2.x-dev

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.

Version: 9.2.x-dev » 9.3.x-dev
quietone’s picture

Issue summary: View changes
Issue tags: -cache +Bug Smash Initiative

Is anyone still experiencing this problem?

quietone’s picture

Issue summary: View changes
Status: Active » Postponed (maintainer needs more info)
Issue tags: +8.7.0 update

Add tag,

Version: 9.3.x-dev » 9.4.x-dev

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.

quietone’s picture

Issue summary: View changes
Status: Postponed (maintainer needs more info) » Active

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

Version: 9.4.x-dev » 9.5.x-dev

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.

quietone’s picture

Version: 9.5.x-dev » 11.x-dev

quietone’s picture

Status: Active » Needs review

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 #3316274: Stabilize FunctionalJavascript testing AJAX: add ::assertExpectedAjaxRequest().

Since that is unrelated I am setting to needs review.

smustgrave’s picture

Title: Some sites are missing the anonymous user, exposed by 8.6.x to 8.7.x update » Add user_requirements to check for missing anonymous user
Issue summary: View changes
Status: Needs review » Reviewed & tested by the community
StatusFileSize
new46.68 KB
new60.19 KB

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.

kristiaanvandeneynde’s picture

Status: Reviewed & tested by the community » Needs work

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
quietone’s picture

Status: Needs work » Needs review

@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.
dpi’s picture

Status: Needs review » Needs work

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.

kristiaanvandeneynde’s picture

Status: Needs work » Reviewed & tested by the community

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.

kristiaanvandeneynde’s picture

Status: Reviewed & tested by the community » Needs review

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.

poker10’s picture

Status: Needs review » Needs work

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!

kristiaanvandeneynde’s picture

Status: Needs work » Needs review

Good review, I missed that documentation copy/paste.

smustgrave’s picture

Status: Needs review » Reviewed & tested by the community

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
catch’s picture

Status: Reviewed & tested by the community » Needs work

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

Akhil Babu made their first commit to this issue’s fork.

akhil babu’s picture

Status: Needs work » Needs review

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

smustgrave’s picture

Status: Needs review » Needs work

1 small nitpicky item.

akhil babu’s picture

Added void typehint.

akhil babu’s picture

Status: Needs work » Needs review
smustgrave’s picture

Status: Needs review » Reviewed & tested by the community

Feedback has been addressed.

quietone’s picture

Status: Reviewed & tested by the community » Needs review

I made some changes that require another review.

smustgrave’s picture

Status: Needs review » Reviewed & tested by the community

Testing the changes believe the changes are good.

longwave’s picture

Status: Reviewed & tested by the community » Needs review

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

smustgrave’s picture

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

kristiaanvandeneynde’s picture

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.

longwave’s picture

Status: Needs review » Needs work

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.

quietone’s picture

Issue summary: View changes
Status: Needs work » Needs review
StatusFileSize
new17.57 KB

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

poker10’s picture

Status: Needs review » Needs work

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!

quietone’s picture

Issue summary: View changes
Status: Needs work » Needs review
StatusFileSize
new17.6 KB

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

smustgrave’s picture

Status: Needs review » Reviewed & tested by the community

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

needs-review-queue-bot’s picture

Status: Reviewed & tested by the community » Needs work
StatusFileSize
new1.45 KB

The Needs Review Queue Bot tested this issue. It fails the Drupal core commit checks. Therefore, this issue status is now "Needs work".

This does not mean that the patch necessarily needs to be re-rolled or the MR rebased. Read the Issue Summary, the issue tags and the latest discussion here to determine what needs to be done.

Consult the Drupal Contributor Guide to find step-by-step guides for working with issues.

quietone’s picture

Status: Needs work » Reviewed & tested by the community

This just needed declare(strict_types=1); added to the one test here. I did that and a rebase. There were no conflicts, so I am restoring the RTBC.

poker10’s picture

@catch in #33 mentioned we should also update the documentation page (https://www.drupal.org/node/1029506) and remove mentions about D6. I have updated it - feel free to update it further if needed (especially the D10+ part). Also tested the MR manually and the warning is displayed correctly when anonymous user is missing.

+1 to RTBC from me.

alexpott made their first commit to this issue’s fork.

alexpott’s picture

Status: Reviewed & tested by the community » Needs work

I left a comment on the MR to address.

pradhumanjain2311 made their first commit to this issue’s fork.

pradhumanjain2311’s picture

Status: Needs work » Needs review

Applied Entity Query As Requested Please Review.

kristiaanvandeneynde’s picture

Status: Needs review » Reviewed & tested by the community

@pradhumanjain2311 All you did was apply a suggested change verbatim. In that case you can set it back to RTBC :)

  • catch committed b6a4ce3e on 10.3.x
    Issue #3057399 by quietone, Akhil Babu, kristiaanvandeneynde, alexpott,...

  • catch committed 9a6e38c0 on 11.x
    Issue #3057399 by quietone, Akhil Babu, kristiaanvandeneynde, alexpott,...
catch’s picture

Version: 11.x-dev » 10.3.x-dev
Status: Reviewed & tested by the community » Fixed

Committed/pushed to 11.x and cherry-picked to 10.3.x, thanks!

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.