Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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 @@ -43,6 +43,7 @@ public class IterableApi {
private IterableNotificationData _notificationData;
private String _deviceId;
private boolean _firstForegroundHandled;
private boolean _autoRetryOnJwtFailure;
private IterableHelper.SuccessHandler _setUserSuccessCallbackHandler;
private IterableHelper.FailureHandler _setUserFailureCallbackHandler;

Expand Down Expand Up @@ -104,6 +105,14 @@ public void execute(@Nullable String data) {
SharedPreferences sharedPref = sharedInstance.getMainActivityContext().getSharedPreferences(IterableConstants.SHARED_PREFS_SAVED_CONFIGURATION, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(IterableConstants.SHARED_PREFS_OFFLINE_MODE_KEY, offlineConfiguration);

// Parse autoRetry flag from remote config. If not present, fall back to local config.
if (jsonData.has(IterableConstants.KEY_AUTO_RETRY)) {
boolean autoRetryRemote = jsonData.getBoolean(IterableConstants.KEY_AUTO_RETRY);
editor.putBoolean(IterableConstants.SHARED_PREFS_AUTO_RETRY_KEY, autoRetryRemote);
_autoRetryOnJwtFailure = autoRetryRemote;
}

editor.apply();
} catch (JSONException e) {
IterableLogger.e(TAG, "Failed to read remote configuration");
Expand Down Expand Up @@ -194,6 +203,22 @@ static void loadLastSavedConfiguration(Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(IterableConstants.SHARED_PREFS_SAVED_CONFIGURATION, Context.MODE_PRIVATE);
boolean offlineMode = sharedPref.getBoolean(IterableConstants.SHARED_PREFS_OFFLINE_MODE_KEY, false);
sharedInstance.apiClient.setOfflineProcessingEnabled(offlineMode);

// Load autoRetry: if a remote value was previously saved, use it; otherwise fall back to local config.
if (sharedPref.contains(IterableConstants.SHARED_PREFS_AUTO_RETRY_KEY)) {
sharedInstance._autoRetryOnJwtFailure = sharedPref.getBoolean(IterableConstants.SHARED_PREFS_AUTO_RETRY_KEY, false);
} else {
sharedInstance._autoRetryOnJwtFailure = sharedInstance.config.autoRetryOnJwtFailure;
}
}

/**
* Returns whether auto-retry on JWT failure is enabled.
* The remote configuration flag takes precedence when present;
* otherwise the local {@link IterableConfig#autoRetryOnJwtFailure} value is used.
*/
boolean isAutoRetryOnJwtFailure() {
Copy link
Contributor

Choose a reason for hiding this comment

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

is there a reason for it not to be private or public?

return _autoRetryOnJwtFailure;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
Expand All @@ -18,6 +19,25 @@ public class IterableAuthManager implements IterableActivityMonitor.AppStateCall
private static final String TAG = "IterableAuth";
private static final String expirationString = "exp";

/**
* Represents the state of the JWT auth token.
* VALID: Last request succeeded with this token.
* INVALID: A 401 JWT error was received; processing should pause.
* UNKNOWN: A new token was obtained but not yet verified by a request.
*/
enum AuthState {
VALID,
INVALID,
UNKNOWN
}

/**
* Listener interface for components that need to react when a new auth token is ready.
*/
interface AuthTokenReadyListener {
void onAuthTokenReady();
}

private final IterableApi api;
private final IterableAuthHandler authHandler;
private final long expiringAuthTokenRefreshPeriod;
Expand All @@ -34,6 +54,9 @@ public class IterableAuthManager implements IterableActivityMonitor.AppStateCall
private volatile boolean isTimerScheduled;
private volatile boolean isInForeground = true; // Assume foreground initially

private volatile AuthState authState = AuthState.UNKNOWN;
private final ArrayList<AuthTokenReadyListener> authTokenReadyListeners = new ArrayList<>();

private final ExecutorService executor = Executors.newSingleThreadExecutor();

IterableAuthManager(IterableApi api, IterableAuthHandler authHandler, RetryPolicy authRetryPolicy, long expiringAuthTokenRefreshPeriod) {
Expand All @@ -45,6 +68,58 @@ public class IterableAuthManager implements IterableActivityMonitor.AppStateCall
this.activityMonitor.addCallback(this);
}

void addAuthTokenReadyListener(AuthTokenReadyListener listener) {
authTokenReadyListeners.add(listener);
}

void removeAuthTokenReadyListener(AuthTokenReadyListener listener) {
authTokenReadyListeners.remove(listener);
}

/**
* Returns true if the auth token is in a state that allows requests to proceed.
* Requests can proceed when auth state is VALID or UNKNOWN (newly obtained token).
* If no authHandler is configured (JWT not used), this always returns true.
*/
boolean isAuthTokenReady() {
if (authHandler == null) {
return true;
}
return authState != AuthState.INVALID;
}

/**
* Marks the auth token as invalid. Called when a 401 JWT error is received.
*/
void setAuthTokenInvalid() {
setAuthState(AuthState.INVALID);
}

AuthState getAuthState() {
return authState;
}

/**
* Centralized auth state setter. Notifies AuthTokenReadyListeners only when
* transitioning from INVALID to a ready state (UNKNOWN or VALID), which means
* a new token has been obtained after a prior auth failure.
*/
private void setAuthState(AuthState newState) {
AuthState previousState = this.authState;
this.authState = newState;

if (previousState == AuthState.INVALID && newState != AuthState.INVALID) {
notifyAuthTokenReadyListeners();
}
}

private void notifyAuthTokenReadyListeners() {
ArrayList<AuthTokenReadyListener> listenersCopy = new ArrayList<>(authTokenReadyListeners);
for (AuthTokenReadyListener listener : listenersCopy) {
listener.onAuthTokenReady();
}
}

public synchronized void requestNewAuthToken(boolean hasFailedPriorAuth, IterableHelper.SuccessHandler successCallback) {
requestNewAuthToken(hasFailedPriorAuth, successCallback, true);
}
Expand All @@ -61,6 +136,9 @@ void reset() {

void setIsLastAuthTokenValid(boolean isValid) {
isLastAuthTokenValid = isValid;
if (isValid) {
setAuthState(AuthState.VALID);
}
}

void resetRetryCount() {
Expand Down Expand Up @@ -132,6 +210,9 @@ public void run() {

private void handleAuthTokenSuccess(String authToken, IterableHelper.SuccessHandler successCallback) {
if (authToken != null) {
// Token obtained but not yet verified by a request - set state to UNKNOWN.
// setAuthState will notify listeners only if previous state was INVALID.
setAuthState(AuthState.UNKNOWN);
IterableApi.getInstance().setAuthToken(authToken);
queueExpirationRefresh(authToken);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,14 @@ public class IterableConfig {
@Nullable
final IterableAPIMobileFrameworkInfo mobileFrameworkInfo;

/**
* When set to true, the SDK will automatically retry API requests that fail due to
* JWT authentication errors (401). Failed requests are retained in the local DB and
* processing is paused until a valid JWT token is obtained.
* This value can be overridden by the remote configuration flag `autoRetry`.
*/
final boolean autoRetryOnJwtFailure;

/**
* Base URL for Webview content loading. Specifically used to enable CORS for external resources.
* If null or empty, defaults to empty string (original behavior with about:blank origin).
Expand Down Expand Up @@ -183,6 +191,7 @@ private IterableConfig(Builder builder) {
decryptionFailureHandler = builder.decryptionFailureHandler;
mobileFrameworkInfo = builder.mobileFrameworkInfo;
webViewBaseUrl = builder.webViewBaseUrl;
autoRetryOnJwtFailure = builder.autoRetryOnJwtFailure;
}

public static class Builder {
Expand Down Expand Up @@ -211,6 +220,7 @@ public static class Builder {
private IterableIdentityResolution identityResolution = new IterableIdentityResolution();
private IterableUnknownUserHandler iterableUnknownUserHandler;
private String webViewBaseUrl;
private boolean autoRetryOnJwtFailure = false;

public Builder() {}

Expand Down Expand Up @@ -453,6 +463,19 @@ public Builder setMobileFrameworkInfo(@NonNull IterableAPIMobileFrameworkInfo mo
return this;
}

/**
* Enable or disable automatic retry of API requests that fail due to JWT authentication
* errors (401). When enabled, failed requests are retained in the local DB and processing
* is paused until a valid JWT token is obtained.
* This value can be overridden by the remote configuration flag `autoRetry`.
* @param autoRetryOnJwtFailure `true` to enable auto-retry on JWT failure
*/
@NonNull
public Builder setAutoRetryOnJwtFailure(boolean autoRetryOnJwtFailure) {
this.autoRetryOnJwtFailure = autoRetryOnJwtFailure;
return this;
}

/**
* Set the base URL for WebView content loading. Used to enable CORS for external resources.
* If not set or null, defaults to empty string (original behavior with about:blank origin).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ public final class IterableConstants {
public static final String KEY_INBOX_SESSION_ID = "inboxSessionId";
public static final String KEY_EMBEDDED_SESSION_ID = "id";
public static final String KEY_OFFLINE_MODE = "offlineMode";
public static final String KEY_AUTO_RETRY = "autoRetry";
public static final String KEY_FIRETV = "FireTV";
public static final String KEY_CREATE_NEW_FIELDS = "createNewFields";
public static final String KEY_IS_USER_KNOWN = "isUserKnown";
Expand Down Expand Up @@ -130,6 +131,7 @@ public final class IterableConstants {
public static final String SHARED_PREFS_FCM_MIGRATION_DONE_KEY = "itbl_fcm_migration_done";
public static final String SHARED_PREFS_SAVED_CONFIGURATION = "itbl_saved_configuration";
public static final String SHARED_PREFS_OFFLINE_MODE_KEY = "itbl_offline_mode";
public static final String SHARED_PREFS_AUTO_RETRY_KEY = "itbl_auto_retry";
public static final String SHARED_PREFS_EVENT_LIST_KEY = "itbl_event_list";
public static final String SHARED_PREFS_USER_UPDATE_OBJECT_KEY = "itbl_user_update_object";
public static final String SHARED_PREFS_UNKNOWN_SESSIONS = "itbl_unknown_sessions";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
Expand Down Expand Up @@ -153,20 +154,27 @@ static IterableApiResponse executeApiRequest(IterableApiRequest iterableApiReque
// Read the response body
try {
BufferedReader in;
if (responseCode < 400) {
if (responseCode >= 0 && responseCode < 400) {
Copy link
Contributor

Choose a reason for hiding this comment

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

is there a 0 code that can occur?

in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
} else {
in = new BufferedReader(
new InputStreamReader(urlConnection.getErrorStream()));
InputStream errorStream = urlConnection.getErrorStream();
Copy link
Contributor

Choose a reason for hiding this comment

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

Isn't it possible to extract just this flow of getting the resultResult to a helper class? this part is quite verbose

if (errorStream != null) {
in = new BufferedReader(
new InputStreamReader(errorStream));
} else {
in = null;
}
}
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
if (in != null) {
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
requestResult = response.toString();
}
in.close();
requestResult = response.toString();
} catch (IOException e) {
logError(iterableApiRequest, baseUrl, e);
error = e.getMessage();
Expand All @@ -186,13 +194,36 @@ static IterableApiResponse executeApiRequest(IterableApiRequest iterableApiReque
jsonError = e.getMessage();
}

// If getResponseCode() returned -1 (e.g. due to network inspector
// interference) but the response body contains JWT error codes,
// we can infer the actual response was a 401.
if (responseCode == -1 && matchesJWTErrorCodes(jsonResponse)) {
responseCode = 401;
}

// Handle HTTP status codes
if (responseCode == 401) {
if (matchesJWTErrorCodes(jsonResponse)) {
apiResponse = IterableApiResponse.failure(responseCode, requestResult, jsonResponse, "JWT Authorization header error");
IterableApi.getInstance().getAuthManager().handleAuthFailure(iterableApiRequest.authToken, getMappedErrorCodeForMessage(jsonResponse));
// We handle the JWT Retry for both online and offline here rather than handling online request in onPostExecute
requestNewAuthTokenAndRetry(iterableApiRequest);

// [F] When autoRetry is enabled and this is an offline task, skip the inline
// retry. The task stays in the DB and IterableTaskRunner will retry it once
// a valid JWT is obtained via the AuthTokenReadyListener callback.
// For online requests or when autoRetry is disabled, use the existing inline retry.
boolean autoRetry = IterableApi.getInstance().isAutoRetryOnJwtFailure();
if (autoRetry && iterableApiRequest.getProcessorType() == IterableApiRequest.ProcessorType.OFFLINE) {
// Schedule a delayed token refresh (respects retry policy).
// Do NOT retry the request inline -- IterableTaskRunner will handle
// the retry after the AuthTokenReadyListener callback fires.
IterableAuthManager authManager = IterableApi.getInstance().getAuthManager();
authManager.setIsLastAuthTokenValid(false);
long retryInterval = authManager.getNextRetryInterval();
authManager.scheduleAuthTokenRefresh(retryInterval, false, null);
} else {
// Existing behavior: retry request inline after obtaining new token
requestNewAuthTokenAndRetry(iterableApiRequest);
}
} else {
apiResponse = IterableApiResponse.failure(responseCode, requestResult, jsonResponse, "Invalid API Key");
}
Expand Down Expand Up @@ -498,13 +529,27 @@ public JSONObject toJSONObject() throws JSONException {
}

static IterableApiRequest fromJSON(JSONObject jsonData, @Nullable IterableHelper.SuccessHandler onSuccess, @Nullable IterableHelper.FailureHandler onFailure) {
return fromJSON(jsonData, null, onSuccess, onFailure);
}

/**
* Deserializes an IterableApiRequest from JSON.
* @param authTokenOverride If non-null, uses this token instead of the one stored in JSON.
* This allows offline tasks to use the latest auth token rather
* than the stale one captured at queue time.
*/
static IterableApiRequest fromJSON(JSONObject jsonData, @Nullable String authTokenOverride, @Nullable IterableHelper.SuccessHandler onSuccess, @Nullable IterableHelper.FailureHandler onFailure) {
try {
String apikey = jsonData.getString("apiKey");
String resourcePath = jsonData.getString("resourcePath");
String requestType = jsonData.getString("requestType");
String authToken = "";
if (jsonData.has("authToken")) {
String authToken;
if (authTokenOverride != null) {
authToken = authTokenOverride;
} else if (jsonData.has("authToken")) {
authToken = jsonData.getString("authToken");
} else {
authToken = "";
}
JSONObject json = jsonData.getJSONObject("data");
return new IterableApiRequest(apikey, resourcePath, json, requestType, authToken, onSuccess, onFailure);
Expand Down
Loading
Loading