How to switch account during Entity Synchronization operations

Body

It is common for Entity Synchronization imports to be regularly run via cron e.g. regularly fetch the list recently created or updated records from a remote system and import them as Drupal entities. When new entities are created, they would normally have the anonymous user as their creator because cron runs as the anonymous user. That might not be desirable; at the very least it is a potential security concern if permissions are not carefully configured.

For that reason, it is better that the entities are created by another user e.g. the root user. Here's how:

# entity_sync.operation_type.my_import.yml
# Only relevant properties are shown.
operations:
  import_list:
    switch_account:
      status: true
      # Switch to user with ID 1.
      to_id: 1
      # Only switch if the user is the anonymous user i.e. cron.
      allowed_from_ids:
        - 0

The above configuration will instruct Entity Synchronization to switch to the user with ID 1 before the operation initiates. That will result in all new entities to be created by the root user. Did you notice the property allowed_from_ids? Imports can also be run via the Sync UI, manually, by a specific user. In that case we might  want to keep the current user as the creator of the entity, either so that the user has the correct permissions or for auditing purposes i.e. who imported the entity. Setting the allowed_from_ids property to 0 will instruct Entity Synchronization to only apply the switch if the current user is the anonymous user.

Note that this feature is not merged in the main development branches nor released yet. This is because some further work is required for implementing - always or optionally - switching back to the previous user after the operation terminates. You will therefore need to add the code available in the merge requests related to this issue - test carefully before using on production!