Skip to content
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

Dead token recovery #1216

Merged
merged 9 commits into from
Feb 7, 2025
Merged

Dead token recovery #1216

merged 9 commits into from
Feb 7, 2025

Conversation

federicocappelli
Copy link
Member

@federicocappelli federicocappelli commented Feb 5, 2025

Task/Issue URL: https://app.asana.com/0/1205842942115003/1209252725803000
iOS PR: no
macOS PR: no
What kind of version bump will this require?: none

Description:

This PR introduces improvements in the "dead token" detection and recovery for Auth V2.
A deat token happens when the refresh has expired.
The only thing we can do is log out the user and try to recover the subscription, if it was purchased via the Apple store, or show an error to the user for Stripe.

Steps to test this PR:
The code is not used yet, check the unit tests


Internal references:

Software Engineering Expectations
Technical Design Template

@@ -204,26 +207,45 @@ final public class DefaultOAuthClient: OAuthClient {
public func getTokens(policy: AuthTokensCachePolicy) async throws -> TokenContainer {
let localTokenContainer = tokenStorage.tokenContainer

if policy != .local,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we now check the refresh token validity every time we return a token

#if DEBUG
let expiresSoon = false
#else
// Expires in less than 10 minutes, check only in release, the staging token expires every 4 minutes
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've added a local check for the token expiry date, if it's less than 10 minutes we treat it as expired

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think about extracting the "10" into a constant. Also for the DEBUG you could use a different value (2?) there? Logic here would be cleaner and the flow would be dependant on a value.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changed!

@@ -237,11 +259,12 @@ final public class DefaultOAuthClient: OAuthClient {
return refreshedTokens
} catch OAuthServiceError.authAPIError(let code) where code == OAuthRequest.BodyErrorCode.invalidTokenRequest {
Logger.OAuthClient.error("Failed to refresh token: invalidTokenRequest")
throw OAuthClientError.refreshTokenExpired
throw OAuthClientError.invalidTokenRequest
Copy link
Member Author

@federicocappelli federicocappelli Feb 5, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here I maintain a similar error to the one sent by the API. .invalidTokenRequest can happen for reasons other than a dead token, for example when we try to use a staging token in production.

@available(macOS 12.0, *)
public struct DeadTokenRecoverer {

private static var recoveryAttempted: Int = 0
Copy link
Member Author

@federicocappelli federicocappelli Feb 5, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In case the BE has a problem and always returns a OAuthClientError.invalidTokenRequest every time we request a token, we don't want to enter an infinite loop, so we must be sure that we are not already in a recovery state.
This state helps with that and it's not a bool because multiple, parallel API requests could use this utility and we want to be sure we don't have concurrency issues.

import os.log

@available(macOS 12.0, *)
public struct DeadTokenRecoverer {
Copy link
Member Author

@federicocappelli federicocappelli Feb 5, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This utility must be outside the subscription manager because requires Apple recovery flow, but we don't want to re-implement it every time, so the dead token recovery business logic is all here and can be used by the main apps.
This utility's main function is used in the SubscriptionManagerV2 autoRecoveryHandler block


subscriptionManager = DefaultSubscriptionManagerV2(
storePurchaseManager: mockStorePurchaseManager,
oAuthClient: mockOAuthClient,
subscriptionEndpointService: mockSubscriptionEndpointService,
subscriptionEnvironment: SubscriptionEnvironment(serviceEnvironment: .staging, purchasePlatform: .stripe),
pixelHandler: { _ in }
pixelHandler: { _ in },
autoRecoveryHandler: {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is an example of the new handler implementation, ignore the overrideTokenResponse that is used only for testing purposes

/// If the client succeeds in making a refresh request but does not get the response, then the second refresh request will fail with `invalidTokenRequest` and the stored token will become unusable and un-refreshable.
private func throwAppropriateDeadTokenError() async throws -> TokenContainer {
Logger.subscription.fault("Dead token detected")
func attemptTokenRecovery() async throws -> TokenContainer {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is where the autoRecoveryHandler is used

@federicocappelli federicocappelli requested review from miasma13 and removed request for miasma13 February 5, 2025 14:42
Copy link
Contributor

@miasma13 miasma13 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall LGTM, just couple of comments

#if DEBUG
let expiresSoon = false
#else
// Expires in less than 10 minutes, check only in release, the staging token expires every 4 minutes
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think about extracting the "10" into a constant. Also for the DEBUG you could use a different value (2?) there? Logic here would be cleaner and the flow would be dependant on a value.

Sources/Subscription/DeadTokenRecoverer.swift Outdated Show resolved Hide resolved
Sources/Subscription/Managers/SubscriptionManagerV2.swift Outdated Show resolved Hide resolved
Sources/Subscription/Managers/SubscriptionManagerV2.swift Outdated Show resolved Hide resolved
Sources/Subscription/Managers/SubscriptionManagerV2.swift Outdated Show resolved Hide resolved

private static var recoveryAttempted: Int = 0

public static func recoverDeadToken(endpointService: any SubscriptionEndpointServiceV2,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two things:

  1. I am thinking about more descriptive name for it as it does very specific thing. I am missing that this is an attempt (and may fail) and how the recovery is made. Suggestions:
  • attemptDeadTokenRecoveryFromPastPurchase(endpointService: any SubscriptionEndpointServiceV2, restoreFlow: any AppStoreRestoreFlowV2)
  • attemptDeadTokenRecovery(using restoreFlow: any AppStoreRestoreFlowV2, endpointService: any SubscriptionEndpointServiceV2)
  1. To be wary for the "real" implementation if the function can potentially be invoked multiple times in parallel without synchronisation.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. What about DeadTokenRecoverer.attemptRecoveryFromPastPurchase(...)?
  2. In theory, recoveryAttemptCount in the struct is the safeguard for that. Only one recovery operation at the time will be executed, the other ones will throw a .tokenUnRefreshable

@federicocappelli federicocappelli merged commit 7ceea51 into main Feb 7, 2025
7 checks passed
@federicocappelli federicocappelli deleted the fcappelli/Refresh_Token_Expired branch February 7, 2025 05:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants