Treating Your Auth Simulator as the Stateful Authority When a Third-Party Identity Provider Owns the Workflow
A stateful auth simulator catches bugs that stateless mocks miss.

Integration testing against stateful APIs requires a simulator that remembers each operation and enforces what can happen next. For OAuth and SSO, that means treating the auth simulator as the stateful authority for codes, tokens, sessions, and users. Seed that authority with an identity world it can use, run full workflows against it in CI, and check that it behaves as the third-party identity provider’s contract says it should.
Why auth workflows break stateless mocks in a way most other API workflows do not
A test passes against a mock, but the same code fails in staging because the real identity provider rejects a reused authorization code or rotates a refresh token. The mock accepted an operation the provider forbids. This is a failure to represent history, because the validity of the next request depends on what the previous request changed.
Auth makes that dependency particularly strict. Unlike a shopping-cart flow, the sequence also has cryptographic constraints, including code ownership, signed claims, and token validity. A plausible-looking token does not establish that its authorization code was issued to this client, remains unexpired, and has not already been consumed. Unit-testing token validation on its own cannot close that gap, because mid-session expiry, group changes, and admin revocation happen over a workflow and cannot be captured in a single response.
What “stateful authority” means when testing auth APIs without hitting production
A stateful authority owns the mutable records and transition rules that auth operations must satisfy to succeed. For an auth simulator, those responsibilities include token issuance, rotation, revocation, and expiry. Responses follow from that state. Redocly’s sandbox requirements analysis distinguishes predefined mock responses from a persistent world that remembers creation, updates, and deletions. Applied to auth, that distinction means a token exchange must change what later exchanges are allowed to do.
The persistent objects include authorization codes, access tokens, refresh tokens, sessions, and users. Codes move from issued to consumed, while users can become locked or have their group memberships changed. Later endpoint calls must see these changes. The simulator therefore needs a connected surface covering discovery, authorization, JWKS, token exchange, and userinfo, with OAuth introspection defined separately by RFC 7662. Those endpoints must derive their behavior from shared state.
That shared authority makes endpoint consistency testable. Once a code is consumed at the token endpoint, a second exchange must fail instead of returning another response with a valid shape. Likewise, introspection must show the token’s status now instead of returning an example unrelated to that token. Hosting does not establish this authority. A local, self-contained simulator can give CI the persistent world it needs without being a provider-hosted sandbox.
Seeding the simulator with a world the auth flow can actually traverse
An empty sandbox cannot support a meaningful login workflow when its users, client registrations, and group memberships do not yet exist. Persistence alone does not make it test-ready. The world must start with the relationships a request needs to pass through authorization, token issuance, and access to protected resources. The seed therefore sets both which workflows the suite can reach and how much setup each test needs.
Registered OAuth clients need their redirect URIs, allowed scopes, and grant types in place. User accounts must cover distinct roles and group memberships. An active, pre-issued refresh token lets a test start at refresh without repeating authorization as setup. A pre-loaded JWKS keypair makes discovery and signing-key responses consistent from the first run. A pre-configured MFA challenge state also allows tests to enter MFA-required paths directly.
The seed needs a reset boundary as well. Otherwise, an open session from one test can change another test’s session-count assertions, even when the simulator behaves correctly in both tests. The practical pattern is to load a version-controlled fixture at startup and let individual tests mutate that world. Teardown or namespace isolation then prevents those mutations from leaking into other tests. The fixture belongs beside the test suite so that the starting identity state is explicit and reproducible.
Modeling the token lifecycle as state transitions, not static fixtures
An authorization code must be consumed after a successful exchange, or expire if its lifetime ends before it is used. A consumed code must fail on replay, making single-use behavior a test assertion. They also expose application code that accidentally exchanges the same code twice, which a fixed token response would accept.
Access tokens must move from active to expired when their lifetime ends, or from active to revoked after an applicable admin or logout action. Refresh tokens must move from active to rotated when a replacement is issued, with the old token invalidated, or from active to revoked. Sessions must move from open to terminated after logout or an admin kill. Each transition changes the next permitted operation. In particular, retaining acceptance of an old refresh token hides the client bug in which a rotated-away credential remains cached.
Time must be controllable within these tests. A simulator-controlled or configurable clock allows expiry during a request or session without sleeps that slow CI and make results nondeterministic. Mocking the JWT validator tests how it reacts to an expired token, but does not show whether the application’s refresh path runs before validation. Hand-maintained transition rules introduce another risk, because they can silently diverge from the provider’s behavior. Without contract verification, that mismatch may go unseen until production.
Running the full OAuth redirect loop in CI without touching the real IdP
The full loop begins with an authorization request to the simulator’s /authorize endpoint containing the client ID, redirect URI, scope, and state parameter. The simulator issues a code and redirects to the configured URI, where the test intercepts the redirect. The test then exchanges that code at /token. At this point, the simulator consumes the code, issues access and refresh tokens, and records the resulting state. This tests the redirect and exchange as a connected sequence rather than treating the token endpoint as the entire integration.
Next, the test calls /userinfo with the access token and receives claims consistent with the seeded user. It then submits the refresh token to /token, causing rotation and invalidation of the old credential. Revocation completes the lifecycle under test. After a call to /revoke, a subsequent /introspect call must report the token as inactive.
Running that sequence against a live provider adds latency, and each pull request then depends on the provider being available. Frequent logins from new CI IPs can also trigger CAPTCHA or suspicious-login detection. The recommended split is a stateful simulator for every PR run, with real-provider integration tests nightly or in staging for certificate expirations, UI changes, and attribute-mapping drift. Parallel jobs need separate identity worlds. Each job must use its own named set of users and client registration, because sharing a pool can cause account collisions or make another job’s stale session look valid.
Fault injection into auth paths: testing what happens when the IdP behaves badly
An auth failure can happen without an exception. The application may serve a request using stale claims with no log entry to show that anything went wrong. Fault injection must establish what the application does when identity information becomes unavailable or contradicts its cached understanding. Useful fault injection targets a particular moment in the workflow.
A latency spike at the token endpoint tests whether the application times out gracefully, retries safely, or creates a broken session. At userinfo, the same delay tests whether it serves cached claims, blocks, or propagates a user-visible error. Key rotation adds a different failure boundary. A 503 from JWKS at that moment tests whether the application uses cached keys or fails open during JWT validation. Inactive introspection results and mid-session refresh rejection similarly test whether the application re-authenticates, continues serving requests, or exposes an unhandled 401.
These scenarios require control over sequence as well as response. A live provider will not fail on command after code exchange but before userinfo retrieval, while a stateless mock lacks the shared history needed to model the interruption. Tool-using agents make this diagnostic problem harder because a stale or revoked credential may reach a downstream API without an exception at the auth step. Injecting that failure on purpose lets the evaluation link the downstream result to the earlier change in identity state.
Using the auth simulator as the identity layer when testing AI agents that call protected APIs
An agent can keep a token across many turns and have it expire halfway through a task. A test that never expires that token cannot show whether the agent re-authenticates before its next protected tool call. Scope boundaries need equivalent enforcement. If a prompt injection induces a request for an ungranted scope or reuse of a revoked credential, the evaluation must reject the operation according to auth state.
An agent can write clear output while sending a malformed token, so static fixtures can make matching the request shape the test expects look like understanding the flow. A stateful simulator makes those behaviors distinguishable by enforcing the same lifecycle constraints used in application integration tests. The relevant evaluation outcome is whether the protected operation was permitted in the current identity state.
For RL environments, repeatability follows from controlling that state. The same seed and state must support the same reward signal, which a live provider cannot reliably supply. Scaling across thousands of containers also requires independent credential state. In the practical configuration, tool definitions point to simulator endpoints, and the simulator owns token state for each agent episode. An episode reset restores the seed so that the next rollout begins from a clean identity world.
Keeping the simulator honest: continuous verification against the real IdP’s contract
The provider may change its token response fields or claim formats while the simulator still returns the old form. A signing-algorithm change can leave the seeded JWKS keypair out of step, and discovery changes can alter supported scopes or grant types. Error formats and HTTP statuses can change too. Passing tests then show that the application works with an old contract, without showing that it works with the provider it will actually use.
Detection and migration must remain separate mechanisms. Freezing simulator behavior supports deterministic tests, but it does not justify ignoring changes to the real provider. When verification detects a difference, teams need an explicit opt-in migration with a reviewable diff. A silent simulator update would instead change the contract while tests are running. Continuous verification must show when teams need to make that choice while keeping the test environment predictable.
Before making a simulator the CI authority, check its lifecycle against the provider’s published specification. Issue a token, rotate it, revoke it, and then introspect it. Compare the response shapes and status codes at each step, including the final inactive result. Escalate any divergence as drift before relying on the simulator for integration-test results.


