1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/mobile/android/base/fxa/authenticator/AndroidFxAccount.java Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,549 @@ 1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public 1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this 1.6 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.7 + 1.8 +package org.mozilla.gecko.fxa.authenticator; 1.9 + 1.10 +import java.io.UnsupportedEncodingException; 1.11 +import java.net.URISyntaxException; 1.12 +import java.security.GeneralSecurityException; 1.13 +import java.util.ArrayList; 1.14 +import java.util.Arrays; 1.15 +import java.util.Collections; 1.16 +import java.util.EnumSet; 1.17 +import java.util.List; 1.18 + 1.19 +import org.mozilla.gecko.background.common.GlobalConstants; 1.20 +import org.mozilla.gecko.background.common.log.Logger; 1.21 +import org.mozilla.gecko.background.fxa.FxAccountUtils; 1.22 +import org.mozilla.gecko.db.BrowserContract; 1.23 +import org.mozilla.gecko.fxa.FirefoxAccounts; 1.24 +import org.mozilla.gecko.fxa.FxAccountConstants; 1.25 +import org.mozilla.gecko.fxa.login.State; 1.26 +import org.mozilla.gecko.fxa.login.State.StateLabel; 1.27 +import org.mozilla.gecko.fxa.login.StateFactory; 1.28 +import org.mozilla.gecko.sync.ExtendedJSONObject; 1.29 +import org.mozilla.gecko.sync.Utils; 1.30 + 1.31 +import android.accounts.Account; 1.32 +import android.accounts.AccountManager; 1.33 +import android.content.ContentResolver; 1.34 +import android.content.Context; 1.35 +import android.content.Intent; 1.36 +import android.content.SharedPreferences; 1.37 +import android.os.Bundle; 1.38 + 1.39 +/** 1.40 + * A Firefox Account that stores its details and state as user data attached to 1.41 + * an Android Account instance. 1.42 + * <p> 1.43 + * Account user data is accessible only to the Android App(s) that own the 1.44 + * Account type. Account user data is not removed when the App's private data is 1.45 + * cleared. 1.46 + */ 1.47 +public class AndroidFxAccount { 1.48 + protected static final String LOG_TAG = AndroidFxAccount.class.getSimpleName(); 1.49 + 1.50 + public static final int CURRENT_PREFS_VERSION = 1; 1.51 + 1.52 + // When updating the account, do not forget to update AccountPickler. 1.53 + public static final int CURRENT_ACCOUNT_VERSION = 3; 1.54 + public static final String ACCOUNT_KEY_ACCOUNT_VERSION = "version"; 1.55 + public static final String ACCOUNT_KEY_PROFILE = "profile"; 1.56 + public static final String ACCOUNT_KEY_IDP_SERVER = "idpServerURI"; 1.57 + 1.58 + // The audience should always be a prefix of the token server URI. 1.59 + public static final String ACCOUNT_KEY_AUDIENCE = "audience"; // Sync-specific. 1.60 + public static final String ACCOUNT_KEY_TOKEN_SERVER = "tokenServerURI"; // Sync-specific. 1.61 + public static final String ACCOUNT_KEY_DESCRIPTOR = "descriptor"; 1.62 + 1.63 + public static final int CURRENT_BUNDLE_VERSION = 2; 1.64 + public static final String BUNDLE_KEY_BUNDLE_VERSION = "version"; 1.65 + public static final String BUNDLE_KEY_STATE_LABEL = "stateLabel"; 1.66 + public static final String BUNDLE_KEY_STATE = "state"; 1.67 + 1.68 + protected static final List<String> ANDROID_AUTHORITIES = Collections.unmodifiableList(Arrays.asList( 1.69 + new String[] { BrowserContract.AUTHORITY })); 1.70 + 1.71 + protected final Context context; 1.72 + protected final AccountManager accountManager; 1.73 + protected final Account account; 1.74 + 1.75 + /** 1.76 + * Create an Android Firefox Account instance backed by an Android Account 1.77 + * instance. 1.78 + * <p> 1.79 + * We expect a long-lived application context to avoid life-cycle issues that 1.80 + * might arise if the internally cached AccountManager instance surfaces UI. 1.81 + * <p> 1.82 + * We take care to not install any listeners or observers that might outlive 1.83 + * the AccountManager; and Android ensures the AccountManager doesn't outlive 1.84 + * the associated context. 1.85 + * 1.86 + * @param applicationContext 1.87 + * to use as long-lived ambient Android context. 1.88 + * @param account 1.89 + * Android account to use for storage. 1.90 + */ 1.91 + public AndroidFxAccount(Context applicationContext, Account account) { 1.92 + this.context = applicationContext; 1.93 + this.account = account; 1.94 + this.accountManager = AccountManager.get(this.context); 1.95 + } 1.96 + 1.97 + /** 1.98 + * Persist the Firefox account to disk as a JSON object. Note that this is a wrapper around 1.99 + * {@link AccountPickler#pickle}, and is identical to calling it directly. 1.100 + * <p> 1.101 + * Note that pickling is different from bundling, which involves operations on a 1.102 + * {@link android.os.Bundle Bundle} object of miscellaenous data associated with the account. 1.103 + * See {@link #persistBundle} and {@link #unbundle} for more. 1.104 + */ 1.105 + public void pickle(final String filename) { 1.106 + AccountPickler.pickle(this, filename); 1.107 + } 1.108 + 1.109 + public Account getAndroidAccount() { 1.110 + return this.account; 1.111 + } 1.112 + 1.113 + protected int getAccountVersion() { 1.114 + String v = accountManager.getUserData(account, ACCOUNT_KEY_ACCOUNT_VERSION); 1.115 + if (v == null) { 1.116 + return 0; // Implicit. 1.117 + } 1.118 + 1.119 + try { 1.120 + return Integer.parseInt(v, 10); 1.121 + } catch (NumberFormatException ex) { 1.122 + return 0; 1.123 + } 1.124 + } 1.125 + 1.126 + /** 1.127 + * Saves the given data as the internal bundle associated with this account. 1.128 + * @param bundle to write to account. 1.129 + */ 1.130 + protected void persistBundle(ExtendedJSONObject bundle) { 1.131 + accountManager.setUserData(account, ACCOUNT_KEY_DESCRIPTOR, bundle.toJSONString()); 1.132 + } 1.133 + 1.134 + /** 1.135 + * Retrieve the internal bundle associated with this account. 1.136 + * @return bundle associated with account. 1.137 + */ 1.138 + protected ExtendedJSONObject unbundle() { 1.139 + final int version = getAccountVersion(); 1.140 + if (version < CURRENT_ACCOUNT_VERSION) { 1.141 + // Needs upgrade. For now, do nothing. We'd like to just put your account 1.142 + // into the Separated state here and have you update your credentials. 1.143 + return null; 1.144 + } 1.145 + 1.146 + if (version > CURRENT_ACCOUNT_VERSION) { 1.147 + // Oh dear. 1.148 + return null; 1.149 + } 1.150 + 1.151 + String bundle = accountManager.getUserData(account, ACCOUNT_KEY_DESCRIPTOR); 1.152 + if (bundle == null) { 1.153 + return null; 1.154 + } 1.155 + return unbundleAccountV2(bundle); 1.156 + } 1.157 + 1.158 + protected String getBundleData(String key) { 1.159 + ExtendedJSONObject o = unbundle(); 1.160 + if (o == null) { 1.161 + return null; 1.162 + } 1.163 + return o.getString(key); 1.164 + } 1.165 + 1.166 + protected boolean getBundleDataBoolean(String key, boolean def) { 1.167 + ExtendedJSONObject o = unbundle(); 1.168 + if (o == null) { 1.169 + return def; 1.170 + } 1.171 + Boolean b = o.getBoolean(key); 1.172 + if (b == null) { 1.173 + return def; 1.174 + } 1.175 + return b.booleanValue(); 1.176 + } 1.177 + 1.178 + protected byte[] getBundleDataBytes(String key) { 1.179 + ExtendedJSONObject o = unbundle(); 1.180 + if (o == null) { 1.181 + return null; 1.182 + } 1.183 + return o.getByteArrayHex(key); 1.184 + } 1.185 + 1.186 + protected void updateBundleDataBytes(String key, byte[] value) { 1.187 + updateBundleValue(key, value == null ? null : Utils.byte2Hex(value)); 1.188 + } 1.189 + 1.190 + protected void updateBundleValue(String key, boolean value) { 1.191 + ExtendedJSONObject descriptor = unbundle(); 1.192 + if (descriptor == null) { 1.193 + return; 1.194 + } 1.195 + descriptor.put(key, value); 1.196 + persistBundle(descriptor); 1.197 + } 1.198 + 1.199 + protected void updateBundleValue(String key, String value) { 1.200 + ExtendedJSONObject descriptor = unbundle(); 1.201 + if (descriptor == null) { 1.202 + return; 1.203 + } 1.204 + descriptor.put(key, value); 1.205 + persistBundle(descriptor); 1.206 + } 1.207 + 1.208 + private ExtendedJSONObject unbundleAccountV1(String bundle) { 1.209 + ExtendedJSONObject o; 1.210 + try { 1.211 + o = new ExtendedJSONObject(bundle); 1.212 + } catch (Exception e) { 1.213 + return null; 1.214 + } 1.215 + if (CURRENT_BUNDLE_VERSION == o.getIntegerSafely(BUNDLE_KEY_BUNDLE_VERSION)) { 1.216 + return o; 1.217 + } 1.218 + return null; 1.219 + } 1.220 + 1.221 + private ExtendedJSONObject unbundleAccountV2(String bundle) { 1.222 + return unbundleAccountV1(bundle); 1.223 + } 1.224 + 1.225 + /** 1.226 + * Note that if the user clears data, an account will be left pointing to a 1.227 + * deleted profile. Such is life. 1.228 + */ 1.229 + public String getProfile() { 1.230 + return accountManager.getUserData(account, ACCOUNT_KEY_PROFILE); 1.231 + } 1.232 + 1.233 + public String getAccountServerURI() { 1.234 + return accountManager.getUserData(account, ACCOUNT_KEY_IDP_SERVER); 1.235 + } 1.236 + 1.237 + public String getAudience() { 1.238 + return accountManager.getUserData(account, ACCOUNT_KEY_AUDIENCE); 1.239 + } 1.240 + 1.241 + public String getTokenServerURI() { 1.242 + return accountManager.getUserData(account, ACCOUNT_KEY_TOKEN_SERVER); 1.243 + } 1.244 + 1.245 + /** 1.246 + * This needs to return a string because of the tortured prefs access in GlobalSession. 1.247 + */ 1.248 + public String getSyncPrefsPath() throws GeneralSecurityException, UnsupportedEncodingException { 1.249 + String profile = getProfile(); 1.250 + String username = account.name; 1.251 + 1.252 + if (profile == null) { 1.253 + throw new IllegalStateException("Missing profile. Cannot fetch prefs."); 1.254 + } 1.255 + 1.256 + if (username == null) { 1.257 + throw new IllegalStateException("Missing username. Cannot fetch prefs."); 1.258 + } 1.259 + 1.260 + final String tokenServerURI = getTokenServerURI(); 1.261 + if (tokenServerURI == null) { 1.262 + throw new IllegalStateException("No token server URI. Cannot fetch prefs."); 1.263 + } 1.264 + 1.265 + final String fxaServerURI = getAccountServerURI(); 1.266 + if (fxaServerURI == null) { 1.267 + throw new IllegalStateException("No account server URI. Cannot fetch prefs."); 1.268 + } 1.269 + 1.270 + final String product = GlobalConstants.BROWSER_INTENT_PACKAGE + ".fxa"; 1.271 + final long version = CURRENT_PREFS_VERSION; 1.272 + 1.273 + // This is unique for each syncing 'view' of the account. 1.274 + final String serverURLThing = fxaServerURI + "!" + tokenServerURI; 1.275 + return Utils.getPrefsPath(product, username, serverURLThing, profile, version); 1.276 + } 1.277 + 1.278 + public SharedPreferences getSyncPrefs() throws UnsupportedEncodingException, GeneralSecurityException { 1.279 + return context.getSharedPreferences(getSyncPrefsPath(), Utils.SHARED_PREFERENCES_MODE); 1.280 + } 1.281 + 1.282 + /** 1.283 + * Extract a JSON dictionary of the string values associated to this account. 1.284 + * <p> 1.285 + * <b>For debugging use only!</b> The contents of this JSON object completely 1.286 + * determine the user's Firefox Account status and yield access to whatever 1.287 + * user data the device has access to. 1.288 + * 1.289 + * @return JSON-object of Strings. 1.290 + */ 1.291 + public ExtendedJSONObject toJSONObject() { 1.292 + ExtendedJSONObject o = unbundle(); 1.293 + o.put("email", account.name); 1.294 + try { 1.295 + o.put("emailUTF8", Utils.byte2Hex(account.name.getBytes("UTF-8"))); 1.296 + } catch (UnsupportedEncodingException e) { 1.297 + // Ignore. 1.298 + } 1.299 + return o; 1.300 + } 1.301 + 1.302 + public static AndroidFxAccount addAndroidAccount( 1.303 + Context context, 1.304 + String email, 1.305 + String profile, 1.306 + String idpServerURI, 1.307 + String tokenServerURI, 1.308 + State state) 1.309 + throws UnsupportedEncodingException, GeneralSecurityException, URISyntaxException { 1.310 + return addAndroidAccount(context, email, profile, idpServerURI, tokenServerURI, state, 1.311 + CURRENT_ACCOUNT_VERSION, true, false, null); 1.312 + } 1.313 + 1.314 + public static AndroidFxAccount addAndroidAccount( 1.315 + Context context, 1.316 + String email, 1.317 + String profile, 1.318 + String idpServerURI, 1.319 + String tokenServerURI, 1.320 + State state, 1.321 + final int accountVersion, 1.322 + final boolean syncEnabled, 1.323 + final boolean fromPickle, 1.324 + ExtendedJSONObject bundle) 1.325 + throws UnsupportedEncodingException, GeneralSecurityException, URISyntaxException { 1.326 + if (email == null) { 1.327 + throw new IllegalArgumentException("email must not be null"); 1.328 + } 1.329 + if (idpServerURI == null) { 1.330 + throw new IllegalArgumentException("idpServerURI must not be null"); 1.331 + } 1.332 + if (tokenServerURI == null) { 1.333 + throw new IllegalArgumentException("tokenServerURI must not be null"); 1.334 + } 1.335 + if (state == null) { 1.336 + throw new IllegalArgumentException("state must not be null"); 1.337 + } 1.338 + 1.339 + // TODO: Add migration code. 1.340 + if (accountVersion != CURRENT_ACCOUNT_VERSION) { 1.341 + throw new IllegalStateException("Could not create account of version " + accountVersion + 1.342 + ". Current version is " + CURRENT_ACCOUNT_VERSION + "."); 1.343 + } 1.344 + 1.345 + // Android has internal restrictions that require all values in this 1.346 + // bundle to be strings. *sigh* 1.347 + Bundle userdata = new Bundle(); 1.348 + userdata.putString(ACCOUNT_KEY_ACCOUNT_VERSION, "" + CURRENT_ACCOUNT_VERSION); 1.349 + userdata.putString(ACCOUNT_KEY_IDP_SERVER, idpServerURI); 1.350 + userdata.putString(ACCOUNT_KEY_TOKEN_SERVER, tokenServerURI); 1.351 + userdata.putString(ACCOUNT_KEY_AUDIENCE, FxAccountUtils.getAudienceForURL(tokenServerURI)); 1.352 + userdata.putString(ACCOUNT_KEY_PROFILE, profile); 1.353 + 1.354 + if (bundle == null) { 1.355 + bundle = new ExtendedJSONObject(); 1.356 + // TODO: How to upgrade? 1.357 + bundle.put(BUNDLE_KEY_BUNDLE_VERSION, CURRENT_BUNDLE_VERSION); 1.358 + } 1.359 + bundle.put(BUNDLE_KEY_STATE_LABEL, state.getStateLabel().name()); 1.360 + bundle.put(BUNDLE_KEY_STATE, state.toJSONObject().toJSONString()); 1.361 + 1.362 + userdata.putString(ACCOUNT_KEY_DESCRIPTOR, bundle.toJSONString()); 1.363 + 1.364 + Account account = new Account(email, FxAccountConstants.ACCOUNT_TYPE); 1.365 + AccountManager accountManager = AccountManager.get(context); 1.366 + // We don't set an Android password, because we don't want to persist the 1.367 + // password (or anything else as powerful as the password). Instead, we 1.368 + // internally manage a sessionToken with a remotely owned lifecycle. 1.369 + boolean added = accountManager.addAccountExplicitly(account, null, userdata); 1.370 + if (!added) { 1.371 + return null; 1.372 + } 1.373 + 1.374 + AndroidFxAccount fxAccount = new AndroidFxAccount(context, account); 1.375 + 1.376 + if (!fromPickle) { 1.377 + fxAccount.clearSyncPrefs(); 1.378 + } 1.379 + 1.380 + if (syncEnabled) { 1.381 + fxAccount.enableSyncing(); 1.382 + } else { 1.383 + fxAccount.disableSyncing(); 1.384 + } 1.385 + 1.386 + return fxAccount; 1.387 + } 1.388 + 1.389 + public void clearSyncPrefs() throws UnsupportedEncodingException, GeneralSecurityException { 1.390 + getSyncPrefs().edit().clear().commit(); 1.391 + } 1.392 + 1.393 + public static Iterable<String> getAndroidAuthorities() { 1.394 + return ANDROID_AUTHORITIES; 1.395 + } 1.396 + 1.397 + /** 1.398 + * Return true if the underlying Android account is currently set to sync automatically. 1.399 + * <p> 1.400 + * This is, confusingly, not the same thing as "being syncable": that refers 1.401 + * to whether this account can be synced, ever; this refers to whether Android 1.402 + * will try to sync the account at appropriate times. 1.403 + * 1.404 + * @return true if the account is set to sync automatically. 1.405 + */ 1.406 + public boolean isSyncing() { 1.407 + boolean isSyncEnabled = true; 1.408 + for (String authority : getAndroidAuthorities()) { 1.409 + isSyncEnabled &= ContentResolver.getSyncAutomatically(account, authority); 1.410 + } 1.411 + return isSyncEnabled; 1.412 + } 1.413 + 1.414 + public void enableSyncing() { 1.415 + Logger.info(LOG_TAG, "Enabling sync for account named like " + getObfuscatedEmail()); 1.416 + for (String authority : getAndroidAuthorities()) { 1.417 + ContentResolver.setSyncAutomatically(account, authority, true); 1.418 + ContentResolver.setIsSyncable(account, authority, 1); 1.419 + } 1.420 + } 1.421 + 1.422 + public void disableSyncing() { 1.423 + Logger.info(LOG_TAG, "Disabling sync for account named like " + getObfuscatedEmail()); 1.424 + for (String authority : getAndroidAuthorities()) { 1.425 + ContentResolver.setSyncAutomatically(account, authority, false); 1.426 + } 1.427 + } 1.428 + 1.429 + /** 1.430 + * Is a sync currently in progress? 1.431 + * 1.432 + * @return true if Android is currently syncing the underlying Android Account. 1.433 + */ 1.434 + public boolean isCurrentlySyncing() { 1.435 + boolean active = false; 1.436 + for (String authority : AndroidFxAccount.getAndroidAuthorities()) { 1.437 + active |= ContentResolver.isSyncActive(account, authority); 1.438 + } 1.439 + return active; 1.440 + } 1.441 + 1.442 + /** 1.443 + * Request a sync. See {@link FirefoxAccounts#requestSync(Account, EnumSet, String[], String[])}. 1.444 + */ 1.445 + public void requestSync() { 1.446 + requestSync(FirefoxAccounts.SOON, null, null); 1.447 + } 1.448 + 1.449 + /** 1.450 + * Request a sync. See {@link FirefoxAccounts#requestSync(Account, EnumSet, String[], String[])}. 1.451 + * 1.452 + * @param syncHints to pass to sync. 1.453 + */ 1.454 + public void requestSync(EnumSet<FirefoxAccounts.SyncHint> syncHints) { 1.455 + requestSync(syncHints, null, null); 1.456 + } 1.457 + 1.458 + /** 1.459 + * Request a sync. See {@link FirefoxAccounts#requestSync(Account, EnumSet, String[], String[])}. 1.460 + * 1.461 + * @param syncHints to pass to sync. 1.462 + * @param stagesToSync stage names to sync. 1.463 + * @param stagesToSkip stage names to skip. 1.464 + */ 1.465 + public void requestSync(EnumSet<FirefoxAccounts.SyncHint> syncHints, String[] stagesToSync, String[] stagesToSkip) { 1.466 + FirefoxAccounts.requestSync(getAndroidAccount(), syncHints, stagesToSync, stagesToSkip); 1.467 + } 1.468 + 1.469 + public synchronized void setState(State state) { 1.470 + if (state == null) { 1.471 + throw new IllegalArgumentException("state must not be null"); 1.472 + } 1.473 + Logger.info(LOG_TAG, "Moving account named like " + getObfuscatedEmail() + 1.474 + " to state " + state.getStateLabel().toString()); 1.475 + updateBundleValue(BUNDLE_KEY_STATE_LABEL, state.getStateLabel().name()); 1.476 + updateBundleValue(BUNDLE_KEY_STATE, state.toJSONObject().toJSONString()); 1.477 + } 1.478 + 1.479 + public synchronized State getState() { 1.480 + String stateLabelString = getBundleData(BUNDLE_KEY_STATE_LABEL); 1.481 + String stateString = getBundleData(BUNDLE_KEY_STATE); 1.482 + if (stateLabelString == null) { 1.483 + throw new IllegalStateException("stateLabelString must not be null"); 1.484 + } 1.485 + if (stateString == null) { 1.486 + throw new IllegalStateException("stateString must not be null"); 1.487 + } 1.488 + 1.489 + try { 1.490 + StateLabel stateLabel = StateLabel.valueOf(stateLabelString); 1.491 + return StateFactory.fromJSONObject(stateLabel, new ExtendedJSONObject(stateString)); 1.492 + } catch (Exception e) { 1.493 + throw new IllegalStateException("could not get state", e); 1.494 + } 1.495 + } 1.496 + 1.497 + /** 1.498 + * <b>For debugging only!</b> 1.499 + */ 1.500 + public void dump() { 1.501 + if (!FxAccountConstants.LOG_PERSONAL_INFORMATION) { 1.502 + return; 1.503 + } 1.504 + ExtendedJSONObject o = toJSONObject(); 1.505 + ArrayList<String> list = new ArrayList<String>(o.keySet()); 1.506 + Collections.sort(list); 1.507 + for (String key : list) { 1.508 + FxAccountConstants.pii(LOG_TAG, key + ": " + o.get(key)); 1.509 + } 1.510 + } 1.511 + 1.512 + /** 1.513 + * Return the Firefox Account's local email address. 1.514 + * <p> 1.515 + * It is important to note that this is the local email address, and not 1.516 + * necessarily the normalized remote email address that the server expects. 1.517 + * 1.518 + * @return local email address. 1.519 + */ 1.520 + public String getEmail() { 1.521 + return account.name; 1.522 + } 1.523 + 1.524 + /** 1.525 + * Return the Firefox Account's local email address, obfuscated. 1.526 + * <p> 1.527 + * Use this when logging. 1.528 + * 1.529 + * @return local email address, obfuscated. 1.530 + */ 1.531 + public String getObfuscatedEmail() { 1.532 + return Utils.obfuscateEmail(account.name); 1.533 + } 1.534 + 1.535 + /** 1.536 + * Create an intent announcing that a Firefox account will be deleted. 1.537 + * 1.538 + * @param context 1.539 + * Android context. 1.540 + * @param account 1.541 + * Android account being removed. 1.542 + * @return <code>Intent</code> to broadcast. 1.543 + */ 1.544 + public static Intent makeDeletedAccountIntent(final Context context, final Account account) { 1.545 + final Intent intent = new Intent(FxAccountConstants.ACCOUNT_DELETED_ACTION); 1.546 + 1.547 + intent.putExtra(FxAccountConstants.ACCOUNT_DELETED_INTENT_VERSION_KEY, 1.548 + Long.valueOf(FxAccountConstants.ACCOUNT_DELETED_INTENT_VERSION)); 1.549 + intent.putExtra(FxAccountConstants.ACCOUNT_DELETED_INTENT_ACCOUNT_KEY, account.name); 1.550 + return intent; 1.551 + } 1.552 +}