Unable to link anonymous user to email/password user. Invalid session error

I tried to follow the iOS guide to link an anonymous user to the newly created with email and password https://docs.mongodb.com/realm/sdk/ios/advanced-guides/link-user-identities/

The first time it failed with an error AuthError Error - confirmation required. It was descriptive enough so I just go through the confirmation flow first.

The second time it failed with an error InvalidSession Error - invalid session. I thought it might be because the user is in the Pending User Login state so I decided to proceed with login.

The third time it failed with the same error InvalidSession Error - invalid session when I tried to log in as anon, then login as email/password and link after that.

I also tried to link with anon credentials after i log in with email/password. It reports success but it doesn’t link anything it just switches to anonymous account and after I log in next time with email/password the anon data is not preserved.

I also checked user.identities[].providerType. There is always just one. It’s local-userpass after email/password login or anon-user after anon login/link.

When I try to login with anon and then link with an existing and not pending email/password account it reports InvalidSession Error - a user already exists with the specified provider

When I try to link to non-existing email/password user it reports InvalidPassword Error - invalid username/password

I tried to delete the user and create it again. It worked when I tried to link the first time only after the user was confirmed. I can’t be sure what was the root cause but more likely the consequence of my actions. I tried to link accounts before the user was confirmed via the email link.

Even though it worked in the end the app might not know the exact moment the user was confirmed (the confirmation might be done on the web also) so even if I try to link users just before the first login it might fail and go into a failed state.