DEV Community

UlyssesDonovan1529
UlyssesDonovan1529

Posted on

Social Identity Linking in 2026: Prevent Duplicates That Escape Session Revocation

A deletion request changes the linking decision. In a B2B SaaS application, a social sign-in must resolve to the same internal account, or deletion can leave another credential outside the session revocation boundary. Short answer: resolve the verified social identity before creating a user, and require proof of control of the existing account before attaching a new credential.

For a team migrating off managed authentication, the acceptance criterion should be concrete: once deletion takes effect, no linked identity may restore access beyond the documented revocation window. This is a proposed evaluation constraint, not a measured result. Session revocation alone also doesn't establish that a GDPR erasure request is complete.

The short implementation—look up an email, create a user if absent, then issue a session—puts too much authority in the lookup. An email match is not sufficient proof that the caller may modify an existing account. Creating users before resolving credential ownership also gives concurrent requests a chance to create duplicates. Put ownership resolution before that write.

Keep deletion sticky.

What must resolve before a social identity can be linked?

Separate two intents: signing in with an existing identity and adding a credential to an authenticated account. Sign-in resolves an identity to its owner. Linking requires authorization to modify that owner as well as proof of the external identity.

Use a stable internal account identifier as the deletion boundary. In this proposed schema, a unique pair of authority and subject identifies an external credential, and its mapping points to one internal account. These values must come from the verified authentication boundary. A browser-supplied subject string is not evidence of identity.

Treat email as a contact or discovery attribute. If someone arrives through an unknown social identity with an email matching an existing account, ask them to authenticate to that account before linking. This introduces friction, but it avoids turning a contact-field match into permission to attach a login credential. OWASP's Authentication Cheat Sheet recommends reauthentication for sensitive operations; applying that principle to linking and deletion makes the authorization boundary explicit.

During migration, an absent mapping should trigger investigation or a deliberate registration decision. It should not silently establish that a person is new. Otherwise, an incomplete import can become a duplicate account.

A Python example for the ownership decision

The reader's Node.js implementation question concerns callback ordering. The same ordering can be evaluated in Python before integrating it into an application: verify the social response, establish the target account through an authenticated session, authorize linking, and then enter the transaction below. Those checks belong on the server.

This example is a repository contract, not a complete authentication implementation.

from dataclasses import dataclass
from typing import Protocol


@dataclass(frozen=True)
class VerifiedIdentity:
    authority: str
    subject: str


@dataclass(frozen=True)
class Account:
    id: str
    state: str


class Transaction(Protocol):
    async def lock_account(self, account_id: str) -> Account: ...
    async def identity_owner(
        self, authority: str, subject: str
    ) -> str | None: ...
    async def insert_identity(
        self, authority: str, subject: str, account_id: str
    ) -> None: ...


class LinkRejected(Exception):
    pass


async def link_identity(
    tx: Transaction,
    account_id: str,
    identity: VerifiedIdentity,
) -> str:
    account = await tx.lock_account(account_id)
    if account.state != "active":
        raise LinkRejected("Account is unavailable for linking")

    owner = await tx.identity_owner(
        identity.authority, identity.subject
    )
    if owner == account.id:
        return account.id
    if owner is not None:
        raise LinkRejected("Credential is already linked")

    await tx.insert_identity(
        identity.authority, identity.subject, account.id
    )
    return account.id
Enter fullscreen mode Exit fullscreen mode

Run the function inside one database transaction and commit before reporting success. Enforce database uniqueness on the authority-and-subject pair. Two accounts can both observe an absent mapping; locking their separate account rows cannot serialize that race. A uniqueness conflict must roll back. Resolve the committed owner in a fresh transaction, accepting the same owner as an idempotent result and rejecting a different owner.

Never convert that conflict into permission to issue a session.

For a synthetic fixture, let acct_17 own ("social.example", "subject_42"). Repeating the link for acct_17 leaves one mapping. Attempting it for acct_29 rejects the link. If acct_17 is deleting, even the repeat is rejected because account state is checked first. These are expected outcomes for the example, not production observations.

The function returns an account identifier. Session issuance remains a separate operation with its own current-state check. That separation keeps a successful link from accidentally becoming a bypass around deletion.

Make deletion govern both session paths

