michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: package org.mozilla.gecko.fxa.authenticator; michael@0: michael@0: import java.io.UnsupportedEncodingException; michael@0: import java.net.URISyntaxException; michael@0: import java.security.GeneralSecurityException; michael@0: import java.util.ArrayList; michael@0: import java.util.Arrays; michael@0: import java.util.Collections; michael@0: import java.util.EnumSet; michael@0: import java.util.List; michael@0: michael@0: import org.mozilla.gecko.background.common.GlobalConstants; michael@0: import org.mozilla.gecko.background.common.log.Logger; michael@0: import org.mozilla.gecko.background.fxa.FxAccountUtils; michael@0: import org.mozilla.gecko.db.BrowserContract; michael@0: import org.mozilla.gecko.fxa.FirefoxAccounts; michael@0: import org.mozilla.gecko.fxa.FxAccountConstants; michael@0: import org.mozilla.gecko.fxa.login.State; michael@0: import org.mozilla.gecko.fxa.login.State.StateLabel; michael@0: import org.mozilla.gecko.fxa.login.StateFactory; michael@0: import org.mozilla.gecko.sync.ExtendedJSONObject; michael@0: import org.mozilla.gecko.sync.Utils; michael@0: michael@0: import android.accounts.Account; michael@0: import android.accounts.AccountManager; michael@0: import android.content.ContentResolver; michael@0: import android.content.Context; michael@0: import android.content.Intent; michael@0: import android.content.SharedPreferences; michael@0: import android.os.Bundle; michael@0: michael@0: /** michael@0: * A Firefox Account that stores its details and state as user data attached to michael@0: * an Android Account instance. michael@0: *

michael@0: * Account user data is accessible only to the Android App(s) that own the michael@0: * Account type. Account user data is not removed when the App's private data is michael@0: * cleared. michael@0: */ michael@0: public class AndroidFxAccount { michael@0: protected static final String LOG_TAG = AndroidFxAccount.class.getSimpleName(); michael@0: michael@0: public static final int CURRENT_PREFS_VERSION = 1; michael@0: michael@0: // When updating the account, do not forget to update AccountPickler. michael@0: public static final int CURRENT_ACCOUNT_VERSION = 3; michael@0: public static final String ACCOUNT_KEY_ACCOUNT_VERSION = "version"; michael@0: public static final String ACCOUNT_KEY_PROFILE = "profile"; michael@0: public static final String ACCOUNT_KEY_IDP_SERVER = "idpServerURI"; michael@0: michael@0: // The audience should always be a prefix of the token server URI. michael@0: public static final String ACCOUNT_KEY_AUDIENCE = "audience"; // Sync-specific. michael@0: public static final String ACCOUNT_KEY_TOKEN_SERVER = "tokenServerURI"; // Sync-specific. michael@0: public static final String ACCOUNT_KEY_DESCRIPTOR = "descriptor"; michael@0: michael@0: public static final int CURRENT_BUNDLE_VERSION = 2; michael@0: public static final String BUNDLE_KEY_BUNDLE_VERSION = "version"; michael@0: public static final String BUNDLE_KEY_STATE_LABEL = "stateLabel"; michael@0: public static final String BUNDLE_KEY_STATE = "state"; michael@0: michael@0: protected static final List ANDROID_AUTHORITIES = Collections.unmodifiableList(Arrays.asList( michael@0: new String[] { BrowserContract.AUTHORITY })); michael@0: michael@0: protected final Context context; michael@0: protected final AccountManager accountManager; michael@0: protected final Account account; michael@0: michael@0: /** michael@0: * Create an Android Firefox Account instance backed by an Android Account michael@0: * instance. michael@0: *

michael@0: * We expect a long-lived application context to avoid life-cycle issues that michael@0: * might arise if the internally cached AccountManager instance surfaces UI. michael@0: *

michael@0: * We take care to not install any listeners or observers that might outlive michael@0: * the AccountManager; and Android ensures the AccountManager doesn't outlive michael@0: * the associated context. michael@0: * michael@0: * @param applicationContext michael@0: * to use as long-lived ambient Android context. michael@0: * @param account michael@0: * Android account to use for storage. michael@0: */ michael@0: public AndroidFxAccount(Context applicationContext, Account account) { michael@0: this.context = applicationContext; michael@0: this.account = account; michael@0: this.accountManager = AccountManager.get(this.context); michael@0: } michael@0: michael@0: /** michael@0: * Persist the Firefox account to disk as a JSON object. Note that this is a wrapper around michael@0: * {@link AccountPickler#pickle}, and is identical to calling it directly. michael@0: *

michael@0: * Note that pickling is different from bundling, which involves operations on a michael@0: * {@link android.os.Bundle Bundle} object of miscellaenous data associated with the account. michael@0: * See {@link #persistBundle} and {@link #unbundle} for more. michael@0: */ michael@0: public void pickle(final String filename) { michael@0: AccountPickler.pickle(this, filename); michael@0: } michael@0: michael@0: public Account getAndroidAccount() { michael@0: return this.account; michael@0: } michael@0: michael@0: protected int getAccountVersion() { michael@0: String v = accountManager.getUserData(account, ACCOUNT_KEY_ACCOUNT_VERSION); michael@0: if (v == null) { michael@0: return 0; // Implicit. michael@0: } michael@0: michael@0: try { michael@0: return Integer.parseInt(v, 10); michael@0: } catch (NumberFormatException ex) { michael@0: return 0; michael@0: } michael@0: } michael@0: michael@0: /** michael@0: * Saves the given data as the internal bundle associated with this account. michael@0: * @param bundle to write to account. michael@0: */ michael@0: protected void persistBundle(ExtendedJSONObject bundle) { michael@0: accountManager.setUserData(account, ACCOUNT_KEY_DESCRIPTOR, bundle.toJSONString()); michael@0: } michael@0: michael@0: /** michael@0: * Retrieve the internal bundle associated with this account. michael@0: * @return bundle associated with account. michael@0: */ michael@0: protected ExtendedJSONObject unbundle() { michael@0: final int version = getAccountVersion(); michael@0: if (version < CURRENT_ACCOUNT_VERSION) { michael@0: // Needs upgrade. For now, do nothing. We'd like to just put your account michael@0: // into the Separated state here and have you update your credentials. michael@0: return null; michael@0: } michael@0: michael@0: if (version > CURRENT_ACCOUNT_VERSION) { michael@0: // Oh dear. michael@0: return null; michael@0: } michael@0: michael@0: String bundle = accountManager.getUserData(account, ACCOUNT_KEY_DESCRIPTOR); michael@0: if (bundle == null) { michael@0: return null; michael@0: } michael@0: return unbundleAccountV2(bundle); michael@0: } michael@0: michael@0: protected String getBundleData(String key) { michael@0: ExtendedJSONObject o = unbundle(); michael@0: if (o == null) { michael@0: return null; michael@0: } michael@0: return o.getString(key); michael@0: } michael@0: michael@0: protected boolean getBundleDataBoolean(String key, boolean def) { michael@0: ExtendedJSONObject o = unbundle(); michael@0: if (o == null) { michael@0: return def; michael@0: } michael@0: Boolean b = o.getBoolean(key); michael@0: if (b == null) { michael@0: return def; michael@0: } michael@0: return b.booleanValue(); michael@0: } michael@0: michael@0: protected byte[] getBundleDataBytes(String key) { michael@0: ExtendedJSONObject o = unbundle(); michael@0: if (o == null) { michael@0: return null; michael@0: } michael@0: return o.getByteArrayHex(key); michael@0: } michael@0: michael@0: protected void updateBundleDataBytes(String key, byte[] value) { michael@0: updateBundleValue(key, value == null ? null : Utils.byte2Hex(value)); michael@0: } michael@0: michael@0: protected void updateBundleValue(String key, boolean value) { michael@0: ExtendedJSONObject descriptor = unbundle(); michael@0: if (descriptor == null) { michael@0: return; michael@0: } michael@0: descriptor.put(key, value); michael@0: persistBundle(descriptor); michael@0: } michael@0: michael@0: protected void updateBundleValue(String key, String value) { michael@0: ExtendedJSONObject descriptor = unbundle(); michael@0: if (descriptor == null) { michael@0: return; michael@0: } michael@0: descriptor.put(key, value); michael@0: persistBundle(descriptor); michael@0: } michael@0: michael@0: private ExtendedJSONObject unbundleAccountV1(String bundle) { michael@0: ExtendedJSONObject o; michael@0: try { michael@0: o = new ExtendedJSONObject(bundle); michael@0: } catch (Exception e) { michael@0: return null; michael@0: } michael@0: if (CURRENT_BUNDLE_VERSION == o.getIntegerSafely(BUNDLE_KEY_BUNDLE_VERSION)) { michael@0: return o; michael@0: } michael@0: return null; michael@0: } michael@0: michael@0: private ExtendedJSONObject unbundleAccountV2(String bundle) { michael@0: return unbundleAccountV1(bundle); michael@0: } michael@0: michael@0: /** michael@0: * Note that if the user clears data, an account will be left pointing to a michael@0: * deleted profile. Such is life. michael@0: */ michael@0: public String getProfile() { michael@0: return accountManager.getUserData(account, ACCOUNT_KEY_PROFILE); michael@0: } michael@0: michael@0: public String getAccountServerURI() { michael@0: return accountManager.getUserData(account, ACCOUNT_KEY_IDP_SERVER); michael@0: } michael@0: michael@0: public String getAudience() { michael@0: return accountManager.getUserData(account, ACCOUNT_KEY_AUDIENCE); michael@0: } michael@0: michael@0: public String getTokenServerURI() { michael@0: return accountManager.getUserData(account, ACCOUNT_KEY_TOKEN_SERVER); michael@0: } michael@0: michael@0: /** michael@0: * This needs to return a string because of the tortured prefs access in GlobalSession. michael@0: */ michael@0: public String getSyncPrefsPath() throws GeneralSecurityException, UnsupportedEncodingException { michael@0: String profile = getProfile(); michael@0: String username = account.name; michael@0: michael@0: if (profile == null) { michael@0: throw new IllegalStateException("Missing profile. Cannot fetch prefs."); michael@0: } michael@0: michael@0: if (username == null) { michael@0: throw new IllegalStateException("Missing username. Cannot fetch prefs."); michael@0: } michael@0: michael@0: final String tokenServerURI = getTokenServerURI(); michael@0: if (tokenServerURI == null) { michael@0: throw new IllegalStateException("No token server URI. Cannot fetch prefs."); michael@0: } michael@0: michael@0: final String fxaServerURI = getAccountServerURI(); michael@0: if (fxaServerURI == null) { michael@0: throw new IllegalStateException("No account server URI. Cannot fetch prefs."); michael@0: } michael@0: michael@0: final String product = GlobalConstants.BROWSER_INTENT_PACKAGE + ".fxa"; michael@0: final long version = CURRENT_PREFS_VERSION; michael@0: michael@0: // This is unique for each syncing 'view' of the account. michael@0: final String serverURLThing = fxaServerURI + "!" + tokenServerURI; michael@0: return Utils.getPrefsPath(product, username, serverURLThing, profile, version); michael@0: } michael@0: michael@0: public SharedPreferences getSyncPrefs() throws UnsupportedEncodingException, GeneralSecurityException { michael@0: return context.getSharedPreferences(getSyncPrefsPath(), Utils.SHARED_PREFERENCES_MODE); michael@0: } michael@0: michael@0: /** michael@0: * Extract a JSON dictionary of the string values associated to this account. michael@0: *

michael@0: * For debugging use only! The contents of this JSON object completely michael@0: * determine the user's Firefox Account status and yield access to whatever michael@0: * user data the device has access to. michael@0: * michael@0: * @return JSON-object of Strings. michael@0: */ michael@0: public ExtendedJSONObject toJSONObject() { michael@0: ExtendedJSONObject o = unbundle(); michael@0: o.put("email", account.name); michael@0: try { michael@0: o.put("emailUTF8", Utils.byte2Hex(account.name.getBytes("UTF-8"))); michael@0: } catch (UnsupportedEncodingException e) { michael@0: // Ignore. michael@0: } michael@0: return o; michael@0: } michael@0: michael@0: public static AndroidFxAccount addAndroidAccount( michael@0: Context context, michael@0: String email, michael@0: String profile, michael@0: String idpServerURI, michael@0: String tokenServerURI, michael@0: State state) michael@0: throws UnsupportedEncodingException, GeneralSecurityException, URISyntaxException { michael@0: return addAndroidAccount(context, email, profile, idpServerURI, tokenServerURI, state, michael@0: CURRENT_ACCOUNT_VERSION, true, false, null); michael@0: } michael@0: michael@0: public static AndroidFxAccount addAndroidAccount( michael@0: Context context, michael@0: String email, michael@0: String profile, michael@0: String idpServerURI, michael@0: String tokenServerURI, michael@0: State state, michael@0: final int accountVersion, michael@0: final boolean syncEnabled, michael@0: final boolean fromPickle, michael@0: ExtendedJSONObject bundle) michael@0: throws UnsupportedEncodingException, GeneralSecurityException, URISyntaxException { michael@0: if (email == null) { michael@0: throw new IllegalArgumentException("email must not be null"); michael@0: } michael@0: if (idpServerURI == null) { michael@0: throw new IllegalArgumentException("idpServerURI must not be null"); michael@0: } michael@0: if (tokenServerURI == null) { michael@0: throw new IllegalArgumentException("tokenServerURI must not be null"); michael@0: } michael@0: if (state == null) { michael@0: throw new IllegalArgumentException("state must not be null"); michael@0: } michael@0: michael@0: // TODO: Add migration code. michael@0: if (accountVersion != CURRENT_ACCOUNT_VERSION) { michael@0: throw new IllegalStateException("Could not create account of version " + accountVersion + michael@0: ". Current version is " + CURRENT_ACCOUNT_VERSION + "."); michael@0: } michael@0: michael@0: // Android has internal restrictions that require all values in this michael@0: // bundle to be strings. *sigh* michael@0: Bundle userdata = new Bundle(); michael@0: userdata.putString(ACCOUNT_KEY_ACCOUNT_VERSION, "" + CURRENT_ACCOUNT_VERSION); michael@0: userdata.putString(ACCOUNT_KEY_IDP_SERVER, idpServerURI); michael@0: userdata.putString(ACCOUNT_KEY_TOKEN_SERVER, tokenServerURI); michael@0: userdata.putString(ACCOUNT_KEY_AUDIENCE, FxAccountUtils.getAudienceForURL(tokenServerURI)); michael@0: userdata.putString(ACCOUNT_KEY_PROFILE, profile); michael@0: michael@0: if (bundle == null) { michael@0: bundle = new ExtendedJSONObject(); michael@0: // TODO: How to upgrade? michael@0: bundle.put(BUNDLE_KEY_BUNDLE_VERSION, CURRENT_BUNDLE_VERSION); michael@0: } michael@0: bundle.put(BUNDLE_KEY_STATE_LABEL, state.getStateLabel().name()); michael@0: bundle.put(BUNDLE_KEY_STATE, state.toJSONObject().toJSONString()); michael@0: michael@0: userdata.putString(ACCOUNT_KEY_DESCRIPTOR, bundle.toJSONString()); michael@0: michael@0: Account account = new Account(email, FxAccountConstants.ACCOUNT_TYPE); michael@0: AccountManager accountManager = AccountManager.get(context); michael@0: // We don't set an Android password, because we don't want to persist the michael@0: // password (or anything else as powerful as the password). Instead, we michael@0: // internally manage a sessionToken with a remotely owned lifecycle. michael@0: boolean added = accountManager.addAccountExplicitly(account, null, userdata); michael@0: if (!added) { michael@0: return null; michael@0: } michael@0: michael@0: AndroidFxAccount fxAccount = new AndroidFxAccount(context, account); michael@0: michael@0: if (!fromPickle) { michael@0: fxAccount.clearSyncPrefs(); michael@0: } michael@0: michael@0: if (syncEnabled) { michael@0: fxAccount.enableSyncing(); michael@0: } else { michael@0: fxAccount.disableSyncing(); michael@0: } michael@0: michael@0: return fxAccount; michael@0: } michael@0: michael@0: public void clearSyncPrefs() throws UnsupportedEncodingException, GeneralSecurityException { michael@0: getSyncPrefs().edit().clear().commit(); michael@0: } michael@0: michael@0: public static Iterable getAndroidAuthorities() { michael@0: return ANDROID_AUTHORITIES; michael@0: } michael@0: michael@0: /** michael@0: * Return true if the underlying Android account is currently set to sync automatically. michael@0: *

michael@0: * This is, confusingly, not the same thing as "being syncable": that refers michael@0: * to whether this account can be synced, ever; this refers to whether Android michael@0: * will try to sync the account at appropriate times. michael@0: * michael@0: * @return true if the account is set to sync automatically. michael@0: */ michael@0: public boolean isSyncing() { michael@0: boolean isSyncEnabled = true; michael@0: for (String authority : getAndroidAuthorities()) { michael@0: isSyncEnabled &= ContentResolver.getSyncAutomatically(account, authority); michael@0: } michael@0: return isSyncEnabled; michael@0: } michael@0: michael@0: public void enableSyncing() { michael@0: Logger.info(LOG_TAG, "Enabling sync for account named like " + getObfuscatedEmail()); michael@0: for (String authority : getAndroidAuthorities()) { michael@0: ContentResolver.setSyncAutomatically(account, authority, true); michael@0: ContentResolver.setIsSyncable(account, authority, 1); michael@0: } michael@0: } michael@0: michael@0: public void disableSyncing() { michael@0: Logger.info(LOG_TAG, "Disabling sync for account named like " + getObfuscatedEmail()); michael@0: for (String authority : getAndroidAuthorities()) { michael@0: ContentResolver.setSyncAutomatically(account, authority, false); michael@0: } michael@0: } michael@0: michael@0: /** michael@0: * Is a sync currently in progress? michael@0: * michael@0: * @return true if Android is currently syncing the underlying Android Account. michael@0: */ michael@0: public boolean isCurrentlySyncing() { michael@0: boolean active = false; michael@0: for (String authority : AndroidFxAccount.getAndroidAuthorities()) { michael@0: active |= ContentResolver.isSyncActive(account, authority); michael@0: } michael@0: return active; michael@0: } michael@0: michael@0: /** michael@0: * Request a sync. See {@link FirefoxAccounts#requestSync(Account, EnumSet, String[], String[])}. michael@0: */ michael@0: public void requestSync() { michael@0: requestSync(FirefoxAccounts.SOON, null, null); michael@0: } michael@0: michael@0: /** michael@0: * Request a sync. See {@link FirefoxAccounts#requestSync(Account, EnumSet, String[], String[])}. michael@0: * michael@0: * @param syncHints to pass to sync. michael@0: */ michael@0: public void requestSync(EnumSet syncHints) { michael@0: requestSync(syncHints, null, null); michael@0: } michael@0: michael@0: /** michael@0: * Request a sync. See {@link FirefoxAccounts#requestSync(Account, EnumSet, String[], String[])}. michael@0: * michael@0: * @param syncHints to pass to sync. michael@0: * @param stagesToSync stage names to sync. michael@0: * @param stagesToSkip stage names to skip. michael@0: */ michael@0: public void requestSync(EnumSet syncHints, String[] stagesToSync, String[] stagesToSkip) { michael@0: FirefoxAccounts.requestSync(getAndroidAccount(), syncHints, stagesToSync, stagesToSkip); michael@0: } michael@0: michael@0: public synchronized void setState(State state) { michael@0: if (state == null) { michael@0: throw new IllegalArgumentException("state must not be null"); michael@0: } michael@0: Logger.info(LOG_TAG, "Moving account named like " + getObfuscatedEmail() + michael@0: " to state " + state.getStateLabel().toString()); michael@0: updateBundleValue(BUNDLE_KEY_STATE_LABEL, state.getStateLabel().name()); michael@0: updateBundleValue(BUNDLE_KEY_STATE, state.toJSONObject().toJSONString()); michael@0: } michael@0: michael@0: public synchronized State getState() { michael@0: String stateLabelString = getBundleData(BUNDLE_KEY_STATE_LABEL); michael@0: String stateString = getBundleData(BUNDLE_KEY_STATE); michael@0: if (stateLabelString == null) { michael@0: throw new IllegalStateException("stateLabelString must not be null"); michael@0: } michael@0: if (stateString == null) { michael@0: throw new IllegalStateException("stateString must not be null"); michael@0: } michael@0: michael@0: try { michael@0: StateLabel stateLabel = StateLabel.valueOf(stateLabelString); michael@0: return StateFactory.fromJSONObject(stateLabel, new ExtendedJSONObject(stateString)); michael@0: } catch (Exception e) { michael@0: throw new IllegalStateException("could not get state", e); michael@0: } michael@0: } michael@0: michael@0: /** michael@0: * For debugging only! michael@0: */ michael@0: public void dump() { michael@0: if (!FxAccountConstants.LOG_PERSONAL_INFORMATION) { michael@0: return; michael@0: } michael@0: ExtendedJSONObject o = toJSONObject(); michael@0: ArrayList list = new ArrayList(o.keySet()); michael@0: Collections.sort(list); michael@0: for (String key : list) { michael@0: FxAccountConstants.pii(LOG_TAG, key + ": " + o.get(key)); michael@0: } michael@0: } michael@0: michael@0: /** michael@0: * Return the Firefox Account's local email address. michael@0: *

michael@0: * It is important to note that this is the local email address, and not michael@0: * necessarily the normalized remote email address that the server expects. michael@0: * michael@0: * @return local email address. michael@0: */ michael@0: public String getEmail() { michael@0: return account.name; michael@0: } michael@0: michael@0: /** michael@0: * Return the Firefox Account's local email address, obfuscated. michael@0: *

michael@0: * Use this when logging. michael@0: * michael@0: * @return local email address, obfuscated. michael@0: */ michael@0: public String getObfuscatedEmail() { michael@0: return Utils.obfuscateEmail(account.name); michael@0: } michael@0: michael@0: /** michael@0: * Create an intent announcing that a Firefox account will be deleted. michael@0: * michael@0: * @param context michael@0: * Android context. michael@0: * @param account michael@0: * Android account being removed. michael@0: * @return Intent to broadcast. michael@0: */ michael@0: public static Intent makeDeletedAccountIntent(final Context context, final Account account) { michael@0: final Intent intent = new Intent(FxAccountConstants.ACCOUNT_DELETED_ACTION); michael@0: michael@0: intent.putExtra(FxAccountConstants.ACCOUNT_DELETED_INTENT_VERSION_KEY, michael@0: Long.valueOf(FxAccountConstants.ACCOUNT_DELETED_INTENT_VERSION)); michael@0: intent.putExtra(FxAccountConstants.ACCOUNT_DELETED_INTENT_ACCOUNT_KEY, account.name); michael@0: return intent; michael@0: } michael@0: }