Sequencing OAuth Grant Steps as Ordered Integration Test Contracts
Ordered, stateful contracts catch OAuth bugs that stateless mocks miss.

Integration testing against stateful APIs requires ordered contracts that pass real state from one operation to the next and verify the constraints it imposes. For OAuth, a stateful simulator with isolated fixtures and controllable faults supports this testing without production credentials. Sequencing OAuth grant steps as ordered integration test contracts tests protocol enforcement, while stateless mocks show only that configured responses agree.
Why an OAuth grant flow is a dependency chain, not a collection of independent calls
An OAuth flow begins with an authorization request, proceeds through code issuance and PKCE-verified token exchange, and reaches scoped resource access. Refresh extends the lifecycle, and optional revocation ends it. These calls are not independent HTTP transactions. Each operation depends on state established earlier, so a successful response is meaningful only if the required prior state exists.
The client creates transaction material, while the authorization server validates the request and user decision. The token endpoint validates the code, client, redirect URI, and PKCE proof before issuing tokens. The resource server then validates token authority and scope. A browser happy path can succeed even when state is ignored, code replay succeeds, or the resource server accepts a token for another audience.
What each step in the chain produces and what the next step must consume
The authorization request establishes a transaction-specific PKCE challenge and state value, both bound to that flow instance. The authorization server response then supplies a short-lived, single-use code bound to the exact client and redirect URI from the originating request. This state constrains the next valid operation. The client must check the returned state before accepting the code, and the token exchange must consume that code with the redirect URI and the verifier corresponding to the transaction’s challenge.
A valid exchange produces an access token and refresh token. The access token lets the client access resources within its authority and scope, while the refresh token is used to renew them later. Under rotation, that renewal produces a new access and refresh pair and invalidates its predecessor. Revocation must then change refresh and resource behavior, with the resource server reflecting revoked state immediately or within a bounded window.
Why stateless mocks cannot verify this chain even when every individual response looks correct
A stateless mock returns a response selected solely by configuration. It can return a plausible code followed by a plausible token, but it has no record connecting their issuance. Matching values do not establish a state transition. Without memory of the authorization request, the mock cannot enforce that an exchanged code was issued for that client, redirect URI, and PKCE challenge.
The same limitation applies when validity changes after use. A canned success response cannot prove that the first exchange marked a code consumed, so a second exchange does not test replay protection. Refresh rotation needs a record of predecessor tokens, and revocation and resource checks must share state. Without those relationships, a green suite may show only that the HTTP client made the expected calls in order. Configuration-consistency is not protocol-enforcement.
What an ordered, stateful integration contract actually is and how it differs from an assertion
An ordered contract defines the state that one step must produce before the next step can proceed. If that precondition is absent, the test fails at the boundary, before reaching an assertion several calls later. Its defining property is a detectable failure when the protected invariant is removed. A passing assertion alone does not establish that property. An assertion that a response contains a token, for example, says nothing about whether that token exceeds the authority granted through consent.
The maidan PR #1417 grant-scope contract suite pins that authority bound end to end. No token issued through code exchange or refresh can include a capability beyond what the consenting member holds, what the client allows, and what is delegatable. The contract checks how those inputs bound the resulting token as well as whether the token is present. Break-checking distinguishes the two by testing whether removal of the bound makes the relevant test fail. This gives the suite a defined failure target for future refactors.
How to structure ordered contracts for each stage of the authorization-code PKCE flow
To implement that model, engineers should structure the PKCE suite as serial contracts in dependency order. The authorization endpoint contract requires exact redirect URI validation rather than prefix matching, with look-alike, subpath, query, and open-redirect variants rejected. It also requires a transaction-specific state value checked before code acceptance and an enforced S256 challenge. These checks establish the conditions for code issuance. The next contract requires a short-lived, single-use code bound to the originating client and redirect URI, with cross-client exchange rejected.
The token exchange contract then exercises those bindings against the issued code. A wrong or omitted verifier must return invalid_grant, as must reuse of the code, while a wrong redirect URI or client must be rejected. Once a valid exchange has set up token state, the refresh contract requires predecessor invalidation and token-family collapse if reuse falls outside a grace window. Revocation comes after a grant and its tokens exist. Its contract must show when consent or grant revocation took effect for refresh and resource access, including how long it took for those calls to fail.
The scope and tenant-isolation contracts that prevent silent grant widening
Silent grant widening happens when a refreshed token has capabilities that the original consent never authorized. Detecting it requires the suite to preserve the relationship between consent, member authority, client allowance, and refresh output. The scope contract must track the grant through exchange and refresh and keep authority capabilities non-delegatable even when the member’s own token holds them.
The maidan PR #1404 grant-management work also sets a bound on who can access a grant. Every read is scoped to the caller’s own workspace and member, and the list contains only the caller’s live grants. Another member’s grant in the same workspace returns a 404, as does the same member’s grant addressed under another workspace. These cases check member isolation and workspace isolation in turn. Dropping either predicate must make its specific contract fail. A successful authorized read alone is insufficient.
Revocation must preserve the same ownership boundary while ending the entire grant lineage. The grant-management work uses revoke_oauth_lineage_audited so that the grant, its access tokens, and its refresh tokens end together. The audit row names the member and records member_revocation as the reason. Break-checking lineage revocation must make a test fail if the implementation stops ending the tokens tied to the grant.
Ordering and isolation requirements that make stateful contract suites work in CI
Serial execution follows directly from the dependency chain because a later step cannot consume state that does not yet exist. That does not require serializing the entire API suite. The recommended split runs stateless tests, which cover the vast majority of the API surface, in parallel while OAuth contract scenarios run serially with their own isolated fixtures. Isolation prevents one run from inheriting another’s consumed codes or revoked grants. Differences between individual and parallel execution indicate state leakage.
A stateful simulator with consistent fixture data seeded ahead of time gives each run a known place to start without teardown logic that can easily break. The OAuth surface should have its own rate-limit buckets so it does not share the broader API’s budget. The grant-scope work shows how to use per-(client-id, address) and per-address buckets and check them with break-checking. This keeps repeated token-endpoint calls from using up a shared API budget while letting the contract suite test how rate limits behave.
Fault conditions that must be covered by ordered contracts, not left to manual testing
A wrong verifier is wrong only relative to a challenge established earlier in that transaction. An expired code must first have been issued, and a replay test requires a successful exchange that persisted the code’s consumed state. The fault contracts need the same setup steps, in the same order, as the happy path. Wrong and omitted verifiers must produce invalid_grant, while a downgraded challenge method must be rejected.
Rate-limit behavior also belongs in the integration contract as well as in unit tests of the limiter. The suite must exercise a 429 response, optionally with Retry-After, against the OAuth surface. For the per-(client-id, address) bucket, one client reaching its limit must not consume another client’s allowance from the same address. A stateful simulator can also inject 429s, 503s, and latency to test how the client handles failures without using live credentials or running into real rate limits.
An arbitrary sleep followed by a rejected request proves only that revocation had taken effect by that later check. Bounded polling must show when the changed state took effect within the allowed window. The grant must be valid before revocation is applied. Otherwise, a rejected resource request could pass the test without showing any propagation at all.
How AI agents using OAuth-gated APIs inherit the same stateful contract requirements
An AI agent can produce coherent output while sending malformed or stale token data to an OAuth-gated API. Its internal representation of grant status may differ from the authorization server’s record. Fluent output does not resolve that divergence. If the test environment returns success regardless of token state, the agent never has to handle expiry, rotation failure, or revocation.
A stateful simulator makes the disagreement observable by allowing the environment to revoke a token mid-session, rotate it, or return a 401. The agent’s response can then be asserted against the authorization state that actually exists. For RL environments and agent evaluation at scale, runs across many parallel containers can be deterministic only if each episode has its own isolated state. Parallel episodes can preserve serial dependencies within each grant flow, applying the same separation between ordering and isolation used in traditional integration suites.
What a complete ordered contract suite for an OAuth implementation covers
Completion requires coverage of each grant type’s lifecycle, each transition’s preconditions, and the associated faults. For client credentials, that includes success, a wrong secret, a rate-limit 429, and scope subset enforcement. Authorization-code PKCE adds plain-challenge rejection, an error without redirection for an unregistered redirect URI, and access_denied after consent denial. These complement the exchange and replay contracts already defined.
A request for a wider scope during refresh must return invalid_scope, and the suite must test rotation, predecessor invalidation, and family collapse outside the reuse grace window. Revocation must end the grant and both token types, reach the resource server within the bounded window, and record the actor. Tenant contracts must check member isolation and workspace isolation on their own. Scope contracts must also preserve the distinction between authority a member holds and authority that can be delegated.
A stateful simulator with consistent fixtures and controllable fault injection provides the foundation for running these contracts in CI and isolated agent evaluations. But infrastructure alone does not make the suite complete. Removing the member check, scope bound, or lineage revocation must cause a specific test to go red. Break-checking is the defining test of the contract. Consistency that can only be broken by changing configuration is not evidence of correct OAuth behavior.


