Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -109,4 +109,20 @@ extension CmxIrohClientRuntime {
static func isConnectivity(_ error: any Error) -> Bool {
(error as? CmxIrohTrustBrokerClientError) == .connectivity
}

/// Failures that may fall back to the verified offline policy cache.
///
/// Connectivity has always qualified. An unauthorized rejection (401/403)
/// qualifies too: it already survived the broker client's single
/// force-refresh retry, so it is a session transition still settling or a
/// server-side availability condition, and the cached bootstrap carries no
/// authority the broker did not previously sign. Proceeding keeps LAN and
/// cached-relay paths dialable while auth settles; a genuinely dead session
/// stops the runtime through the auth coordinator's state clear.
static func recoversWithCachedPolicy(_ error: any Error) -> Bool {
if isConnectivity(error) { return true }
guard case let .rejected(statusCode, _)? =
error as? CmxIrohTrustBrokerClientError else { return false }
return statusCode == 401 || statusCode == 403
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ extension CmxIrohClientRuntime {
// authenticated discovery can still confirm an existing tuple.
registration = nil
} else {
guard Self.isConnectivity(error),
guard Self.recoversWithCachedPolicy(error),
let cached = try await offlineBootstrap(
expectation: offlineExpectation,
confirmedLocalBinding: nil
Expand All @@ -100,7 +100,7 @@ extension CmxIrohClientRuntime {
discovery = try await broker.discover()
} catch {
guard let registration,
Self.isConnectivity(error),
Self.recoversWithCachedPolicy(error),
let cached = try await offlineBootstrap(
expectation: offlineExpectation,
confirmedLocalBinding: registration.binding
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,26 @@ public struct CmxIrohBrokerTokenSource: Sendable {
/// Both tokens from ONE snapshot, so a request can never mix an old access
/// token with a rotated refresh token.
public let credentialPair: @Sendable () async -> CmxIrohBrokerCredentials?
/// Replaces a pair the broker just rejected as unauthorized.
///
/// A pair that was coherent at capture can still be rejected when another
/// lane rotates the session between capture and server validation (the
/// wake-time RPC force refresh, most commonly). Live sources force-mint
/// through their session owner and return the replacement pair; frozen
/// pinned sources (sign-out revocation) return nil so a destructive flow
/// never silently switches credentials. The client retries the rejected
/// request at most once with the recovered pair.
public let recoveredCredentialPair:
@Sendable (_ rejected: CmxIrohBrokerCredentials) async -> CmxIrohBrokerCredentials?

public init(
credentialPair: @escaping @Sendable () async -> CmxIrohBrokerCredentials?
credentialPair: @escaping @Sendable () async -> CmxIrohBrokerCredentials?,
recoveredCredentialPair: @escaping @Sendable (
_ rejected: CmxIrohBrokerCredentials
) async -> CmxIrohBrokerCredentials? = { _ in nil }
) {
self.credentialPair = credentialPair
self.recoveredCredentialPair = recoveredCredentialPair
self.accessToken = { await credentialPair()?.accessToken }
self.refreshToken = { await credentialPair()?.refreshToken }
}
Expand Down Expand Up @@ -451,8 +466,49 @@ public actor CmxIrohTrustBrokerClient: CmxIrohRelayPolicyServing {
guard let pair = await tokenSource.credentialPair() else {
throw CmxIrohTrustBrokerClientError.missingAuthentication
}
let accessToken = pair.accessToken
let refreshToken = pair.refreshToken
do {
return try await performAuthenticatedRequest(
path: path,
method: method,
body: body,
queryItems: queryItems,
credentials: pair
)
} catch let error as CmxIrohTrustBrokerClientError
where Self.isUnauthorizedRejection(error) {
// A pair that was coherent at capture can be rejected when another
// lane rotated the session before the server validated it. Recover
// ONCE with a pair minted after the rejection; a second rejection
// is authoritative and propagates.
guard let recovered = await tokenSource.recoveredCredentialPair(pair) else {
throw error
}
return try await performAuthenticatedRequest(
path: path,
method: method,
body: body,
queryItems: queryItems,
credentials: recovered
)
}
}

private static func isUnauthorizedRejection(
_ error: CmxIrohTrustBrokerClientError
) -> Bool {
guard case let .rejected(statusCode, _) = error else { return false }
return statusCode == 401
}

private func performAuthenticatedRequest<Response: Decodable & Sendable>(
path: String,
method: String,
body: Data?,
queryItems: [URLQueryItem],
credentials: CmxIrohBrokerCredentials
) async throws -> Response {
let accessToken = credentials.accessToken
let refreshToken = credentials.refreshToken
guard Self.isSafeHeaderValue(accessToken), Self.isSafeHeaderValue(refreshToken) else {
throw CmxIrohTrustBrokerClientError.invalidAuthentication
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,18 @@ public enum CmxIrohTrustBrokerClientError:
case .rateLimited:
return true
case let .rejected(statusCode, _):
return statusCode == 408
// 401/403: an unauthorized rejection here already survived the
// broker client's single force-refresh retry, so it is a session
// transition still settling (rotation race, locked token store) or
// a server-side availability condition — not a trust change. The
// cached policy was verified when stored; tearing the runtime down
// buys nothing and turns a seconds-long auth blip into a full
// endpoint rebuild. A genuinely dead session clears auth state
// through the coordinator, which stops the runtime through the
// lifecycle owner instead.
return statusCode == 401
|| statusCode == 403
|| statusCode == 408
|| statusCode == 425
|| statusCode == 429
|| (500...599).contains(statusCode)
Expand All @@ -53,7 +64,12 @@ public enum CmxIrohTrustBrokerClientError:
case let .rejected(statusCode, _):
// A server failure cannot establish trust, so retrying the request
// is safe while the lifecycle-owned start task remains current.
return statusCode == 408
// 401 joins the retriable set: it already survived the broker
// client's single force-refresh retry, so it is a session
// transition still settling; a dead session exits through the auth
// coordinator's state clear, not through this loop.
return statusCode == 401
|| statusCode == 408
|| statusCode == 425
|| statusCode == 429
|| (500...599).contains(statusCode)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import Foundation
import Testing
@testable import CmuxIrohTransport

/// Regression coverage for the wake-time authorization outage: a broker 401
/// used to tear down the whole verified runtime (endpoint, routes, offline
/// cache) and nap for 30s+ of backoff, turning a seconds-long token rotation
/// race into a multi-minute connectivity gap on every app foreground.
struct CmxIrohTrustBrokerClientAuthClassifierTests {
@Test
func unauthorizedRejectionPreservesVerifiedPolicyDuringRefresh() {
#expect(CmxIrohTrustBrokerClientError.preservesVerifiedPolicyDuringRefresh(
CmxIrohTrustBrokerClientError.rejected(
statusCode: 401,
code: "unauthorized"
)
))
#expect(CmxIrohTrustBrokerClientError.preservesVerifiedPolicyDuringRefresh(
CmxIrohTrustBrokerClientError.rejected(statusCode: 403, code: nil)
))
}

@Test
func unauthorizedRejectionRetriesInitialActivation() {
#expect(CmxIrohTrustBrokerClientError.retriesInitialActivation(
CmxIrohTrustBrokerClientError.rejected(
statusCode: 401,
code: "unauthorized"
)
))
// 403 can be a durable permission denial; initial activation must not
// spin on it.
#expect(!CmxIrohTrustBrokerClientError.retriesInitialActivation(
CmxIrohTrustBrokerClientError.rejected(statusCode: 403, code: nil)
))
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
import Foundation
import Testing
@testable import CmuxIrohTransport

/// The broker client's exactly-once credential recovery: a pair that was
/// coherent at capture can still be rejected when another lane rotates the
/// session between capture and server validation (the wake-time RPC force
/// refresh, most commonly). One retry with a pair minted after the rejection
/// absorbs the race; a second rejection is authoritative.
@Suite(.serialized)
struct CmxIrohTrustBrokerClientAuthRecoveryTests {
private actor RecoveryRecorder {
private(set) var rejectedPairs: [CmxIrohBrokerCredentials] = []
private let recovered: CmxIrohBrokerCredentials?

init(recovered: CmxIrohBrokerCredentials?) {
self.recovered = recovered
}

func recover(
_ rejected: CmxIrohBrokerCredentials
) -> CmxIrohBrokerCredentials? {
rejectedPairs.append(rejected)
return recovered
}
}

@Test
func unauthorizedRejectionRetriesOnceWithRecoveredPair() async throws {
let transport = RecordingBrokerTransport(responses: [
.json(status: 401, body: #"{"error":"unauthorized"}"#),
.json(status: 201, body: Self.challengeBody),
])
let recorder = RecoveryRecorder(recovered: CmxIrohBrokerCredentials(
accessToken: "fresh-access",
refreshToken: "fresh-refresh"
))
let client = try makeClient(transport: transport, recorder: recorder)

let response = try await client.issueChallenge(try Self.challengeRequest)

#expect(response.challengeID == "123e4567-e89b-42d3-a456-426614174000")
let requests = await transport.requests()
#expect(requests.count == 2)
#expect(requests.first?.value(
forHTTPHeaderField: "Authorization"
) == "Bearer stale-access")
#expect(requests.last?.value(
forHTTPHeaderField: "Authorization"
) == "Bearer fresh-access")
#expect(requests.last?.value(
forHTTPHeaderField: "X-Stack-Refresh-Token"
) == "fresh-refresh")
let rejected = await recorder.rejectedPairs
#expect(rejected.count == 1)
#expect(rejected.first?.accessToken == "stale-access")
#expect(rejected.first?.refreshToken == "stale-refresh")
}

