Token State Drift Between CI Runs and How to Lock Your Auth Simulator to a Known Starting Grant

Reset your auth simulator to a versioned grant before every run.

· 8 min read · Updated
Cover illustration for “Token State Drift Between CI Runs and How to Lock Your Auth Simulator to a Known Starting Grant”
Auth Flow Testing · November 2, 2026 · 8 min read · 1,836 words

Integration testing against stateful APIs requires a simulator that preserves state within a scenario but resets it before the next run. For auth tests, the starting grant must be an explicit, versioned fixture, reset and verified before every CI invocation. This prevents token state drift from making tests pass on the strength of authorization history alone.

Why token state drift is a stateful problem, not a configuration mistake

An auth simulator remembers which tokens were minted, exchanged, expired, or revoked. That memory makes it useful for testing workflows where order of operations changes the result. It also creates a persistence problem between runs. If nothing resets the auth store, the next invocation begins with the grant state that the previous invocation left behind, even when the application configuration is correct.

A token minted for one principal can coexist with a fresh token issued during the next run. The simulator need not report a conflict. Both entries can be valid within its stored world, while only one belongs to the intended test conditions. The resulting contamination is therefore a structural consequence of uncontrolled state.

The most misleading outcome is a successful test. An elevated-scope grant left over from an earlier run can authorize a call that a clean simulator would refuse. The same mistake appears in a payment mock that returns “captured” before any capture call occurs. In both cases, the test accepts a result without proving that the required transition produced it.

How state accumulates across runs in practice

Grants are left behind when a reset clears application data but leaves the simulator’s auth store untouched. A long-lived or never-expiring token can then become an undeclared dependency of later tests. The reset boundary is incomplete. WorkOS Emulate says that tests should not depend on state left behind by earlier runs and uses a seed file to rebuild the world the test needs. For an in-memory emulator, rebooting without a seed discards history but does not recreate the required starting conditions.

One CI job may mint a token, another may exchange it, and a third may attempt to revoke it against the same simulator instance. The sequence depends on which job runs first. Tests that behave differently alone and in parallel are a characteristic symptom of this shared-state problem. A reset before the jobs start cannot, on its own, handle changes that compete with each other while the jobs run.

Changes to the upstream contract can also make stored state stale, even when the stored bytes stay the same. In its 2025-03-31.basil release, Stripe moved the Checkout Session field shipping_details to collected_information.shipping_details. That is a payload-contract change. It illustrates why reproducing an old fixture does not establish compatibility with the current API. Hard-fail contract tests that check query, body, and WebSocket payloads help guard against this kind of drift.

Kalshi rejects timestamps too far from server time with the same 401 returned for a wrong key. When the CI container clock is frozen or has drifted, signing can fail even if the code is correct. The response does not distinguish the two causes. Unlike a stale scope that permits an invalid success, clock skew can make the intended grant appear unusable.

Why the false-confidence failure mode is worse than an outright breakage

A failing test creates an immediate investigation point. A test that passes against the wrong principal or scope gives no such warning, because the assertion succeeds. When a real token with narrower scope later fails the same call, the divergence becomes visible outside the pipeline that was supposed to catch it.

Repeated execution can deepen that false confidence. More green runs do not strengthen the evidence if each run inherits the same unauthorized assumption. WorkOS identifies accumulating state between runs as a drawback of testing against its live API and recommends seeded emulator state instead. Its in-memory design makes rebooting with a seed file the deliberate reset primitive.

Vendor sandboxes offer separation from production, but separation is not deterministic initialization. Stripe sandbox payments do not go through real card networks, PayPal sandbox test values do not work in production, and Apple’s sandbox returns transactions as if payments had succeeded, though it does not process actual payments. These are partial environments with their own behavior. Stripe supports up to five isolated sandboxes and direct webhook event triggering through its CLI, but those capabilities do not provide a pipeline-controlled, resettable starting grant.

The principle behind locking to a known starting grant

The remedy is to make authorization state a declared fixture independent of earlier execution. A known starting grant specifies which principals exist, which tokens have been issued, their scopes, and their issue and expiry times. It defines the precondition of the test. Resetting to that specification before every run replaces inherited state with the intended starting state.

This distinction preserves the reason for using a stateful simulator. State should change as the test exercises issuance, exchange, expiry, and revocation. Those transitions are part of the behavior under test. The uncontrolled history between invocations is not. For integration tests where order of operations is significant, the fixture fixes the starting point while the scenario establishes the sequence that follows.

WorkOS provides a reference pattern through its seed file, which declares users, organizations, roles, and permissions. Rebooting the in-memory emulator discards prior state and recreates that declared world. The seed becomes the durable input. This follows the same principle as database fixtures that replace prior inserts with a known test setup. It also tells reviewers which authorization conditions the test assumes, something state left over from earlier runs cannot do.

