Merge "[Thread] add missing permissions to ThreadNetworkDemoApp" into main am: a490186098

Original change: https://android-review.googlesource.com/c/platform/packages/modules/Connectivity/+/3002350

Change-Id: I6e693f1dcc7b5823acf140d85403442a95aed5ce
Signed-off-by: Automerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com>
diff --git a/Tethering/apex/Android.bp b/Tethering/apex/Android.bp
index 4bae221..047ba02 100644
--- a/Tethering/apex/Android.bp
+++ b/Tethering/apex/Android.bp
@@ -23,26 +23,23 @@
 // different value depending on the branch.
 java_defaults {
     name: "ConnectivityNextEnableDefaults",
-    enabled: true,
+    enabled: false,
 }
-
 java_defaults {
     name: "NetworkStackApiShimSettingsForCurrentBranch",
     // API shims to include in the networking modules built from the branch. Branches that disable
     // the "next" targets must use stable shims (latest stable API level) instead of current shims
     // (X_current API level).
-    static_libs: ["NetworkStackApiCurrentShims"],
+    static_libs: ["NetworkStackApiStableShims"],
 }
-
 apex_defaults {
     name: "ConnectivityApexDefaults",
     // Tethering app to include in the AOSP apex. Branches that disable the "next" targets may use
     // a stable tethering app instead, but will generally override the AOSP apex to use updatable
     // package names and keys, so that apex will be unused anyway.
-    apps: ["TetheringNext"], // Replace to "Tethering" if ConnectivityNextEnableDefaults is false.
+    apps: ["Tethering"], // Replace to "Tethering" if ConnectivityNextEnableDefaults is false.
 }
-
-enable_tethering_next_apex = true
+enable_tethering_next_apex = false
 // This is a placeholder comment to avoid merge conflicts
 // as the above target may have different "enabled" values
 // depending on the branch
diff --git a/common/Android.bp b/common/Android.bp
index 0048a0a..f4b4cae 100644
--- a/common/Android.bp
+++ b/common/Android.bp
@@ -20,8 +20,6 @@
     default_applicable_licenses: ["Android-Apache-2.0"],
 }
 
-build = ["FlaggedApi.bp"]
-
 // This is a placeholder comment to avoid merge conflicts
 // as the above target may not exist
 // depending on the branch
diff --git a/framework-t/Android.bp b/framework-t/Android.bp
index bc919ac..0ee2275 100644
--- a/framework-t/Android.bp
+++ b/framework-t/Android.bp
@@ -20,12 +20,12 @@
     default_applicable_licenses: ["Android-Apache-2.0"],
 }
 
-framework_remoteauth_srcs = [":framework-remoteauth-java-sources"]
-framework_remoteauth_api_srcs = []
+framework_remoteauth_srcs = [":framework-remoteauth-java-sources-udc-compat"]
+framework_remoteauth_api_srcs = [":framework-remoteauth-java-sources"]
 
 java_defaults {
     name: "enable-remoteauth-targets",
-    enabled: true,
+    enabled: false,
 }
 
 // Include build rules from Sources.bp
diff --git a/remoteauth/framework-udc-compat/Android.bp b/remoteauth/framework-udc-compat/Android.bp
new file mode 100644
index 0000000..799ffd0
--- /dev/null
+++ b/remoteauth/framework-udc-compat/Android.bp
@@ -0,0 +1,32 @@
+// Copyright (C) 2023 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+// Sources included in the framework-connectivity jar for compatibility
+// builds in udc branches. They are only compatibility stubs to make
+// the module build, since remoteauth is not available on U.
+filegroup {
+    name: "framework-remoteauth-java-sources-udc-compat",
+    srcs: [
+        "java/**/*.java",
+    ],
+    path: "java",
+    visibility: [
+        "//packages/modules/Connectivity/framework-t:__subpackages__",
+    ],
+}
+
diff --git a/remoteauth/framework-udc-compat/java/README.md b/remoteauth/framework-udc-compat/java/README.md
new file mode 100644
index 0000000..7a01308
--- /dev/null
+++ b/remoteauth/framework-udc-compat/java/README.md
@@ -0,0 +1,4 @@
+# RemoteAuth udc compatibility framework files
+
+This directory is created to contain compatibility implementations of RemoteAuth classes for builds
+in udc branches.
diff --git a/remoteauth/service-udc-compat/Android.bp b/remoteauth/service-udc-compat/Android.bp
new file mode 100644
index 0000000..69c667d
--- /dev/null
+++ b/remoteauth/service-udc-compat/Android.bp
@@ -0,0 +1,51 @@
+// Copyright (C) 2023 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+// Compatibility library included in the service-connectivity jar for
+// builds in udc branches. It only contains compatibility stubs to make
+// the module build, since remoteauth is not available on U.
+
+// Main lib for remoteauth services.
+java_library {
+    name: "service-remoteauth-pre-jarjar-udc-compat",
+    srcs: ["java/**/*.java"],
+
+    defaults: [
+        "framework-system-server-module-defaults"
+    ],
+    libs: [
+        "androidx.annotation_annotation",
+        "error_prone_annotations",
+    ],
+    sdk_version: "system_server_current",
+    // This is included in service-connectivity which is 30+
+    min_sdk_version: "30",
+
+    dex_preopt: {
+        enabled: false,
+        app_image: false,
+    },
+    visibility: [
+        "//packages/modules/Connectivity/service",
+        "//packages/modules/Connectivity/service-t",
+    ],
+    apex_available: [
+        "com.android.tethering",
+    ],
+}
+
diff --git a/remoteauth/service-udc-compat/java/com/android/server/remoteauth/RemoteAuthService.java b/remoteauth/service-udc-compat/java/com/android/server/remoteauth/RemoteAuthService.java
new file mode 100644
index 0000000..ac4fde1
--- /dev/null
+++ b/remoteauth/service-udc-compat/java/com/android/server/remoteauth/RemoteAuthService.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2023 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.server.remoteauth;
+
+import android.os.Binder;
+import android.content.Context;
+
+/** Compatibility stub for RemoteAuthService in udc branch builds. */
+public class RemoteAuthService extends Binder {
+    public static final String SERVICE_NAME = "remote_auth";
+    public RemoteAuthService(Context context) {
+        throw new UnsupportedOperationException("RemoteAuthService is not supported in this build");
+    }
+}
diff --git a/service-t/Android.bp b/service-t/Android.bp
index 779f354..012c076 100644
--- a/service-t/Android.bp
+++ b/service-t/Android.bp
@@ -20,7 +20,7 @@
     default_applicable_licenses: ["Android-Apache-2.0"],
 }
 