A correct mapping gives deletion a target. Revocation still needs enforcement.

For database-backed sessions, one proposed design makes deletion and session issuance lock the same account row. Deletion marks the account unavailable and invalidates its sessions in a transaction. Issuance checks that state before creating a session. The example's account lock only contributes to this guarantee if the deletion path follows the same discipline. Document the complete transaction boundary; a lock in one callback is insufficient.

A self-contained credential needs a different question: how does a protected resource learn that access has been revoked? Changing an account row cannot affect a validation decision that never consults current state. Choose an enforcement mechanism, such as checking an account revocation record, and include caching in its documented validity window. Measure rejection at the resource, not merely success from the deletion endpoint.

There is a trade-off. Consulting current state adds a dependency to protected requests, while caching can delay enforcement. Decide the required revocation window first, then measure latency and availability against it.

During migration overlap, both old and new authentication paths must honor the same deletion boundary. Import identity mappings before enabling the replacement sign-in path. A rollback should restore routing without restoring access for an unavailable account. Test rollback explicitly; a successful forward migration says little about old credentials.

Take the evaluation harness from notebook to production

A single successful callback is easy to demonstrate. The interesting result is whether ownership and deletion survive retries, partial failures, and concurrency. Start with synthetic fixtures and six expected outcomes:

  1. Repeating a link for the same account leaves exactly one mapping.
  2. Linking another account's credential rejects the change without moving ownership.
  3. Concurrent links from different accounts produce one owner.
  4. Deletion racing with session issuance respects the revocation deadline.
  5. Replaying an old callback after deletion cannot recreate an active account.
  6. Rolling routing back cannot restore access through an old session.

For the fourth case, pause issuance after its initial read, commit deletion, and resume issuance. Reverse the ordering too. Assert the final authorization result at the protected resource. This is where the eval becomes useful: it checks the security outcome across boundaries, rather than repeating the implementation's own assertions.

A timeout is not a missing identity. Keep dependency errors distinct from lookup misses, and test a lost response after commit so a retry cannot create another account.

For an AI application, keep model calls outside this decision. Use authenticated identifiers and deterministic rules to authorize linking. An assistant can explain account status through an authorized interface, but model-generated similarity between profiles should not establish ownership. Use compact synthetic fixtures in evaluations and keep identity tokens out of prompts. That is a prompt-cost aware choice with a clear benefit: fewer unnecessary model calls and an inspectable authorization decision.

Measure the boundary before adopting the design

Track unresolved identity mappings, rejected ownership changes, uniqueness conflicts, and session attempts against unavailable accounts. Use correlation identifiers to trace deletion operations without putting credentials in logs. OWASP's authentication guidance provides a starting point for monitoring authentication events and handling sensitive authentication data.

Measure elapsed time from the committed deletion transition to rejection on every session acceptance path. Include paths still active during migration. Define the starting event precisely; a duration measured from a later cleanup job excludes part of the operation.

Then inventory the wider erasure work: application records, derived retrieval content, background jobs, and retained data each need a handling decision. Revocation proves an access-control result. A GDPR erasure claim requires examining the wider data lifecycle and applicable obligations.

Before moving off managed authentication, measure the work the team will own: maintaining mappings, operating revocation checks, testing races, and diagnosing incomplete deletion. Keep those responsibilities beside latency and evaluation coverage in the decision. The notebook-to-prod gate is specific: every linked credential must respect the same deletion boundary through retries, concurrency, and rollback.

References

The authentication controls and reauthentication guidance cited above come from the following public reference. The transaction design and fixtures are proposed engineering choices to evaluate against that guidance.

Sources

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

Your six-case harness is the strongest part of this post — especially case 4, deletion racing with session issuance, and case 5, replaying an old callback after deletion. Most posts stop at 'revoke the session,' and yours correctly points out that revocation alone does not establish that a GDPR erasure request is complete. The gap I would push on is the self-contained credential one you name but leave open: if the protected resource cannot consult current state, how does it learn that acct_17 is deleting in time? Short-lived tokens with a tight revocation window seem like the only honest answer there, but that trades away the point of a self-contained credential. What deadline would you actually measure for that case — elapsed time from the committed deletion transition to rejection on every session acceptance path?