Merge "Add toggle to allow or disable null algorithms"
diff --git a/res/values/strings.xml b/res/values/strings.xml
index c38b080..733d0e1 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -10938,6 +10938,11 @@
     <!-- Title for if toggle access is disabled by carrier [CHAR LIMIT=NONE] -->
     <string name="enable_2g_summary_disabled_carrier"><xliff:g id="carrier_name_2g" example="Google Fi">%1$s</xliff:g> requires 2G to be available</string>
 
+    <!-- Title for toggle if user wants to allow null cellular algorithms [CHAR LIMIT=40] -->
+    <string name="allow_null_algorithms_title">Allow less secure connection</string>
+    <!-- Summary for if the user wants to allow null cellular algorithms [CHAR LIMIT=NONE] -->
+    <string name="allow_null_algorithms_summary">May improve your signal in some locations. For emergency calls, less secure connections are always allowed.</string>
+
     <!-- Label for All services preference in App info settings [CHAR LIMIT=40] -->
     <string name="app_info_all_services_label">All services</string>
 
diff --git a/res/xml/mobile_network_settings.xml b/res/xml/mobile_network_settings.xml
index 987c2ce..7f059fb 100644
--- a/res/xml/mobile_network_settings.xml
+++ b/res/xml/mobile_network_settings.xml
@@ -250,6 +250,13 @@
             settings:userRestriction="no_cellular_2g"/>
 
         <SwitchPreference
+            android:key="allow_null_algorithms"
+            android:title="@string/allow_null_algorithms_title"
+            android:summary="@string/allow_null_algorithms_summary"
+            settings:controller=
+                "com.android.settings.network.telephony.NullAlgorithmsPreferenceController" />
+
+        <SwitchPreference
             android:key="nr_advanced_calling"
             android:title="@string/nr_advanced_calling_title"
             android:persistent="false"