@Test
func unauthorizedRejectionWithoutRecoveryPropagates() async throws {
let transport = RecordingBrokerTransport(responses: [
.json(status: 401, body: #"{"error":"unauthorized"}"#),
])
let client = try CmxIrohTrustBrokerClient(
baseURL: #require(URL(string: "https://cmux.example")),
tokenSource: CmxIrohBrokerTokenSource(credentialPair: {
CmxIrohBrokerCredentials(
accessToken: "stale-access",
refreshToken: "stale-refresh"
)
}),
transport: transport
)

await #expect(throws: CmxIrohTrustBrokerClientError.rejected(
statusCode: 401,
code: "unauthorized"
)) {
_ = try await client.issueChallenge(try Self.challengeRequest)
}
#expect(await transport.requests().count == 1)
}

@Test
func repeatedUnauthorizedRejectionStopsAfterOneRetry() async throws {
let transport = RecordingBrokerTransport(responses: [
.json(status: 401, body: #"{"error":"unauthorized"}"#),
.json(status: 401, body: #"{"error":"unauthorized"}"#),
])
let recorder = RecoveryRecorder(recovered: CmxIrohBrokerCredentials(
accessToken: "fresh-access",
refreshToken: "fresh-refresh"
))
let client = try makeClient(transport: transport, recorder: recorder)

await #expect(throws: CmxIrohTrustBrokerClientError.rejected(
statusCode: 401,
code: "unauthorized"
)) {
_ = try await client.issueChallenge(try Self.challengeRequest)
}
#expect(await transport.requests().count == 2)
#expect(await recorder.rejectedPairs.count == 1)
}

