Skip to content

Comments

feat: Migrate PreferencesManager to DataStore with Encrypted Storage#477

Merged
volodymyr-chekyrta merged 2 commits intoopenedx:developfrom
raccoongang:feat/migration_to_data_store
Feb 18, 2026
Merged

feat: Migrate PreferencesManager to DataStore with Encrypted Storage#477
volodymyr-chekyrta merged 2 commits intoopenedx:developfrom
raccoongang:feat/migration_to_data_store

Conversation

@PavloNetrebchuk
Copy link
Contributor

Migrates PreferencesManager from SharedPreferences to Jetpack DataStore Preferences with AES-256-GCM encryption for sensitive data using Android Keystore.

DataStore Migration:

  • Replaced SharedPreferences with DataStore
  • Introduced type-safe preference keys using stringPreferencesKey, longPreferencesKey, booleanPreferencesKey
  • Updated clearCorePreferences() and clearCalendarPreferences() to suspend functions
  • Added androidx.datastore:datastore-preferences:1.2.0 dependency

Encryption Implementation:

  • Created DataStoreEncryption class using Android Keystore + AES-256-GCM
  • Encrypted sensitive fields:
    • accessToken
    • refreshToken
    • pushToken
    • user (JSON)
    • profile (JSON)

Security Details:

  • Algorithm : AES-256-GCM
  • Key Storage : Android Keystore (hardware-backed when available)
  • IV Length : 2 bytes (random per encryption)
  • Auth Tag : 128 bits
  • Format : Base64(IV + ciphertext + auth_tag)

Motivation

SharedPreferences limitations:

  • No encryption for sensitive data
  • Synchronous API blocks the calling thread
  • No type safety for keys

New implementation advantages:

  • Sensitive tokens encrypted at rest
  • Keys stored in Android Keystore (never exportable)
  • Type-safe key definitions
  • Guaranteed atomic writes

@openedx-webhooks openedx-webhooks added the open-source-contribution PR author is not from Axim or 2U label Feb 5, 2026
@openedx-webhooks
Copy link

Thanks for the pull request, @PavloNetrebchuk!

This repository is currently maintained by @openedx/openedx-mobile-maintainers.

Once you've gone through the following steps feel free to tag them in a comment and let them know that your changes are ready for engineering review.

🔘 Get product approval

If you haven't already, check this list to see if your contribution needs to go through the product review process.

  • If it does, you'll need to submit a product proposal for your contribution, and have it reviewed by the Product Working Group.
    • This process (including the steps you'll need to take) is documented here.
  • If it doesn't, simply proceed with the next step.
🔘 Provide context

To help your reviewers and other members of the community understand the purpose and larger context of your changes, feel free to add as much of the following information to the PR description as you can:

  • Dependencies

    This PR must be merged before / after / at the same time as ...

  • Blockers

    This PR is waiting for OEP-1234 to be accepted.

  • Timeline information

    This PR must be merged by XX date because ...

  • Partner information

    This is for a course on edx.org.

  • Supporting documentation
  • Relevant Open edX discussion forum threads
🔘 Get a green build

If one or more checks are failing, continue working on your changes until this is no longer the case and your build turns green.

Details
Where can I find more information?

If you'd like to get more details on all aspects of the review process for open source pull requests (OSPRs), check out the following resources:

When can I expect my changes to be merged?

Our goal is to get community contributions seen and reviewed as efficiently as possible.

However, the amount of time that it takes to review and merge a PR can vary significantly based on factors such as:

  • The size and impact of the changes that it introduces
  • The need for product review
  • Maintenance status of the parent repository

💡 As a result it may take up to several weeks or months to complete a review and merge your PR.

@PavloNetrebchuk PavloNetrebchuk force-pushed the feat/migration_to_data_store branch from d65fbc3 to aa018a7 Compare February 5, 2026 13:26
@mphilbrick211 mphilbrick211 moved this from Needs Triage to Ready for Review in Contributions Feb 9, 2026
Copy link

@RawanMatar89 RawanMatar89 left a comment

Choose a reason for hiding this comment

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

@PavloNetrebchuk Will you please mention how this PR manage the migration for old user preferences ?


private fun getString(key: String, defValue: String = ""): String {
return sharedPreferences.getString(key, defValue) ?: defValue
private fun <T> getValue(key: Preferences.Key<T>, defaultValue: T): T = runBlocking {

Choose a reason for hiding this comment

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

dataStore is async, so calling getValue on the main thread with runBlocking and dataStore could cause UI freeze.

val encrypted = getValue(key, "")
if (encrypted.isEmpty()) return defaultValue
val decrypted = encryption.decrypt(encrypted)
return decrypted.ifEmpty { defaultValue }

Choose a reason for hiding this comment

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

all fun calls use "" as 'default value'.
keystore key can be invalidated if the user change device security settings or the system updated. so I think we should handle this senecio to prevent the case of using the app with an empty access token which will lead to bad user experience

@PavloNetrebchuk
Copy link
Contributor Author

PavloNetrebchuk commented Feb 16, 2026

Hi @RawanMatar89
Thank you for the feedback.
I have already added changes according your messages:

Fix 1: runBlocking → runBlocking(Dispatchers.IO)
Both getValue and setValue now dispatch DataStore I/O to the IO thread pool, preventing potential deadlocks where DataStore's internal coroutine dispatcher conflicts with the calling thread.

Fix 2: Keystore invalidation handling

  • scope (CoroutineScope(Dispatchers.IO + SupervisorJob())) for async cleanup
  • Volatile anotation isKeyInvalidated flag to short-circuit after first detection
  • In getEncryptedString(): if encrypted data exists but decrypt() returns "", the keystore key has been invalidated. The code sets the flag, clears core preferences, and sends LogoutEvent(true) via AppNotifier. This triggers
    AppViewModel.handleLogoutEvent() → clears DB → navigates to login screen.
  • Constructor now takes AppNotifier as a second parameter.

Fix 3: SharedPreferences → DataStore migration

  • shouldMigrate(): checks if old SharedPreferences (BuildConfig.APPLICATION_ID) has data
  • migrate(): copies all old values to DataStore with:
    • Encryption of sensitive fields (access_token, refresh_token, push_token, user, account)
    • Key remapping for renamed keys (CALENDAR_ID → calendar_id, IS_RELATIVE_DATES_ENABLED → is_relative_dates_enabled, etc.)
    • Type-safe helpers for String/Long/Boolean migrations
  • cleanUp(): clears the old SharedPreferences after successful migration

@PavloNetrebchuk PavloNetrebchuk force-pushed the feat/migration_to_data_store branch from f095314 to a0b2e74 Compare February 16, 2026 10:30
Copy link

@RawanMatar89 RawanMatar89 left a comment

Choose a reason for hiding this comment

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

@PavloNetrebchuk, great efforts 👏🏻 LGTM 👍🏻

@volodymyr-chekyrta volodymyr-chekyrta merged commit 1d6048d into openedx:develop Feb 18, 2026
6 checks passed
@github-project-automation github-project-automation bot moved this from Ready for Review to Done in Contributions Feb 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

open-source-contribution PR author is not from Axim or 2U

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants