DEV Community

ErasmusPierce7981
ErasmusPierce7981

Posted on

Account Erasure: Enforcing Refresh Rotation With Sliding and Absolute Expiry

Gate the provider migration on one operational test: refresh token rotation must enforce sliding session expiry and an absolute cap while account erasure prevents renewal through either identity system, including during a request already in flight. A successful deletion response alone doesn't establish that property.

TL;DR: For a Node.js application using Express, keep refresh-token rotation, sliding expiry, and the absolute session deadline in authoritative server-side state. Atomically consume each refresh token and issue its successor, setting the new idle deadline to the earlier of now plus the idle window and the original absolute deadline. Account deletion must serialize against renewal and make every session unusable. The implementation below expresses that transaction contract in Go; the same contract belongs behind the Express refresh handler.

For a B2B SaaS team moving off a managed identity provider, this is an erasure-readiness runbook. Its acceptance criterion is deliberately narrower than GDPR compliance: stop authenticated use and credential renewal while the separate data-erasure workflow handles records, retention requirements, and applicable exceptions. Article 17 defines the right to erasure and its exceptions; revoking credentials does not, by itself, satisfy it.

What can renew after the account has been deleted?

Start with the dangerous interleaving. A renewal request reads an active account, the deletion transaction revokes its sessions, and then renewal writes a fresh credential using the account state it read earlier. Every individual operation can report success while the combined result violates the deletion invariant. Moving the account check into middleware doesn't close that race, because a check outside the transaction cannot protect a later write.

Serialize those operations.

The account record is the common serialization point: renewal and deletion must acquire the same account lock, or use an equivalent serializable transaction with retries, before deciding whether a credential can remain valid. Renewal also locks its token-family state. Deletion first marks the account inactive and revokes its sessions within that ordering; asynchronous cleanup can follow after the denial state is durable. Keep the lock order consistent across both paths.

The old provider matters here. A local session database cannot revoke a credential that an application still accepts independently from the previous issuer. Before cutover, inventory every authentication entry point, including background API calls and services that validate access tokens locally, and establish which authority can deny each one. OAuth token revocation is a defined mechanism in RFC 7009, but support for that endpoint is not evidence that all resource servers observe deletion immediately. Measure the enforcement path you actually deploy.

A signed access token can remain cryptographically valid after its refresh family has been revoked. If the service promises immediate denial, its authorization path needs current account or session status, with a documented policy for unavailable status checks. Otherwise, the promised bound must include the remaining access-token lifetime and any cached authorization state. A short access-token lifetime reduces that bound; it does not make it zero.

How should refresh token rotation enforce sliding session expiry and an absolute cap?

Use an idle window to bound inactivity and an absolute deadline to bound the lifetime of the authenticated session even under continuous use. OWASP's Session Management Cheat Sheet distinguishes these timeout controls. RFC 9700 describes refresh-token rotation as a replay-detection mechanism: a refresh yields a replacement token, the previous one becomes invalid, and retained relationship information lets the server detect reuse. Neither mechanism substitutes for the other.

For an illustrative policy, choose a 30-minute idle window and an 8-hour absolute lifetime. These are example inputs, not measured recommendations. A successful refresh at elapsed hour 7 and minute 50 grants at most 10 more minutes. It cannot reset the session's original 8-hour deadline. At either deadline, require authentication again.

The following Go policy function is intentionally independent of HTTP and storage. Its caller must authenticate the presented refresh secret, load these records under the shared transaction locks, and persist either successor issuance or family revocation before responding. The function does not implement that transaction, token generation, hashing, or cookie handling. Its return value makes the required storage action explicit.

package sessionpolicy

import "time"

type Action uint8

const (
    Deny Action = iota
    RevokeFamily
    Rotate
)

type State struct {
    AccountActive bool
    FamilyRevoked bool
    PresentedUsed bool
    IdleUntil     time.Time
    AbsoluteUntil time.Time
}

func Decide(now time.Time, idleWindow time.Duration, s State) (Action, time.Time) {
    if !s.AccountActive || s.FamilyRevoked {
        return Deny, time.Time{}
    }
    if s.PresentedUsed {
        return RevokeFamily, time.Time{}
    }
    if idleWindow <= 0 || !now.Before(s.IdleUntil) || !now.Before(s.AbsoluteUntil) {
        return Deny, time.Time{}
    }
    next := now.Add(idleWindow)
    if next.After(s.AbsoluteUntil) {
        next = s.AbsoluteUntil
    }
    return Rotate, next
}
Enter fullscreen mode Exit fullscreen mode