Concrete patterns for resetting and verifying grant state before a run

The implementation choice depends on what the test needs to exercise. Seed-on-boot recreates mutable simulator state, capture-and-replay removes a network dependency, and contract gates detect disagreement with the provider’s API. These patterns solve different parts of the problem. A reproducible response fixture does not replace an auth reset, while a correctly seeded emulator does not establish that its payloads still match the upstream contract.

WorkOS Emulate is an open-source, in-memory emulator covering authorization, code exchange, sessions, organization selection, and signed webhooks. Its event names and payload shapes are generated from the WorkOS OpenAPI spec. The documented reset pattern is seed-on-boot. For a team using this approach, the lesson is to declare the required users, organizations, roles, and permissions in the seed file, then reboot from that file before the run. Failure injection can then test whether the correct grant is needed, going beyond a check that the happy path completes.

A third-party Kalshi Python SDK provides RecordingTransport and ReplayTransport for capturing fixtures against the real demo API and replaying them in CI without a network dependency. The third-party SDK’s retry defaults allow only GET requests to retry, while POST and DELETE never retry, avoiding duplicate state mutations through those retries. The pattern makes network behavior reproducible, but its value depends on pinning fixtures to the scenario they represent. Replaying the wrong starting conditions would only make the wrong test repeatable.

Contract gates address the separate question of whether the simulator still represents the API. For Stripe webhooks, the recommended pattern is to build signed fixtures for each supported event version and prove that each payload matches the schema declared by event.api_version. Combinations that are unknown or contradict each other are rejected before business logic runs. Where actual behavior must be measured against the live API, the resolution process requires a token with the right scopes before simulated behavior is trusted. Declaration and verification serve different purposes.

For PayPal auth delivery, testing non-2xx handling includes checking that retry behavior does not create duplicate state mutations. That requires a controlled failure scenario. Scenario-flag switching supplies an intentional condition for the test, rather than leaving it dependent on whatever failure or grant state the preceding run produced.

Fault injection as a verification step, not an add-on

A pinned grant tested only under expected conditions establishes a narrow result. It shows that the code accepts the expected authorization state on the happy path. It does not establish correct error handling. Latency, 429s, 503s, and auth failures can expose behavior that a clean run never reaches, so these conditions belong in verification of the known-state setup.

AgentChaos, an August 2026 paper, reported that runtime fault injection into LLM API responses reduced pass@1 by up to 49.66 points across five agent systems and four backbone models. The most damaging failures did not raise errors. AutoGen triggered fewer than half its configured faults and rarely triggered tool call faults because its short call chains often finished before injection occurred. The relevant lesson extends beyond agents. Configuring a fault does not prove that the test encountered it.

For auth integration tests, the practical consequence is to test failure behavior from the same declared authorization preconditions used for successful scenarios. That keeps the grant known when a retry or error path behaves in an unexpected way. The fault is the deliberate difference. WorkOS describes failure injection alongside its seed-file pattern, but each can be used on its own. Error hooks can be registered in the seed file, over HTTP at runtime, or programmatically.

A successful request proves that one path through the authorization logic works. A controlled auth failure tests how the application handles refusal, and a retry scenario tests whether repeated attempts change state in the wrong way. Neither result substitutes for the other. Both are more interpretable when the starting grant is fixed.

How to version the starting grant alongside the code that depends on it

A fixture can eliminate inherited state and still become stale. If it remains frozen while the API changes, it may preserve reproducibility at the cost of relevant coverage. That is a different form of drift. The operational discipline is to keep the grant declaration in the same repository as the tests that depend on it, so changes to auth logic and its required fixture can be reviewed together.

Some fixtures should remain frozen deliberately. A Stripe webhook regression case may need the exact byte layout that once exposed a retry or deduplication failure, even after the provider changes its format. Replacing it silently would discard that coverage. The recommended response is an upstream-drift signal and a second scenario for the new format. A pin preserves history only when its purpose remains explicit.

The Backlot/Brekkylab update workflow provides a concrete model for deliberate baseline changes. The command backlot diff --source slack --update-baseline writes an entry for a deliberate gap and drops a stale one. A note explaining the intentional gap is added by hand during review. The rationale is versioned with the fixture. This separates accepting a known difference from overlooking an unexplained mismatch.

For teams applying this discipline, contract-test or diff signals that show divergence from the live API should block promotion pending review. Fixture changes must be deliberate and visible. In the in-memory seed pattern, updating the seed file changes the durable definition of the starting world, and its git history makes that definition auditable and reversible.

More in Auth Flow Testing