Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add reset after failure, result.error after failure #865

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
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 @@ -31,51 +31,45 @@ public class FlutterSecureStorage {

private String sharedPreferencesName = DEFAULT_PREF_NAME;
private String preferencesKeyPrefix = DEFAULT_KEY_PREFIX;
private SharedPreferences encryptedPreferences;
private final SharedPreferences encryptedPreferences;

Choose a reason for hiding this comment

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

If I understand correctly, the constructor of FlutterSecureStorage should throw an error, if the initialization of encryptedPreferences fails. I believe, that this means, that encryptedPreferences cannot be null (see EncryptedSharedPreferences.create).
If so, we could/should maybe add the @NonNull annotation for encryptedPreferences here (and we can probably remove most null checks in class methods).


public FlutterSecureStorage(Context context, Map<String, Object> options) {
public FlutterSecureStorage(Context context, Map<String, Object> options) throws GeneralSecurityException, IOException {
this.applicationContext = context.getApplicationContext();
this.options = options;
ensureOptions();
getEncryptedSharedPreferences();
encryptedPreferences = getEncryptedSharedPreferences();
}

public boolean containsKey(String key) {
SharedPreferences preferences = getEncryptedSharedPreferences();
return preferences != null && preferences.contains(addPrefixToKey(key));
return encryptedPreferences != null && encryptedPreferences.contains(addPrefixToKey(key));
}

public String read(String key) {
SharedPreferences preferences = getEncryptedSharedPreferences();
return preferences != null ? preferences.getString(addPrefixToKey(key), null) : null;
return encryptedPreferences != null ? encryptedPreferences.getString(addPrefixToKey(key), null) : null;
}

public void write(String key, String value) {
SharedPreferences preferences = getEncryptedSharedPreferences();
if (preferences != null) {
preferences.edit().putString(addPrefixToKey(key), value).apply();
if (encryptedPreferences != null) {
encryptedPreferences.edit().putString(addPrefixToKey(key), value).apply();
}
}

public void delete(String key) {
SharedPreferences preferences = getEncryptedSharedPreferences();
if (preferences != null) {
preferences.edit().remove(addPrefixToKey(key)).apply();
if (encryptedPreferences != null) {
encryptedPreferences.edit().remove(addPrefixToKey(key)).apply();
}
}

public void deleteAll() {
SharedPreferences preferences = getEncryptedSharedPreferences();
if (preferences != null) {
preferences.edit().clear().apply();
if (encryptedPreferences != null) {
encryptedPreferences.edit().clear().apply();
}
}

public Map<String, String> readAll() {
SharedPreferences preferences = getEncryptedSharedPreferences();
Map<String, String> result = new HashMap<>();
if (preferences != null) {
Map<String, ?> allEntries = preferences.getAll();
if (encryptedPreferences != null) {
Map<String, ?> allEntries = encryptedPreferences.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
Expand All @@ -102,18 +96,21 @@ private void ensureOptions() {
: DEFAULT_KEY_PREFIX;
}

private SharedPreferences getEncryptedSharedPreferences() {
if (encryptedPreferences == null) {
private SharedPreferences getEncryptedSharedPreferences() throws GeneralSecurityException, IOException {
try {
final SharedPreferences encryptedPreferences = initializeEncryptedSharedPreferencesManager(applicationContext);
migrateToEncryptedPreferences(encryptedPreferences);
return encryptedPreferences;
} catch (Exception e) {

Choose a reason for hiding this comment

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

I am a bit unsure, if we should reset the storage on any exception; maybe, we should only reset it on exceptions where we know that the reset is absolutely necessary? (I think, javax.crypto.AEADBadTagException would be an example)

Log.w(TAG, "EncryptedSharedPreferences initialization failed, resetting storage", e);
applicationContext.getSharedPreferences(sharedPreferencesName, Context.MODE_PRIVATE).edit().clear().apply();
try {
encryptedPreferences = initializeEncryptedSharedPreferencesManager(applicationContext);
migrateToEncryptedPreferences(encryptedPreferences);
} catch (Exception e) {
Log.e(TAG, "EncryptedSharedPreferences initialization failed", e);
return initializeEncryptedSharedPreferencesManager(applicationContext);
} catch (Exception f) {
Log.e(TAG, "EncryptedSharedPreferences initialization after reset failed", e);
throw f;
}
} else {
return encryptedPreferences;
}
return null;
}

private SharedPreferences initializeEncryptedSharedPreferencesManager(Context context) throws GeneralSecurityException, IOException {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
package com.it_nomads.fluttersecurestorage;

import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.NonNull;

Expand All @@ -22,15 +20,16 @@

public class FlutterSecureStoragePlugin implements MethodCallHandler, FlutterPlugin {

private static final String TAG = "FlutterSecureStoragePl";
private MethodChannel channel;
private FlutterSecureStorage secureStorage;
private HandlerThread workerThread;
private Handler workerThreadHandler;
private FlutterPluginBinding binding;

@Override
public void onAttachedToEngine(FlutterPluginBinding binding) {
initInstance(binding.getBinaryMessenger(), binding.getApplicationContext());
this.binding = binding;
initInstance(binding.getBinaryMessenger());
}

@Override
Expand All @@ -46,16 +45,30 @@ public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
secureStorage = null;
}

private void initInstance(BinaryMessenger messenger, Context context) {
private void initInstance(BinaryMessenger messenger) {
workerThread = new HandlerThread("fluttersecurestorage.worker");
workerThread.start();
workerThreadHandler = new Handler(workerThread.getLooper());
channel = new MethodChannel(messenger, "plugins.it_nomads.com/flutter_secure_storage");
channel.setMethodCallHandler(this);
initSecureStorage(null);
}

private boolean initSecureStorage(Result result) {
if (secureStorage != null) return true;

try {
secureStorage = new FlutterSecureStorage(context, new HashMap<>());
workerThread = new HandlerThread("fluttersecurestorage.worker");
workerThread.start();
workerThreadHandler = new Handler(workerThread.getLooper());
channel = new MethodChannel(messenger, "plugins.it_nomads.com/flutter_secure_storage");
channel.setMethodCallHandler(this);
secureStorage = new FlutterSecureStorage(binding.getApplicationContext(), new HashMap<>());
return true;
} catch (Exception e) {
Log.e(TAG, "Plugin initialization failed", e);
if (result != null) {
result.error(
"RESET_FAILED", // Error code
"Failed to reset and initialize encrypted preferences", // Error message
e.toString() // Details (stack trace or additional info)
);
}
return false;
}
}

Expand Down Expand Up @@ -87,6 +100,9 @@ private void handleMethodCall(MethodCall call, Result result) {
String method = call.method;
Map<String, Object> args = extractArguments(call);

boolean isInitialized = initSecureStorage(result);
if (!isInitialized) return;

switch (method) {
case "write":
handleWrite(args, result);
Expand Down
Loading