Repository navigation
T 1532290: Serialize concurrent token refreshes to prevent one-time refresh token double-spend #174
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
vishal-mb
merged 4 commits into
main
from
Task/1532290-Serialize-concurrent-token-refreshes
Aug 31, 2026
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
2b615bb
Add red contract test: concurrent middleware refreshes double-spend t…
vishal-mb 7ab1df1
Serialize in-process token refreshes with an atomic generation-scoped…
vishal-mb 1ffbd27
Merge remote-tracking branch 'origin/main' into Task/1532290-Serializ…
vishal-mb a10843b
Test client failure waiter behavior
vishal-mb File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
53 changes: 53 additions & 0 deletions
53
Sources/Conduit/Auth/TokenStorage/Coordination/OAuth2RefreshClaimRegistry.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| // | ||
| // OAuth2RefreshClaimRegistry.swift | ||
| // Conduit | ||
| // | ||
| // Copyright © 2026 MINDBODY. All rights reserved. | ||
| // | ||
|
|
||
| import Foundation | ||
|
|
||
| /// Process-wide atomic refresh claim per client + authorization — the in-process mutual exclusion the check-then-act persisted lock lacks. | ||
| final class OAuth2RefreshClaimRegistry { | ||
|
|
||
| static let shared = OAuth2RefreshClaimRegistry() | ||
|
|
||
| private struct Claim { | ||
| let generation: UInt64 | ||
| let expiresAt: Date | ||
| } | ||
|
|
||
| private let lock = NSLock() | ||
| private var claims: [String: Claim] = [:] | ||
| private var nextGeneration: UInt64 = 0 | ||
|
|
||
| /// Returns an ownership generation for `release(key:generation:)`, or nil if a live claim is held. | ||
| /// Claims expire after `staleAfter` and become stealable, so a hung refresh can never wedge refreshes permanently. | ||
| func tryClaim(key: String, staleAfter: TimeInterval) -> UInt64? { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| if let existing = claims[key], Date() < existing.expiresAt { | ||
| return nil | ||
| } | ||
| nextGeneration += 1 | ||
| claims[key] = Claim(generation: nextGeneration, expiresAt: Date().addingTimeInterval(staleAfter)) | ||
| return nextGeneration | ||
| } | ||
|
|
||
| /// Returns whether `generation` still owns the claim; gates completion side effects of a possibly-superseded refresh. | ||
| func owns(key: String, generation: UInt64) -> Bool { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| return claims[key]?.generation == generation | ||
|
vishal-mb marked this conversation as resolved.
|
||
| } | ||
|
|
||
| /// No-ops unless `generation` owns the current claim — a superseded holder cannot clear its successor's claim. | ||
| func release(key: String, generation: UInt64) { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| guard claims[key]?.generation == generation else { | ||
| return | ||
| } | ||
| claims[key] = nil | ||
| } | ||
| } | ||
143 changes: 143 additions & 0 deletions
143
Tests/ConduitTests/Auth/ConcurrentRefreshTestSupport.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,143 @@ | ||
| // | ||
| // ConcurrentRefreshTestSupport.swift | ||
| // Conduit | ||
| // | ||
| // Copyright © 2026 MINDBODY. All rights reserved. | ||
| // | ||
|
|
||
| import Foundation | ||
| @testable import Conduit | ||
|
|
||
| /// Records every grant issued and returns rotated tokens like a real token endpoint. | ||
| final class RecordingRefreshStrategyFactory: OAuth2RefreshStrategyFactory { | ||
| private let recordLock = NSLock() | ||
| private(set) var issuedGrantRefreshTokens: [String] = [] | ||
|
|
||
| func make(refreshToken: String, clientConfiguration: OAuth2ClientConfiguration) -> OAuth2TokenGrantStrategy { | ||
| recordLock.lock() | ||
| issuedGrantRefreshTokens.append(refreshToken) | ||
| let rotation = issuedGrantRefreshTokens.count | ||
| recordLock.unlock() | ||
| let rotatedToken = BearerToken(accessToken: "ACCESS_\(rotation)", | ||
| refreshToken: "ROTATED_\(rotation)", | ||
| expiration: Date().addingTimeInterval(3_600)) | ||
| return StubbedGrantStrategy(token: rotatedToken) | ||
| } | ||
| } | ||
|
|
||
| /// Completes asynchronously with a fixed token, mimicking token-endpoint latency. | ||
| struct StubbedGrantStrategy: OAuth2TokenGrantStrategy { | ||
| let token: BearerToken | ||
|
|
||
| func issueToken(completion: @escaping (Result<BearerToken>) -> Void) { | ||
| DispatchQueue.global().asyncAfter(deadline: .now() + .milliseconds(50)) { | ||
| completion(.value(token)) | ||
| } | ||
| } | ||
|
|
||
| func issueToken() throws -> BearerToken { | ||
| return token | ||
| } | ||
| } | ||
|
|
||
| /// Fails with clientFailure only after the test signals, so the claim can go stale while the grant is in flight. | ||
| struct GatedFailureStrategy: OAuth2TokenGrantStrategy { | ||
| let proceed: DispatchSemaphore | ||
|
|
||
| func issueToken(completion: @escaping (Result<BearerToken>) -> Void) { | ||
| DispatchQueue.global().async { | ||
| self.proceed.wait() | ||
| completion(.error(OAuth2Error.clientFailure(nil, nil))) | ||
| } | ||
| } | ||
|
|
||
| func issueToken() throws -> BearerToken { | ||
| throw OAuth2Error.clientFailure(nil, nil) | ||
| } | ||
| } | ||
|
|
||
| final class GatedFailureStrategyFactory: OAuth2RefreshStrategyFactory { | ||
| let proceed = DispatchSemaphore(value: 0) | ||
| private let recordLock = NSLock() | ||
| private var recordedRefreshTokens: [String] = [] | ||
|
|
||
| var issuedGrantRefreshTokens: [String] { | ||
| recordLock.lock() | ||
| defer { recordLock.unlock() } | ||
| return recordedRefreshTokens | ||
| } | ||
|
|
||
| func make(refreshToken: String, clientConfiguration: OAuth2ClientConfiguration) -> OAuth2TokenGrantStrategy { | ||
| recordLock.lock() | ||
| recordedRefreshTokens.append(refreshToken) | ||
| recordLock.unlock() | ||
| return GatedFailureStrategy(proceed: proceed) | ||
| } | ||
| } | ||
|
|
||
| /// Succeeds with a rotated token only after the test signals, so the claim can go stale while the grant is in flight. | ||
| struct GatedSuccessStrategy: OAuth2TokenGrantStrategy { | ||
| let proceed: DispatchSemaphore | ||
| let token: BearerToken | ||
|
|
||
| func issueToken(completion: @escaping (Result<BearerToken>) -> Void) { | ||
| DispatchQueue.global().async { | ||
| self.proceed.wait() | ||
| completion(.value(token)) | ||
| } | ||
| } | ||
|
|
||
| func issueToken() throws -> BearerToken { | ||
| return token | ||
| } | ||
| } | ||
|
|
||
| final class GatedSuccessStrategyFactory: OAuth2RefreshStrategyFactory { | ||
| let proceed = DispatchSemaphore(value: 0) | ||
|
|
||
| func make(refreshToken: String, clientConfiguration: OAuth2ClientConfiguration) -> OAuth2TokenGrantStrategy { | ||
| GatedSuccessStrategy(proceed: proceed, | ||
| token: BearerToken(accessToken: "LATE", refreshToken: "RT_LATE", | ||
| expiration: Date().addingTimeInterval(3_600))) | ||
| } | ||
| } | ||
|
|
||
| /// Returns the expired token for the first read and the fresh token afterwards — scripting the | ||
| /// "another refresh persisted while we raced" interleavings deterministically. | ||
| final class ScriptedReadTokenStore: OAuth2TokenStore { | ||
| private let underlying = OAuth2TokenMemoryStore() | ||
| private let readLock = NSLock() | ||
| private var reads = 0 | ||
| let expiredToken = BearerToken(accessToken: "EXPIRED", refreshToken: "RT_OLD", expiration: Date()) | ||
| let freshToken = BearerToken(accessToken: "FRESH", refreshToken: "RT_NEW", | ||
| expiration: Date().addingTimeInterval(3_600)) | ||
|
|
||
| @discardableResult | ||
| func store<Token: OAuth2Token & DataConvertible>(token: Token?, for client: OAuth2ClientConfiguration, | ||
| with authorization: OAuth2Authorization) -> Bool { | ||
| underlying.store(token: token, for: client, with: authorization) | ||
| } | ||
|
|
||
| func tokenFor<Token: OAuth2Token & DataConvertible>(client: OAuth2ClientConfiguration, | ||
| authorization: OAuth2Authorization) -> Token? { | ||
| readLock.lock() | ||
| defer { readLock.unlock() } | ||
| reads += 1 | ||
| return (reads == 1 ? expiredToken : freshToken) as? Token | ||
| } | ||
|
|
||
| @discardableResult | ||
| func lockRefreshToken(timeout: TimeInterval, client: OAuth2ClientConfiguration, | ||
| authorization: OAuth2Authorization) -> Bool { | ||
| underlying.lockRefreshToken(timeout: timeout, client: client, authorization: authorization) | ||
| } | ||
|
|
||
| @discardableResult | ||
| func unlockRefreshTokenFor(client: OAuth2ClientConfiguration, authorization: OAuth2Authorization) -> Bool { | ||
| underlying.unlockRefreshTokenFor(client: client, authorization: authorization) | ||
| } | ||
|
|
||
| func refreshTokenLockExpirationFor(client: OAuth2ClientConfiguration, authorization: OAuth2Authorization) -> Date? { | ||
| underlying.refreshTokenLockExpirationFor(client: client, authorization: authorization) | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.