@Test
func forbiddenRejectionDoesNotInvokeRecovery() async throws {
let transport = RecordingBrokerTransport(responses: [
.json(status: 403, body: #"{"error":"forbidden"}"#),
])
let recorder = RecoveryRecorder(recovered: CmxIrohBrokerCredentials(
accessToken: "fresh-access",
refreshToken: "fresh-refresh"
))
let client = try makeClient(transport: transport, recorder: recorder)

await #expect(throws: CmxIrohTrustBrokerClientError.rejected(
statusCode: 403,
code: "forbidden"
)) {
_ = try await client.issueChallenge(try Self.challengeRequest)
}
#expect(await transport.requests().count == 1)
#expect(await recorder.rejectedPairs.isEmpty)
}

@Test
func authRejectionsRecoverWithCachedPolicy() {
#expect(CmxIrohClientRuntime.recoversWithCachedPolicy(
CmxIrohTrustBrokerClientError.connectivity
))
#expect(CmxIrohClientRuntime.recoversWithCachedPolicy(
CmxIrohTrustBrokerClientError.rejected(
statusCode: 401,
code: "unauthorized"
)
))
#expect(CmxIrohClientRuntime.recoversWithCachedPolicy(
CmxIrohTrustBrokerClientError.rejected(statusCode: 403, code: nil)
))
#expect(!CmxIrohClientRuntime.recoversWithCachedPolicy(
CmxIrohTrustBrokerClientError.rejected(statusCode: 500, code: nil)
))
#expect(!CmxIrohClientRuntime.recoversWithCachedPolicy(
CmxIrohTrustBrokerClientError.invalidResponse
))
}

private func makeClient(
transport: RecordingBrokerTransport,
recorder: RecoveryRecorder
) throws -> CmxIrohTrustBrokerClient {
try CmxIrohTrustBrokerClient(
baseURL: #require(URL(string: "https://cmux.example")),
tokenSource: CmxIrohBrokerTokenSource(
credentialPair: {
CmxIrohBrokerCredentials(
accessToken: "stale-access",
refreshToken: "stale-refresh"
)
},
recoveredCredentialPair: { rejected in
await recorder.recover(rejected)
}
),
transport: transport
)
}

private static let challengeBody =
#"{"challenge_id":"123e4567-e89b-42d3-a456-426614174000","nonce":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","expires_at":"2026-07-10T01:00:00.000Z"}"#

private static let endpointID =
"03a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b8"

private static var challengeRequest: CmxIrohChallengeRequest {
get throws {
let secret = try CmxIrohSecretKey(
bytes: Data((0 ..< 32).map(UInt8.init))
)
let identity = try CmxIrohIdentityMaterial(
secretKey: secret,
generation: 1
)
let signer = try CmxIrohRegistrationSigner(
identity: identity,
endpointID: endpointID
)
let payload = try CmxIrohRegistrationPayload(
deviceID: "123e4567-e89b-42d3-a456-426614174001",
appInstanceID: "123e4567-e89b-42d3-a456-426614174002",
tag: "stable",
platform: .ios,
endpointID: endpointID,
identityGeneration: 1,
pairingEnabled: false,
capabilities: ["control"],
pathHints: [],
now: Date(timeIntervalSince1970: 1_782_000_000)
)
return try signer.prepare(payload: payload).challengeRequest
}
}
}
Loading