Wiring a Fully Controllable Auth Simulator Into Your Integration Test Suite for Stateful Grant Sequences
A local auth simulator lets you test OAuth grant order, not just response shapes.

Integration testing against stateful APIs requires a simulator that stores what earlier calls produced and uses that state to validate later calls. For OAuth, that means enforcing the grant sequence. Wiring a fully controllable auth simulator into an integration test suite lets engineers test order-dependent behavior locally, including replay rejection, refresh, and revocation, without hitting production.
Why OAuth grant flows require stateful test infrastructure
An authentication test suite can stay green while a production deployment fails at code exchange or refresh. The application parsed the expected responses and reached its dashboard, yet the tests never exercised the constraints between requests. That gap is structural. OAuth 2.0 authorization flows need records from earlier steps, while stateless test infrastructure treats each call as an event on its own.
The authorization code flow exposes the mismatch clearly. The client generates a cryptographically random code_verifier and derives a code_challenge using BASE64URL of SHA-256 of the verifier. The authorization server must retain that challenge so the token endpoint can compare it with the value derived from the verifier presented later. Meanwhile, the client must retain its verifier across the redirect. Neither side can validate the exchange from the token request alone.
The code itself introduces further dependencies on history. It is short-lived, single-use, and bound to client_id and redirect_uri, so its validity depends on issuance, elapsed time, and whether an earlier exchange consumed it. Refresh and revocation extend that history beyond initial authentication. A fixed response can resemble the output of any one step, but it cannot establish that the preceding steps made that output valid.
What stateless mocks actually verify, and what they leave dark
A stateless mock can establish that application code handles a particular response shape. Intercepting a fetch to the token endpoint, returning hardcoded JSON, and asserting that the interface updates is a useful parsing test. Its evidence stops there. It does not establish that the client supplied a valid verifier or exchanged a code belonging to the right client.
The distinction becomes important when the fixture supplies the very success condition the test claims to establish. If the stub returns a token regardless of the authorization history, a successful exchange follows from configuration. Adding more response fixtures covers more data shapes. It does not add memory to the infrastructure.
Without a stored challenge, a mock cannot test PKCE binding across requests. Without an issued-code record, it cannot distinguish first use from replay. Likewise, a resource endpoint cannot enforce the scope actually granted if its response is disconnected from consent and token issuance.
A practical discriminator is whether the infrastructure passes a “create then read, mutate then read” sequence with state-consistent responses. The second read must reflect the mutation. The same principle applies to grant state. Product terminology does not change this distinction between a mock and a simulator.
The grant sequence as a state machine: what a simulator must track
Authorization Code + PKCE begins with a client-generated verifier of 43–128 characters. The client derives code_challenge = BASE64URL(SHA-256(verifier)), and the simulator records the challenge against the in-flight authorization request. The request to /authorize includes response_type=code, the challenge, scope, and CSRF state. The simulator stores the state binding. Authentication and consent then add the consent decision and granted scope to that history.
Code issuance creates a new state with its own guards. The simulator records a short-lived code bound to client_id and redirect_uri, marks it as issued, and starts its expiry clock. The client subsequently posts grant_type=authorization_code, the code, redirect URI, client ID, and verifier to /token. The simulator derives the challenge from the submitted verifier and compares it with the stored challenge. A valid exchange consumes the code and issues tokens.
Resource access depends on those issued tokens. The resource endpoint validates the Bearer token against issuance state and checks its scope against the grant. A later grant_type=refresh_token request produces a new access token and, when configured, rotates the refresh token and revokes the old one. Revocation changes subsequent refresh and resource behavior, with any asynchronous propagation following documented timing.
Other grant types need their own models of how state changes. Client Credentials and Device Code flows still need records of the tokens issued, their scopes, and their expiry. RFC 9700, Best Current Practice for OAuth 2.0 Security, recommends challenge methods that do not expose the verifier and identifies S256 as the only such method. The simulator’s PKCE behavior must reflect the security profile being tested, rather than treating all challenge methods as interchangeable.
What "stateful" requires architecturally: the separator between a mock and a simulator
Storage alone does not make an auth simulator. Its protocol layer must enforce guards and apply transitions, so a consumed code produces the documented error. A wrong verifier must fail against the stored challenge. Responses must derive from the current records, with each step reflecting what earlier steps actually produced.
That protocol layer should be separable from HTTP, storage, and framework hooks. The separation allows PKCE computation, state validation, and issuance rules to be tested without coupling every assertion to transport behavior. It also makes the distinction between a protocol defect and an IO defect clearer. A configurable response handler that bypasses these rules remains a stub even if it retains some values.
Before each test, the simulator must return to a known baseline, with realistic seed data where the scenario needs it. An empty starting point forces every test to construct its prerequisites and can encourage dependence on execution or insertion order. A seeded grant history instead permits a test to begin at refresh or revocation without borrowing another test’s state.
Fault injection completes the control surface. Expired codes, scope mismatches, and a 429 from the token endpoint must be available on demand. These controls need to coexist with normal transition rules so the client encounters failures within a coherent grant history.
How do you wire a stateful auth simulator into an integration test suite?
Run the simulator as a local process on a laptop or in CI. Point the client’s authorization-server configuration at its base URL. No application change is needed beyond endpoint configuration. Running locally means the tests do not depend on live credentials, an external network being available, or live-service rate limits. In CI, the simulator can run as a sidecar or container.
Establish each scenario’s starting state before invoking the application. Seed existing consent, issued tokens, or revoked grants when those are the prerequisites under test. Then reset the simulator between tests or use isolated per-test namespaces. Test order must not supply hidden preconditions.
Place assertions at the protocol boundary that owns each rule. The authorization endpoint owns redirect validation, while the token endpoint owns verifier checks and code exchange. Assertions on the token response should check the scope, type, and lifetime fields. The resource endpoint must check intended audience and granted scopes, while refresh assertions must follow the configured rotation policy.
The suite should exercise S256 computation and the documented handling of missing or wrong verifiers and downgraded methods. It should also check redirect variants, expired codes, cross-client exchanges, and token requests that exceed the grant. Resource calls need cases for missing, expired, wrong-audience, and under-scoped tokens.
Wire controlled faults into the same execution path. A token-endpoint 429 tests backoff, a truncated or structurally malformed token response tests parsing resilience, and authorization-redirect latency tests timeout handling. Disrupting the network alone does not test all these protocol-specific failures. The CI suite should exit non-zero when a grant-sequence guard fires when it should not.
Testing the negative path: guard failures, replay, and revocation propagation
A successful grant shows that the flow works when its conditions are valid. Negative-path tests check whether the guards reject invalid transitions. Their assertions need to cover both the error returned and the history that makes rejection necessary. A canned failure response does not prove that a guard detected anything.
Code replay provides the clearest example of this distinction. The first exchange must succeed and consume the code before the second exchange is attempted. The second request must then fail because that same code is no longer usable. Similarly, a cross-client test must present client B with a code issued to client A.
Other guards bind requests to earlier decisions. A wrong verifier must produce the documented error, and a downgrade from S256 to plain must be rejected when the tested profile requires S256. Redirect checks must reject unregistered destinations and mismatches involving a subpath or query parameter. A request for wider scope than consent granted must produce rejection or scope downgrade according to the server’s documented policy.
Revocation tests must follow the change through refresh and resource access after POST /revoke. If propagation is asynchronous, assertions must cover the modeled transition. A browser can still reach a dashboard while these controls are broken. Interface success cannot substitute for boundary-level assertions.
Authorization codes, client secrets, access tokens, refresh tokens, ID tokens, and PKCE verifiers should stay out of test output. Use generated transaction IDs and redacted fingerprints instead. The simulator’s test-control API should support this approach with opaque identifiers.
Applying the same stateful pattern to AI agents that use OAuth-protected APIs
An AI agent encounters the same grant constraints as a conventional application. An agent can produce coherent text while sending a structurally malformed or semantically wrong token, so the test must evaluate its API interactions against retained protocol state.
The agent must extract the authorization code and state from the redirect response and pass the retained PKCE verifier in the correct position during exchange. Endpoint selection must also be explicit in the test. The exchange belongs at the token endpoint.
Later calls depend on correct response handling for valid inputs. Tests must establish that the agent reads and stores access_token, token_type, expires_in, and refresh_token correctly. When a resource call returns a 401 in the refresh scenario, the agent should initiate refresh. The simulator can evaluate that choice against the grant already in progress.
An error early in the sequence can affect every later tool invocation, even when the agent continues to produce plausible explanations. Tests must also address crafted tokens and attempts to exchange codes the agent should not hold. Those cases belong before deployment because post-deployment sampling cannot establish that the relevant guards were exercised.
Keeping the simulator accurate: drift, verification, and the cost of divergence
Statefulness does not guarantee fidelity to the real API. An authorization server can change PKCE requirements, code lifetimes, or error response shapes while the simulator still accepts the old behavior. Scope additions and deprecations create the same risk at resource boundaries. A change to refresh-token rotation can invalidate an otherwise coherent local grant model.
The environment being modeled must also be explicit. Braintree documents that its sandbox can differ from production, including in processing options, webhooks, and dispute management.
Continuous verification should include re-verification against the live API before every release as well as periodic checks. A change between weekly checks is enough to let a broken integration reach staging. This verification is separate from the local integration suite’s execution. Its purpose is to keep the model credible without making every application test depend on a live service.
Published fidelity scores should state which endpoints and behaviors were checked and when verification took place. Without that visibility, teams must audit the simulator themselves or return to live API testing. Lightweight stateless stubs can serve shape-only assertions in early CI, while every merge touching auth-flow code should be gated on a full stateful simulator run.