-service_remoteauth_pre_jarjar_lib = "service-remoteauth-pre-jarjar"
+service_remoteauth_pre_jarjar_lib = "service-remoteauth-pre-jarjar-udc-compat"
 
 // Include build rules from Sources.bp
 build = ["Sources.bp"]
diff --git a/service-t/src/com/android/server/net/NetworkStatsService.java b/service-t/src/com/android/server/net/NetworkStatsService.java
index 64b17eb..8b67137 100644
--- a/service-t/src/com/android/server/net/NetworkStatsService.java
+++ b/service-t/src/com/android/server/net/NetworkStatsService.java
@@ -1429,7 +1429,11 @@
     }
 
     @Override
-    public INetworkStatsSession openSessionForUsageStats(int flags, String callingPackage) {
+    public INetworkStatsSession openSessionForUsageStats(
+            int flags, @NonNull String callingPackage) {
+        Objects.requireNonNull(callingPackage);
+        PermissionUtils.enforcePackageNameMatchesUid(
+                mContext, Binder.getCallingUid(), callingPackage);
         return openSessionInternal(flags, callingPackage);
     }
 
@@ -1944,6 +1948,7 @@
 
         final int callingPid = Binder.getCallingPid();
         final int callingUid = Binder.getCallingUid();
+        PermissionUtils.enforcePackageNameMatchesUid(mContext, callingUid, callingPackage);
         @NetworkStatsAccess.Level int accessLevel = checkAccessLevel(callingPackage);
         DataUsageRequest normalizedRequest;
         final long token = Binder.clearCallingIdentity();
diff --git a/service/Android.bp b/service/Android.bp
index c35c4f8..322c4d3 100644
--- a/service/Android.bp
+++ b/service/Android.bp
@@ -20,7 +20,7 @@
     default_applicable_licenses: ["Android-Apache-2.0"],
 }
 
-service_remoteauth_pre_jarjar_lib = "service-remoteauth-pre-jarjar"
+service_remoteauth_pre_jarjar_lib = "service-remoteauth-pre-jarjar-udc-compat"
 
 // The above variables may have different values
 // depending on the branch, and this comment helps
diff --git a/tests/cts/hostside/Android.bp b/tests/cts/hostside/Android.bp
index f6c0430..92e7cfb 100644
--- a/tests/cts/hostside/Android.bp
+++ b/tests/cts/hostside/Android.bp
@@ -12,7 +12,7 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-next_app_data = [":CtsHostsideNetworkTestsAppNext"]
+next_app_data = []
 
 // The above line is put in place to prevent any future automerger merge conflict between aosp,
 // downstream branches. The CtsHostsideNetworkTestsAppNext target will not exist in
diff --git a/tests/unit/java/com/android/server/net/NetworkStatsServiceTest.java b/tests/unit/java/com/android/server/net/NetworkStatsServiceTest.java
index 3d7ad66..1afc13e 100644
--- a/tests/unit/java/com/android/server/net/NetworkStatsServiceTest.java
+++ b/tests/unit/java/com/android/server/net/NetworkStatsServiceTest.java
@@ -64,6 +64,7 @@
 import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
 import static android.text.format.DateUtils.WEEK_IN_MILLIS;
 
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.doThrow;
 import static com.android.server.net.NetworkStatsEventLogger.POLL_REASON_RAT_CHANGED;
 import static com.android.server.net.NetworkStatsEventLogger.PollEvent.pollReasonNameOf;
 import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_POLL;
