PageRenderTime 67ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/src/main/java/org/mozilla/gecko/fxa/authenticator/AndroidFxAccount.java

http://github.com/mozilla-services/android-sync
Java | 738 lines | 490 code | 89 blank | 159 comment | 75 complexity | 672bb8b5853d5d61dd26c68ebe3b90e6 MD5 | raw file
Possible License(s): MPL-2.0
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. package org.mozilla.gecko.fxa.authenticator;
  5. import java.io.UnsupportedEncodingException;
  6. import java.net.URISyntaxException;
  7. import java.security.GeneralSecurityException;
  8. import java.util.ArrayList;
  9. import java.util.Collections;
  10. import java.util.EnumSet;
  11. import java.util.HashMap;
  12. import java.util.List;
  13. import java.util.Map;
  14. import java.util.concurrent.ConcurrentHashMap;
  15. import java.util.concurrent.Semaphore;
  16. import org.mozilla.gecko.AppConstants;
  17. import org.mozilla.gecko.background.ReadingListConstants;
  18. import org.mozilla.gecko.background.common.GlobalConstants;
  19. import org.mozilla.gecko.background.common.log.Logger;
  20. import org.mozilla.gecko.background.fxa.FxAccountUtils;
  21. import org.mozilla.gecko.db.BrowserContract;
  22. import org.mozilla.gecko.fxa.FirefoxAccounts;
  23. import org.mozilla.gecko.fxa.FxAccountConstants;
  24. import org.mozilla.gecko.fxa.login.State;
  25. import org.mozilla.gecko.fxa.login.State.StateLabel;
  26. import org.mozilla.gecko.fxa.login.StateFactory;
  27. import org.mozilla.gecko.sync.ExtendedJSONObject;
  28. import org.mozilla.gecko.sync.Utils;
  29. import org.mozilla.gecko.sync.setup.Constants;
  30. import android.accounts.Account;
  31. import android.accounts.AccountManager;
  32. import android.content.ContentResolver;
  33. import android.content.Context;
  34. import android.content.Intent;
  35. import android.content.SharedPreferences;
  36. import android.os.Bundle;
  37. import android.util.Log;
  38. /**
  39. * A Firefox Account that stores its details and state as user data attached to
  40. * an Android Account instance.
  41. * <p>
  42. * Account user data is accessible only to the Android App(s) that own the
  43. * Account type. Account user data is not removed when the App's private data is
  44. * cleared.
  45. */
  46. public class AndroidFxAccount {
  47. protected static final String LOG_TAG = AndroidFxAccount.class.getSimpleName();
  48. public static final int CURRENT_SYNC_PREFS_VERSION = 1;
  49. public static final int CURRENT_RL_PREFS_VERSION = 1;
  50. // When updating the account, do not forget to update AccountPickler.
  51. public static final int CURRENT_ACCOUNT_VERSION = 3;
  52. public static final String ACCOUNT_KEY_ACCOUNT_VERSION = "version";
  53. public static final String ACCOUNT_KEY_PROFILE = "profile";
  54. public static final String ACCOUNT_KEY_IDP_SERVER = "idpServerURI";
  55. public static final String ACCOUNT_KEY_TOKEN_SERVER = "tokenServerURI"; // Sync-specific.
  56. public static final String ACCOUNT_KEY_DESCRIPTOR = "descriptor";
  57. public static final int CURRENT_BUNDLE_VERSION = 2;
  58. public static final String BUNDLE_KEY_BUNDLE_VERSION = "version";
  59. public static final String BUNDLE_KEY_STATE_LABEL = "stateLabel";
  60. public static final String BUNDLE_KEY_STATE = "state";
  61. // Services may request OAuth tokens from the Firefox Account dynamically.
  62. // Each such token is prefixed with "oauth::" and a service-dependent scope.
  63. // Such tokens should be destroyed when the account is removed from the device.
  64. // This list collects all the known "oauth::" token types in order to delete them when necessary.
  65. private static final List<String> KNOWN_OAUTH_TOKEN_TYPES;
  66. static {
  67. final List<String> list = new ArrayList<>();
  68. if (AppConstants.MOZ_ANDROID_READING_LIST_SERVICE) {
  69. list.add(ReadingListConstants.AUTH_TOKEN_TYPE);
  70. }
  71. KNOWN_OAUTH_TOKEN_TYPES = Collections.unmodifiableList(list);
  72. }
  73. public static final Map<String, Boolean> DEFAULT_AUTHORITIES_TO_SYNC_AUTOMATICALLY_MAP;
  74. static {
  75. final HashMap<String, Boolean> m = new HashMap<String, Boolean>();
  76. // By default, Firefox Sync is enabled.
  77. m.put(BrowserContract.AUTHORITY, true);
  78. DEFAULT_AUTHORITIES_TO_SYNC_AUTOMATICALLY_MAP = Collections.unmodifiableMap(m);
  79. }
  80. private static final String PREF_KEY_LAST_SYNCED_TIMESTAMP = "lastSyncedTimestamp";
  81. protected final Context context;
  82. protected final AccountManager accountManager;
  83. protected final Account account;
  84. /**
  85. * A cache associating Account name (email address) to a representation of the
  86. * account's internal bundle.
  87. * <p>
  88. * The cache is invalidated entirely when <it>any</it> new Account is added,
  89. * because there is no reliable way to know that an Account has been removed
  90. * and then re-added.
  91. */
  92. protected static final ConcurrentHashMap<String, ExtendedJSONObject> perAccountBundleCache =
  93. new ConcurrentHashMap<>();
  94. public static void invalidateCaches() {
  95. perAccountBundleCache.clear();
  96. }
  97. /**
  98. * Create an Android Firefox Account instance backed by an Android Account
  99. * instance.
  100. * <p>
  101. * We expect a long-lived application context to avoid life-cycle issues that
  102. * might arise if the internally cached AccountManager instance surfaces UI.
  103. * <p>
  104. * We take care to not install any listeners or observers that might outlive
  105. * the AccountManager; and Android ensures the AccountManager doesn't outlive
  106. * the associated context.
  107. *
  108. * @param applicationContext
  109. * to use as long-lived ambient Android context.
  110. * @param account
  111. * Android account to use for storage.
  112. */
  113. public AndroidFxAccount(Context applicationContext, Account account) {
  114. this.context = applicationContext;
  115. this.account = account;
  116. this.accountManager = AccountManager.get(this.context);
  117. }
  118. /**
  119. * Persist the Firefox account to disk as a JSON object. Note that this is a wrapper around
  120. * {@link AccountPickler#pickle}, and is identical to calling it directly.
  121. * <p>
  122. * Note that pickling is different from bundling, which involves operations on a
  123. * {@link android.os.Bundle Bundle} object of miscellaneous data associated with the account.
  124. * See {@link #persistBundle} and {@link #unbundle} for more.
  125. */
  126. public void pickle(final String filename) {
  127. AccountPickler.pickle(this, filename);
  128. }
  129. public Account getAndroidAccount() {
  130. return this.account;
  131. }
  132. protected int getAccountVersion() {
  133. String v = accountManager.getUserData(account, ACCOUNT_KEY_ACCOUNT_VERSION);
  134. if (v == null) {
  135. return 0; // Implicit.
  136. }
  137. try {
  138. return Integer.parseInt(v, 10);
  139. } catch (NumberFormatException ex) {
  140. return 0;
  141. }
  142. }
  143. /**
  144. * Saves the given data as the internal bundle associated with this account.
  145. * @param bundle to write to account.
  146. */
  147. protected synchronized void persistBundle(ExtendedJSONObject bundle) {
  148. perAccountBundleCache.put(account.name, bundle);
  149. accountManager.setUserData(account, ACCOUNT_KEY_DESCRIPTOR, bundle.toJSONString());
  150. }
  151. protected ExtendedJSONObject unbundle() {
  152. return unbundle(true);
  153. }
  154. /**
  155. * Retrieve the internal bundle associated with this account.
  156. * @return bundle associated with account.
  157. */
  158. protected synchronized ExtendedJSONObject unbundle(boolean allowCachedBundle) {
  159. if (allowCachedBundle) {
  160. final ExtendedJSONObject cachedBundle = perAccountBundleCache.get(account.name);
  161. if (cachedBundle != null) {
  162. Logger.debug(LOG_TAG, "Returning cached account bundle.");
  163. return cachedBundle;
  164. }
  165. }
  166. final int version = getAccountVersion();
  167. if (version < CURRENT_ACCOUNT_VERSION) {
  168. // Needs upgrade. For now, do nothing. We'd like to just put your account
  169. // into the Separated state here and have you update your credentials.
  170. return null;
  171. }
  172. if (version > CURRENT_ACCOUNT_VERSION) {
  173. // Oh dear.
  174. return null;
  175. }
  176. String bundleString = accountManager.getUserData(account, ACCOUNT_KEY_DESCRIPTOR);
  177. if (bundleString == null) {
  178. return null;
  179. }
  180. final ExtendedJSONObject bundle = unbundleAccountV2(bundleString);
  181. perAccountBundleCache.put(account.name, bundle);
  182. Logger.info(LOG_TAG, "Account bundle persisted to cache.");
  183. return bundle;
  184. }
  185. protected String getBundleData(String key) {
  186. ExtendedJSONObject o = unbundle();
  187. if (o == null) {
  188. return null;
  189. }
  190. return o.getString(key);
  191. }
  192. protected boolean getBundleDataBoolean(String key, boolean def) {
  193. ExtendedJSONObject o = unbundle();
  194. if (o == null) {
  195. return def;
  196. }
  197. Boolean b = o.getBoolean(key);
  198. if (b == null) {
  199. return def;
  200. }
  201. return b;
  202. }
  203. protected byte[] getBundleDataBytes(String key) {
  204. ExtendedJSONObject o = unbundle();
  205. if (o == null) {
  206. return null;
  207. }
  208. return o.getByteArrayHex(key);
  209. }
  210. protected void updateBundleValues(String key, String value, String... more) {
  211. if (more.length % 2 != 0) {
  212. throw new IllegalArgumentException("more must be a list of key, value pairs");
  213. }
  214. ExtendedJSONObject descriptor = unbundle();
  215. if (descriptor == null) {
  216. return;
  217. }
  218. descriptor.put(key, value);
  219. for (int i = 0; i + 1 < more.length; i += 2) {
  220. descriptor.put(more[i], more[i+1]);
  221. }
  222. persistBundle(descriptor);
  223. }
  224. private ExtendedJSONObject unbundleAccountV1(String bundle) {
  225. ExtendedJSONObject o;
  226. try {
  227. o = new ExtendedJSONObject(bundle);
  228. } catch (Exception e) {
  229. return null;
  230. }
  231. if (CURRENT_BUNDLE_VERSION == o.getIntegerSafely(BUNDLE_KEY_BUNDLE_VERSION)) {
  232. return o;
  233. }
  234. return null;
  235. }
  236. private ExtendedJSONObject unbundleAccountV2(String bundle) {
  237. return unbundleAccountV1(bundle);
  238. }
  239. /**
  240. * Note that if the user clears data, an account will be left pointing to a
  241. * deleted profile. Such is life.
  242. */
  243. public String getProfile() {
  244. return accountManager.getUserData(account, ACCOUNT_KEY_PROFILE);
  245. }
  246. public String getAccountServerURI() {
  247. return accountManager.getUserData(account, ACCOUNT_KEY_IDP_SERVER);
  248. }
  249. public String getTokenServerURI() {
  250. return accountManager.getUserData(account, ACCOUNT_KEY_TOKEN_SERVER);
  251. }
  252. public String getOAuthServerURI() {
  253. // Allow testing against stage.
  254. if (FxAccountConstants.STAGE_AUTH_SERVER_ENDPOINT.equals(getAccountServerURI())) {
  255. return FxAccountConstants.STAGE_OAUTH_SERVER_ENDPOINT;
  256. } else {
  257. return FxAccountConstants.DEFAULT_OAUTH_SERVER_ENDPOINT;
  258. }
  259. }
  260. private String constructPrefsPath(String product, long version, String extra) throws GeneralSecurityException, UnsupportedEncodingException {
  261. String profile = getProfile();
  262. String username = account.name;
  263. if (profile == null) {
  264. throw new IllegalStateException("Missing profile. Cannot fetch prefs.");
  265. }
  266. if (username == null) {
  267. throw new IllegalStateException("Missing username. Cannot fetch prefs.");
  268. }
  269. final String fxaServerURI = getAccountServerURI();
  270. if (fxaServerURI == null) {
  271. throw new IllegalStateException("No account server URI. Cannot fetch prefs.");
  272. }
  273. // This is unique for each syncing 'view' of the account.
  274. final String serverURLThing = fxaServerURI + "!" + extra;
  275. return Utils.getPrefsPath(product, username, serverURLThing, profile, version);
  276. }
  277. /**
  278. * This needs to return a string because of the tortured prefs access in GlobalSession.
  279. */
  280. public String getSyncPrefsPath() throws GeneralSecurityException, UnsupportedEncodingException {
  281. final String tokenServerURI = getTokenServerURI();
  282. if (tokenServerURI == null) {
  283. throw new IllegalStateException("No token server URI. Cannot fetch prefs.");
  284. }
  285. final String product = GlobalConstants.BROWSER_INTENT_PACKAGE + ".fxa";
  286. final long version = CURRENT_SYNC_PREFS_VERSION;
  287. return constructPrefsPath(product, version, tokenServerURI);
  288. }
  289. public String getReadingListPrefsPath() throws GeneralSecurityException, UnsupportedEncodingException {
  290. final String product = GlobalConstants.BROWSER_INTENT_PACKAGE + ".reading";
  291. final long version = CURRENT_RL_PREFS_VERSION;
  292. return constructPrefsPath(product, version, "");
  293. }
  294. public SharedPreferences getSyncPrefs() throws UnsupportedEncodingException, GeneralSecurityException {
  295. return context.getSharedPreferences(getSyncPrefsPath(), Utils.SHARED_PREFERENCES_MODE);
  296. }
  297. public SharedPreferences getReadingListPrefs() throws UnsupportedEncodingException, GeneralSecurityException {
  298. return context.getSharedPreferences(getReadingListPrefsPath(), Utils.SHARED_PREFERENCES_MODE);
  299. }
  300. /**
  301. * Extract a JSON dictionary of the string values associated to this account.
  302. * <p>
  303. * <b>For debugging use only!</b> The contents of this JSON object completely
  304. * determine the user's Firefox Account status and yield access to whatever
  305. * user data the device has access to.
  306. *
  307. * @return JSON-object of Strings.
  308. */
  309. public ExtendedJSONObject toJSONObject() {
  310. ExtendedJSONObject o = unbundle();
  311. o.put("email", account.name);
  312. try {
  313. o.put("emailUTF8", Utils.byte2Hex(account.name.getBytes("UTF-8")));
  314. } catch (UnsupportedEncodingException e) {
  315. // Ignore.
  316. }
  317. return o;
  318. }
  319. public static AndroidFxAccount addAndroidAccount(
  320. Context context,
  321. String email,
  322. String profile,
  323. String idpServerURI,
  324. String tokenServerURI,
  325. State state,
  326. final Map<String, Boolean> authoritiesToSyncAutomaticallyMap)
  327. throws UnsupportedEncodingException, GeneralSecurityException, URISyntaxException {
  328. return addAndroidAccount(context, email, profile, idpServerURI, tokenServerURI, state,
  329. authoritiesToSyncAutomaticallyMap,
  330. CURRENT_ACCOUNT_VERSION, false, null);
  331. }
  332. public static AndroidFxAccount addAndroidAccount(
  333. Context context,
  334. String email,
  335. String profile,
  336. String idpServerURI,
  337. String tokenServerURI,
  338. State state,
  339. final Map<String, Boolean> authoritiesToSyncAutomaticallyMap,
  340. final int accountVersion,
  341. final boolean fromPickle,
  342. ExtendedJSONObject bundle)
  343. throws UnsupportedEncodingException, GeneralSecurityException, URISyntaxException {
  344. if (email == null) {
  345. throw new IllegalArgumentException("email must not be null");
  346. }
  347. if (profile == null) {
  348. throw new IllegalArgumentException("profile must not be null");
  349. }
  350. if (idpServerURI == null) {
  351. throw new IllegalArgumentException("idpServerURI must not be null");
  352. }
  353. if (tokenServerURI == null) {
  354. throw new IllegalArgumentException("tokenServerURI must not be null");
  355. }
  356. if (state == null) {
  357. throw new IllegalArgumentException("state must not be null");
  358. }
  359. // TODO: Add migration code.
  360. if (accountVersion != CURRENT_ACCOUNT_VERSION) {
  361. throw new IllegalStateException("Could not create account of version " + accountVersion +
  362. ". Current version is " + CURRENT_ACCOUNT_VERSION + ".");
  363. }
  364. // Android has internal restrictions that require all values in this
  365. // bundle to be strings. *sigh*
  366. Bundle userdata = new Bundle();
  367. userdata.putString(ACCOUNT_KEY_ACCOUNT_VERSION, "" + CURRENT_ACCOUNT_VERSION);
  368. userdata.putString(ACCOUNT_KEY_IDP_SERVER, idpServerURI);
  369. userdata.putString(ACCOUNT_KEY_TOKEN_SERVER, tokenServerURI);
  370. userdata.putString(ACCOUNT_KEY_PROFILE, profile);
  371. if (bundle == null) {
  372. bundle = new ExtendedJSONObject();
  373. // TODO: How to upgrade?
  374. bundle.put(BUNDLE_KEY_BUNDLE_VERSION, CURRENT_BUNDLE_VERSION);
  375. }
  376. bundle.put(BUNDLE_KEY_STATE_LABEL, state.getStateLabel().name());
  377. bundle.put(BUNDLE_KEY_STATE, state.toJSONObject().toJSONString());
  378. userdata.putString(ACCOUNT_KEY_DESCRIPTOR, bundle.toJSONString());
  379. Account account = new Account(email, FxAccountConstants.ACCOUNT_TYPE);
  380. AccountManager accountManager = AccountManager.get(context);
  381. // We don't set an Android password, because we don't want to persist the
  382. // password (or anything else as powerful as the password). Instead, we
  383. // internally manage a sessionToken with a remotely owned lifecycle.
  384. boolean added = accountManager.addAccountExplicitly(account, null, userdata);
  385. if (!added) {
  386. return null;
  387. }
  388. // Try to work around an intermittent issue described at
  389. // http://stackoverflow.com/a/11698139. What happens is that tests that
  390. // delete and re-create the same account frequently will find the account
  391. // missing all or some of the userdata bundle, possibly due to an Android
  392. // AccountManager caching bug.
  393. for (String key : userdata.keySet()) {
  394. accountManager.setUserData(account, key, userdata.getString(key));
  395. }
  396. AndroidFxAccount fxAccount = new AndroidFxAccount(context, account);
  397. if (!fromPickle) {
  398. fxAccount.clearSyncPrefs();
  399. }
  400. fxAccount.setAuthoritiesToSyncAutomaticallyMap(authoritiesToSyncAutomaticallyMap);
  401. return fxAccount;
  402. }
  403. public void clearSyncPrefs() throws UnsupportedEncodingException, GeneralSecurityException {
  404. getSyncPrefs().edit().clear().commit();
  405. }
  406. public void setAuthoritiesToSyncAutomaticallyMap(Map<String, Boolean> authoritiesToSyncAutomaticallyMap) {
  407. if (authoritiesToSyncAutomaticallyMap == null) {
  408. throw new IllegalArgumentException("authoritiesToSyncAutomaticallyMap must not be null");
  409. }
  410. for (String authority : DEFAULT_AUTHORITIES_TO_SYNC_AUTOMATICALLY_MAP.keySet()) {
  411. boolean authorityEnabled = DEFAULT_AUTHORITIES_TO_SYNC_AUTOMATICALLY_MAP.get(authority);
  412. final Boolean enabled = authoritiesToSyncAutomaticallyMap.get(authority);
  413. if (enabled != null) {
  414. authorityEnabled = enabled.booleanValue();
  415. }
  416. // Accounts are always capable of being synced ...
  417. ContentResolver.setIsSyncable(account, authority, 1);
  418. // ... but not always automatically synced.
  419. ContentResolver.setSyncAutomatically(account, authority, authorityEnabled);
  420. }
  421. }
  422. public Map<String, Boolean> getAuthoritiesToSyncAutomaticallyMap() {
  423. final Map<String, Boolean> authoritiesToSync = new HashMap<>();
  424. for (String authority : DEFAULT_AUTHORITIES_TO_SYNC_AUTOMATICALLY_MAP.keySet()) {
  425. final boolean enabled = ContentResolver.getSyncAutomatically(account, authority);
  426. authoritiesToSync.put(authority, enabled);
  427. }
  428. return authoritiesToSync;
  429. }
  430. /**
  431. * Is a sync currently in progress?
  432. *
  433. * @return true if Android is currently syncing the underlying Android Account.
  434. */
  435. public boolean isCurrentlySyncing() {
  436. boolean active = false;
  437. for (String authority : AndroidFxAccount.DEFAULT_AUTHORITIES_TO_SYNC_AUTOMATICALLY_MAP.keySet()) {
  438. active |= ContentResolver.isSyncActive(account, authority);
  439. }
  440. return active;
  441. }
  442. /**
  443. * Request a sync. See {@link FirefoxAccounts#requestSync(Account, EnumSet, String[], String[])}.
  444. */
  445. public void requestSync() {
  446. requestSync(FirefoxAccounts.SOON, null, null);
  447. }
  448. /**
  449. * Request a sync. See {@link FirefoxAccounts#requestSync(Account, EnumSet, String[], String[])}.
  450. *
  451. * @param syncHints to pass to sync.
  452. */
  453. public void requestSync(EnumSet<FirefoxAccounts.SyncHint> syncHints) {
  454. requestSync(syncHints, null, null);
  455. }
  456. /**
  457. * Request a sync. See {@link FirefoxAccounts#requestSync(Account, EnumSet, String[], String[])}.
  458. *
  459. * @param syncHints to pass to sync.
  460. * @param stagesToSync stage names to sync.
  461. * @param stagesToSkip stage names to skip.
  462. */
  463. public void requestSync(EnumSet<FirefoxAccounts.SyncHint> syncHints, String[] stagesToSync, String[] stagesToSkip) {
  464. FirefoxAccounts.requestSync(getAndroidAccount(), syncHints, stagesToSync, stagesToSkip);
  465. }
  466. public synchronized void setState(State state) {
  467. if (state == null) {
  468. throw new IllegalArgumentException("state must not be null");
  469. }
  470. Logger.info(LOG_TAG, "Moving account named like " + getObfuscatedEmail() +
  471. " to state " + state.getStateLabel().toString());
  472. updateBundleValues(
  473. BUNDLE_KEY_STATE_LABEL, state.getStateLabel().name(),
  474. BUNDLE_KEY_STATE, state.toJSONObject().toJSONString());
  475. broadcastAccountStateChangedIntent();
  476. }
  477. protected void broadcastAccountStateChangedIntent() {
  478. final Intent intent = new Intent(FxAccountConstants.ACCOUNT_STATE_CHANGED_ACTION);
  479. intent.putExtra(Constants.JSON_KEY_ACCOUNT, account.name);
  480. context.sendBroadcast(intent, FxAccountConstants.PER_ACCOUNT_TYPE_PERMISSION);
  481. }
  482. public synchronized State getState() {
  483. String stateLabelString = getBundleData(BUNDLE_KEY_STATE_LABEL);
  484. String stateString = getBundleData(BUNDLE_KEY_STATE);
  485. if (stateLabelString == null || stateString == null) {
  486. throw new IllegalStateException("stateLabelString and stateString must not be null, but: " +
  487. "(stateLabelString == null) = " + (stateLabelString == null) +
  488. " and (stateString == null) = " + (stateString == null));
  489. }
  490. try {
  491. StateLabel stateLabel = StateLabel.valueOf(stateLabelString);
  492. Logger.debug(LOG_TAG, "Account is in state " + stateLabel);
  493. return StateFactory.fromJSONObject(stateLabel, new ExtendedJSONObject(stateString));
  494. } catch (Exception e) {
  495. throw new IllegalStateException("could not get state", e);
  496. }
  497. }
  498. /**
  499. * <b>For debugging only!</b>
  500. */
  501. public void dump() {
  502. if (!FxAccountUtils.LOG_PERSONAL_INFORMATION) {
  503. return;
  504. }
  505. ExtendedJSONObject o = toJSONObject();
  506. ArrayList<String> list = new ArrayList<String>(o.keySet());
  507. Collections.sort(list);
  508. for (String key : list) {
  509. FxAccountUtils.pii(LOG_TAG, key + ": " + o.get(key));
  510. }
  511. }
  512. /**
  513. * Return the Firefox Account's local email address.
  514. * <p>
  515. * It is important to note that this is the local email address, and not
  516. * necessarily the normalized remote email address that the server expects.
  517. *
  518. * @return local email address.
  519. */
  520. public String getEmail() {
  521. return account.name;
  522. }
  523. /**
  524. * Return the Firefox Account's local email address, obfuscated.
  525. * <p>
  526. * Use this when logging.
  527. *
  528. * @return local email address, obfuscated.
  529. */
  530. public String getObfuscatedEmail() {
  531. return Utils.obfuscateEmail(account.name);
  532. }
  533. /**
  534. * Create an intent announcing that a Firefox account will be deleted.
  535. *
  536. * @return <code>Intent</code> to broadcast.
  537. */
  538. public Intent makeDeletedAccountIntent() {
  539. final Intent intent = new Intent(FxAccountConstants.ACCOUNT_DELETED_ACTION);
  540. final List<String> tokens = new ArrayList<>();
  541. intent.putExtra(FxAccountConstants.ACCOUNT_DELETED_INTENT_VERSION_KEY,
  542. Long.valueOf(FxAccountConstants.ACCOUNT_DELETED_INTENT_VERSION));
  543. intent.putExtra(FxAccountConstants.ACCOUNT_DELETED_INTENT_ACCOUNT_KEY, account.name);
  544. // Get the tokens from AccountManager. Note: currently, only reading list service supports OAuth. The following logic will
  545. // be extended in future to support OAuth for other services.
  546. for (String tokenKey : KNOWN_OAUTH_TOKEN_TYPES) {
  547. final String authToken = accountManager.peekAuthToken(account, tokenKey);
  548. if (authToken != null) {
  549. tokens.add(authToken);
  550. }
  551. }
  552. // Update intent with tokens and service URI.
  553. intent.putExtra(FxAccountConstants.ACCOUNT_OAUTH_SERVICE_ENDPOINT_KEY, getOAuthServerURI());
  554. // Deleted broadcasts are package-private, so there's no security risk include the tokens in the extras
  555. intent.putExtra(FxAccountConstants.ACCOUNT_DELETED_INTENT_ACCOUNT_AUTH_TOKENS, tokens.toArray(new String[tokens.size()]));
  556. return intent;
  557. }
  558. public void setLastSyncedTimestamp(long now) {
  559. try {
  560. getSyncPrefs().edit().putLong(PREF_KEY_LAST_SYNCED_TIMESTAMP, now).commit();
  561. } catch (Exception e) {
  562. Logger.warn(LOG_TAG, "Got exception setting last synced time; ignoring.", e);
  563. }
  564. }
  565. public long getLastSyncedTimestamp() {
  566. final long neverSynced = -1L;
  567. try {
  568. return getSyncPrefs().getLong(PREF_KEY_LAST_SYNCED_TIMESTAMP, neverSynced);
  569. } catch (Exception e) {
  570. Logger.warn(LOG_TAG, "Got exception getting last synced time; ignoring.", e);
  571. return neverSynced;
  572. }
  573. }
  574. // Debug only! This is dangerous!
  575. public void unsafeTransitionToDefaultEndpoints() {
  576. unsafeTransitionToStageEndpoints(
  577. FxAccountConstants.DEFAULT_AUTH_SERVER_ENDPOINT,
  578. FxAccountConstants.DEFAULT_TOKEN_SERVER_ENDPOINT);
  579. }
  580. // Debug only! This is dangerous!
  581. public void unsafeTransitionToStageEndpoints() {
  582. unsafeTransitionToStageEndpoints(
  583. FxAccountConstants.STAGE_AUTH_SERVER_ENDPOINT,
  584. FxAccountConstants.STAGE_TOKEN_SERVER_ENDPOINT);
  585. }
  586. protected void unsafeTransitionToStageEndpoints(String authServerEndpoint, String tokenServerEndpoint) {
  587. try {
  588. getReadingListPrefs().edit().clear().commit();
  589. } catch (UnsupportedEncodingException | GeneralSecurityException e) {
  590. // Ignore.
  591. }
  592. try {
  593. getSyncPrefs().edit().clear().commit();
  594. } catch (UnsupportedEncodingException | GeneralSecurityException e) {
  595. // Ignore.
  596. }
  597. State state = getState();
  598. setState(state.makeSeparatedState());
  599. accountManager.setUserData(account, ACCOUNT_KEY_IDP_SERVER, authServerEndpoint);
  600. accountManager.setUserData(account, ACCOUNT_KEY_TOKEN_SERVER, tokenServerEndpoint);
  601. ContentResolver.setIsSyncable(account, BrowserContract.READING_LIST_AUTHORITY, 1);
  602. }
  603. /**
  604. * Take the lock to own updating any Firefox Account's internal state.
  605. *
  606. * We use a <code>Semaphore</code> rather than a <code>ReentrantLock</code>
  607. * because the callback that needs to release the lock may not be invoked on
  608. * the thread that initially acquired the lock. Be aware!
  609. */
  610. protected static final Semaphore sLock = new Semaphore(1, true /* fair */);
  611. // Which consumer took the lock?
  612. // Synchronized by this.
  613. protected String lockTag = null;
  614. // Are we locked? (It's not easy to determine who took the lock dynamically,
  615. // so we maintain this flag internally.)
  616. // Synchronized by this.
  617. protected boolean locked = false;
  618. // Block until we can take the shared state lock.
  619. public synchronized void acquireSharedAccountStateLock(final String tag) throws InterruptedException {
  620. final long id = Thread.currentThread().getId();
  621. this.lockTag = tag;
  622. Log.d(Logger.DEFAULT_LOG_TAG, "Thread with tag and thread id acquiring lock: " + lockTag + ", " + id + " ...");
  623. sLock.acquire();
  624. locked = true;
  625. Log.d(Logger.DEFAULT_LOG_TAG, "Thread with tag and thread id acquiring lock: " + lockTag + ", " + id + " ... ACQUIRED");
  626. }
  627. // If we hold the shared state lock, release it. Otherwise, ignore the request.
  628. public synchronized void releaseSharedAccountStateLock() {
  629. final long id = Thread.currentThread().getId();
  630. Log.d(Logger.DEFAULT_LOG_TAG, "Thread with tag and thread id releasing lock: " + lockTag + ", " + id + " ...");
  631. if (locked) {
  632. sLock.release();
  633. locked = false;
  634. Log.d(Logger.DEFAULT_LOG_TAG, "Thread with tag and thread id releasing lock: " + lockTag + ", " + id + " ... RELEASED");
  635. } else {
  636. Log.d(Logger.DEFAULT_LOG_TAG, "Thread with tag and thread id releasing lock: " + lockTag + ", " + id + " ... NOT LOCKED");
  637. }
  638. }
  639. @Override
  640. protected synchronized void finalize() {
  641. if (locked) {
  642. // Should never happen, but...
  643. sLock.release();
  644. locked = false;
  645. final long id = Thread.currentThread().getId();
  646. Log.e(Logger.DEFAULT_LOG_TAG, "Thread with tag and thread id releasing lock: " + lockTag + ", " + id + " ... RELEASED DURING FINALIZE");
  647. }
  648. }
  649. }