The storage contract carries most of the security burden. Keep the absolute deadline immutable for the session, store a verifier rather than a plaintext refresh secret, and retain enough consumed-token information to associate an authenticated replay with its family. A random unknown token is a denial, not permission to revoke an arbitrary family. On Rotate, consume the presented token and insert its successor in the same transaction; on RevokeFamily, commit the revocation even though the HTTP request will be rejected. A generic error handler that rolls back every unsuccessful request would silently undo replay containment.

That is an expensive mistake.

Only return a successor after commit. If the commit succeeds but the response is lost, retrying the consumed token can trigger replay handling. Decide explicitly how the client coordinates refreshes and recovers from ambiguous responses, rather than allowing two browser tabs to renew the same credential concurrently and hoping their timing is favorable. A strict reuse policy favors containment over transparent retries; any retry-tolerance design needs its own threat model and atomic implementation.

For the Express boundary, keep the refresh handler thin: validate the request, invoke the transactional service, and set the replacement credential only after the service confirms commit. For browser cookies, apply Secure, HttpOnly, and an appropriate SameSite policy, and address CSRF for cookie-authenticated requests. These controls protect transport and browser behavior; they cannot repair a renewal transaction that races with erasure.

Make the migration decision against the deletion SLO

A buy-versus-build discussion becomes useful when it names the work transferred to the on-call team. The trade-off is operational ownership: self-operation is not suitable for a team that cannot maintain transaction isolation, credential protection, and recovery procedures. Keeping a managed boundary still requires verification of its deletion semantics. The comparison below describes responsibilities to verify, not guarantees about any product.

Decision Managed identity boundary Application-operated authority
Renewal and replay Verify rotation semantics and observable revocation behavior Own atomic token consumption, family history, and replay containment
Account erasure Coordinate provider deletion with application denial state Coordinate account locks, session revocation, and downstream cleanup
Availability Include external calls and provider failures in the SLO model Include database contention, replication, and recovery in the SLO model
Exit readiness Establish how old credentials stop working at cutover Maintain a tested denial path for every accepted issuer

Define a deletion-enforcement SLO before choosing the boundary. Measure the interval from durable acceptance of the deletion request to denial at each protected service. Keep the asynchronous data-erasure completion objective separate, because its dependencies and legal retention decisions differ. If caches participate in authorization, their invalidation and maximum staleness belong in the enforcement budget.

Capacity planning starts at the transaction rate, not at registered-account count. Every successful refresh writes state; replay detection needs retained history; erasing an account with many sessions can concentrate work on one account lock. Estimate refresh demand from active sessions and the client's actual renewal cadence, then load-test that estimate with concurrent erasures. Expanding storage history improves replay attribution but consumes space and complicates retention policy. Account for both before treating self-operation as a smaller bill.

Useful signals include renewal latency, account-lock wait time, rejected renewals by reason, replay-triggered family revocations, and age of the oldest pending erasure job. Never log refresh secrets. Keep account identifiers out of high-cardinality metric labels; use access-controlled audit records when investigations need correlation. An apparently healthy refresh success rate can conceal a deletion path that is falling behind.

Verify denial before widening traffic, and preserve it during rollback

Exercise the policy boundaries with a controlled clock: just before the idle deadline, exactly at it, near the absolute cap, and exactly at the cap. Check that repeated successful renewal never moves the absolute deadline. These are deterministic acceptance tests, not a performance benchmark.

Then test the database, because a passing policy function cannot demonstrate transaction isolation. Race two requests carrying the same token and verify that at most one successor is committed; under the strict policy described here, an authenticated replay revokes the family. Race refresh against deletion in both orderings. If refresh commits first, deletion must revoke its successor. If deletion commits first, refresh must fail. Also inject a lost response after commit and confirm the client takes the intended recovery path.

Deploy with a limited cohort only after those checks pass, and inspect enforcement latency at every resource server, including any path still accepting the previous issuer. The erasure workflow should be idempotent so retries preserve the denial state while cleanup progresses. Do not report full data erasure merely because credential revocation has finished.

Rollback must preserve revocations.

Reverting an application release must not restore deleted accounts, unconsume refresh tokens, or re-enable the previous issuer for accounts already denied. Keep the denial records compatible with the rollback release and rehearse that release against accounts erased during the migration. If the old authentication path cannot observe those records, restoring it is incompatible with the deletion guarantee; retain the enforcement boundary while correcting the rollout.

The cutover is ready when the team can demonstrate bounded renewal, denial across every accepted credential path, and rollback that preserves erasure state. Those are observable conditions a platform team can own, regardless of who operates the identity service.

References

Top comments (0)