@@ -98,6 +99,7 @@
 import android.app.AlarmManager;
 import android.content.Context;
 import android.content.Intent;
+import android.content.pm.PackageManager;
 import android.content.res.Resources;
 import android.database.ContentObserver;
 import android.net.DataUsageRequest;
@@ -124,7 +126,9 @@
 import android.os.HandlerThread;
 import android.os.IBinder;
 import android.os.PowerManager;
+import android.os.Process;
 import android.os.SimpleClock;
+import android.os.UserHandle;
 import android.provider.Settings;
 import android.system.ErrnoException;
 import android.telephony.TelephonyManager;
@@ -244,6 +248,7 @@
     private static @Mock WifiInfo sWifiInfo;
     private @Mock INetd mNetd;
     private @Mock TetheringManager mTetheringManager;
+    private @Mock PackageManager mPm;
     private @Mock NetworkStatsFactory mStatsFactory;
     @NonNull
     private final TestNetworkStatsSettings mSettings =
@@ -303,6 +308,16 @@
         }
 
         @Override
+        public PackageManager getPackageManager() {
+            return mPm;
+        }
+
+        @Override
+        public Context createContextAsUser(UserHandle user, int flags) {
+            return this;
+        }
+
+        @Override
         public Object getSystemService(String name) {
             if (Context.TELEPHONY_SERVICE.equals(name)) return mTelephonyManager;
             if (Context.TETHERING_SERVICE.equals(name)) return mTetheringManager;
@@ -412,6 +427,9 @@
                 any(), tetheringEventCbCaptor.capture());
         mTetheringEventCallback = tetheringEventCbCaptor.getValue();
 
+        doReturn(Process.myUid()).when(mPm)
+                .getPackageUid(eq(mServiceContext.getPackageName()), anyInt());
+
         mUsageCallback = new TestableUsageCallback(mUsageCallbackBinder);
     }
 
@@ -1573,7 +1591,7 @@
 
         // Register and verify request and that binder was called
         DataUsageRequest request = mService.registerUsageCallback(
-                mServiceContext.getOpPackageName(), inputRequest, mUsageCallback);
+                mServiceContext.getPackageName(), inputRequest, mUsageCallback);
         assertTrue(request.requestId > 0);
         assertTrue(Objects.equals(sTemplateWifi, request.template));
         long minThresholdInBytes = 2 * 1024 * 1024; // 2 MB
@@ -2786,6 +2804,38 @@
     }
 
     @Test
+    public void testEnforcePackageNameMatchesUid() throws Exception {
+        final String testMyPackageName = "test.package.myname";
+        final String testRedPackageName = "test.package.red";
+        final String testInvalidPackageName = "test.package.notfound";
+
+        doReturn(UID_RED).when(mPm).getPackageUid(eq(testRedPackageName), anyInt());
+        doReturn(Process.myUid()).when(mPm).getPackageUid(eq(testMyPackageName), anyInt());
+        doThrow(new PackageManager.NameNotFoundException()).when(mPm)
+                .getPackageUid(eq(testInvalidPackageName), anyInt());
+
+        assertThrows(SecurityException.class, () ->
+                mService.openSessionForUsageStats(0 /* flags */, testRedPackageName));
+        assertThrows(SecurityException.class, () ->
+                mService.openSessionForUsageStats(0 /* flags */, testInvalidPackageName));
+        assertThrows(NullPointerException.class, () ->
+                mService.openSessionForUsageStats(0 /* flags */, null));
+        // Verify package name belongs to ourselves does not throw.
+        mService.openSessionForUsageStats(0 /* flags */, testMyPackageName);
+
+        long thresholdInBytes = 10 * 1024 * 1024;  // 10 MB
+        DataUsageRequest request = new DataUsageRequest(
+                2 /* requestId */, sTemplateImsi1, thresholdInBytes);
+        assertThrows(SecurityException.class, () ->
+                mService.registerUsageCallback(testRedPackageName, request, mUsageCallback));
+        assertThrows(SecurityException.class, () ->
+                mService.registerUsageCallback(testInvalidPackageName, request, mUsageCallback));
+        assertThrows(NullPointerException.class, () ->
+                mService.registerUsageCallback(null, request, mUsageCallback));
+        mService.registerUsageCallback(testMyPackageName, request, mUsageCallback);
+    }
+
+    @Test
     public void testDumpSkDestroyListenerLogs() throws ErrnoException {
         doAnswer((invocation) -> {
             final IndentingPrintWriter ipw = (IndentingPrintWriter) invocation.getArgument(0);