diff --git a/src/com/android/settings/network/telephony/NullAlgorithmsPreferenceController.java b/src/com/android/settings/network/telephony/NullAlgorithmsPreferenceController.java
new file mode 100644
index 0000000..c4fdcbd
--- /dev/null
+++ b/src/com/android/settings/network/telephony/NullAlgorithmsPreferenceController.java
@@ -0,0 +1,111 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.settings.network.telephony;
+
+import android.content.Context;
+import android.provider.DeviceConfig;
+import android.telephony.TelephonyManager;
+import android.util.Log;
+
+/**
+ * Preference controller for "Allow Null Algorithms"
+ *
+ * <p>This preference controller is toggling null algorithms is not a per-sim operation.
+ */
+public class NullAlgorithmsPreferenceController extends TelephonyTogglePreferenceController {
+
+    // log tags have a char limit of 24 so we can't use the class name
+    private static final String LOG_TAG = "NullAlgosController";
+
+    private TelephonyManager mTelephonyManager;
+
+    /**
+     * Class constructor of "Allow Null Algorithms" toggle.
+     *
+     * @param context of settings
+     * @param key     assigned within UI entry of XML file
+     */
+    public NullAlgorithmsPreferenceController(Context context, String key) {
+        super(context, key);
+        mTelephonyManager = mContext.getSystemService(TelephonyManager.class);
+    }
+
+    /**
+     * Get the {@link com.android.settings.core.BasePreferenceController.AvailabilityStatus} for
+     * this preference given a {@code subId}. This dictates whether the setting is available on
+     * the device, and if it is not, offers some context as to why.
+     */
+    @Override
+    public int getAvailabilityStatus(int subId) {
+        if (mTelephonyManager == null) {
+            Log.w(LOG_TAG,
+                    "Telephony manager not yet initialized. Marking availability as "
+                            + "CONDITIONALLY_UNAVAILABLE");
+            mTelephonyManager = mContext.getSystemService(TelephonyManager.class);
+            return CONDITIONALLY_UNAVAILABLE;
+        }
+
+        if (!DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_CELLULAR_SECURITY,
+                TelephonyManager.PROPERTY_ENABLE_NULL_CIPHER_TOGGLE, false)) {
+            Log.i(LOG_TAG, "Null cipher toggle is disabled by DeviceConfig");
+            return CONDITIONALLY_UNAVAILABLE;
+        }
+
+        try {
+            mTelephonyManager.isNullCipherAndIntegrityPreferenceEnabled();
+        } catch (UnsupportedOperationException e) {
+            Log.i(LOG_TAG, "Null cipher enablement is unsupported: " + e.getMessage());
+            return UNSUPPORTED_ON_DEVICE;
+        }
+
+        return AVAILABLE;
+    }
+
+    /**
+     * Return {@code true} if null algorithms are currently allowed.
+     *
+     * <p><b>NOTE:</b> This method returns the active state of the preference controller and is not
+     * the parameter passed into {@link #setChecked(boolean)}, which is instead the requested future
+     * state.
+     */
+    @Override
+    public boolean isChecked() {
+        return mTelephonyManager.isNullCipherAndIntegrityPreferenceEnabled();
+    }
+
+    /**
+     * Called when a user preference changes on the toggle. We pass this info on to the Telephony
+     * Framework so that the modem can be updated with the user's preference.
+     *
+     * <p>See {@link com.android.settings.core.TogglePreferenceController#setChecked(boolean)} for
+     * details.
+     *
+     * @param isChecked The toggle value that we're being requested to enforce. A value of {@code
+     *                  false} denotes that null ciphers will be disabled by the modem after this
+     *                  function
+     *                  completes, if it is not already.
+     */
+    @Override
+    public boolean setChecked(boolean isChecked) {
+        if (isChecked) {
+            Log.i(LOG_TAG, "Enabling null algorithms");
+        } else {
+            Log.i(LOG_TAG, "Disabling null algorithms");
+        }
+        mTelephonyManager.setNullCipherAndIntegrityEnabled(isChecked);
+        return true;
+    }
+}
diff --git a/tests/unit/src/com/android/settings/network/telephony/NullAlgorithmsPreferenceControllerTest.java b/tests/unit/src/com/android/settings/network/telephony/NullAlgorithmsPreferenceControllerTest.java
new file mode 100644
index 0000000..e57dfcd
--- /dev/null
+++ b/tests/unit/src/com/android/settings/network/telephony/NullAlgorithmsPreferenceControllerTest.java
@@ -0,0 +1,144 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.settings.network.telephony;
+
+import static com.android.settings.core.BasePreferenceController.AVAILABLE;
+import static com.android.settings.core.BasePreferenceController.CONDITIONALLY_UNAVAILABLE;
+import static com.android.settings.core.BasePreferenceController.UNSUPPORTED_ON_DEVICE;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.os.Looper;
+import android.provider.DeviceConfig;
+import android.telephony.TelephonyManager;
+import android.util.Log;
+
+import androidx.preference.Preference;
+import androidx.preference.PreferenceManager;
+import androidx.preference.PreferenceScreen;
+import androidx.test.core.app.ApplicationProvider;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+
+@RunWith(AndroidJUnit4.class)
+public final class NullAlgorithmsPreferenceControllerTest {
+    private static final String LOG_TAG = "NullAlgosControllerTest";
+    private static final int SUB_ID = 2;
+    private static final String PREFERENCE_KEY = "TEST_NULL_CIPHER_PREFERENCE";
+
+    @Mock
+    private TelephonyManager mTelephonyManager;
+    private Preference mPreference;
+    private PreferenceScreen mPreferenceScreen;
+    private NullAlgorithmsPreferenceController mController;
+    private Context mContext;
+    // Ideally we would use TestableDeviceConfig, but that's not doable because the Settings
+    // app is not currently debuggable. For now, we use the real device config and ensure that
+    // we reset the cellular_security namespace property to its pre-test value after every test.
+    private DeviceConfig.Properties mPreTestProperties;
+
+    @Before
+    public void setUp() {
+        if (Looper.myLooper() == null) {
+            Looper.prepare();
+        }
+
+        mPreTestProperties = DeviceConfig.getProperties(
+                TelephonyManager.PROPERTY_ENABLE_NULL_CIPHER_TOGGLE);
+
+        MockitoAnnotations.initMocks(this);
+
+        mContext = spy(ApplicationProvider.getApplicationContext());
+        when(mContext.getSystemService(TelephonyManager.class)).thenReturn(mTelephonyManager);
+
+        doReturn(mTelephonyManager).when(mTelephonyManager).createForSubscriptionId(SUB_ID);
+
+        mController = new NullAlgorithmsPreferenceController(mContext, PREFERENCE_KEY);
+
+        mPreference = spy(new Preference(mContext));
+        mPreference.setKey(PREFERENCE_KEY);
+        mPreferenceScreen = new PreferenceManager(mContext).createPreferenceScreen(mContext);
+        mPreferenceScreen.addPreference(mPreference);
+    }
+
+    @After
+    public void tearDown() {
+        try {
+            DeviceConfig.setProperties(mPreTestProperties);
+        } catch (DeviceConfig.BadConfigException e) {
+            Log.e(LOG_TAG,
+                    "Failed to reset DeviceConfig to pre-test state. Test results may be impacted. "
+                            + e.getMessage());
+        }
+    }
+
+    @Test
+    public void getAvailabilityStatus_unsupportedHardware_unsupportedOnDevice() {
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_CELLULAR_SECURITY,
+                TelephonyManager.PROPERTY_ENABLE_NULL_CIPHER_TOGGLE, Boolean.TRUE.toString(),
+                false);
+        doThrow(UnsupportedOperationException.class).when(
+                mTelephonyManager).isNullCipherAndIntegrityPreferenceEnabled();
+        assertThat(mController.getAvailabilityStatus()).isEqualTo(UNSUPPORTED_ON_DEVICE);
+    }
+
+    @Test
+    public void getAvailabilityStatus_featureFlagOff_conditionallyUnavailable() {
+        doReturn(true).when(mTelephonyManager).isNullCipherAndIntegrityPreferenceEnabled();
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_CELLULAR_SECURITY,
+                TelephonyManager.PROPERTY_ENABLE_NULL_CIPHER_TOGGLE, Boolean.FALSE.toString(),
+                false);
+        assertThat(mController.getAvailabilityStatus()).isEqualTo(CONDITIONALLY_UNAVAILABLE);
+    }
+
+    @Test
+    public void getAvailabilityStatus_returnAvailable() {
+        DeviceConfig.setProperty(DeviceConfig.NAMESPACE_CELLULAR_SECURITY,
+                TelephonyManager.PROPERTY_ENABLE_NULL_CIPHER_TOGGLE, Boolean.TRUE.toString(),
+                false);
+        // The value returned here shouldn't matter. The fact that this call is successful
+        // indicates that the device supports this operation
+        doReturn(true).when(mTelephonyManager).isNullCipherAndIntegrityPreferenceEnabled();
+        assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
+    }
+
+    @Test
+    public void setChecked_true() {
+        mController.setChecked(true);
+        verify(mTelephonyManager, times(1)).setNullCipherAndIntegrityEnabled(true);
+    }
+
+    @Test
+    public void setChecked_false() {
+        mController.setChecked(false);
+        verify(mTelephonyManager, times(1)).setNullCipherAndIntegrityEnabled(false);
+    }
+}