summaryrefslogtreecommitdiff
path: root/adservices/service-core/java/com/android/adservices/service/appsetid/AppSetIdServiceImpl.java
blob: 8221309f82f3ad6e5beed9139e80f48cf8c2d2fc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
/*
 * 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.adservices.service.appsetid;

import static android.adservices.common.AdServicesStatusUtils.STATUS_BACKGROUND_CALLER;
import static android.adservices.common.AdServicesStatusUtils.STATUS_CALLER_NOT_ALLOWED;
import static android.adservices.common.AdServicesStatusUtils.STATUS_INTERNAL_ERROR;
import static android.adservices.common.AdServicesStatusUtils.STATUS_RATE_LIMIT_REACHED;
import static android.adservices.common.AdServicesStatusUtils.STATUS_SUCCESS;
import static android.adservices.common.AdServicesStatusUtils.STATUS_UNAUTHORIZED;

import static com.android.adservices.service.stats.AdServicesStatsLog.AD_SERVICES_API_CALLED__API_CLASS__APPSETID;
import static com.android.adservices.service.stats.AdServicesStatsLog.AD_SERVICES_API_CALLED__API_NAME__GET_APPSETID;

import android.adservices.appsetid.GetAppSetIdParam;
import android.adservices.appsetid.IAppSetIdService;
import android.adservices.appsetid.IGetAppSetIdCallback;
import android.adservices.common.AdServicesStatusUtils;
import android.adservices.common.CallerMetadata;
import android.annotation.NonNull;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Binder;
import android.os.Process;
import android.os.RemoteException;

import com.android.adservices.LogUtil;
import com.android.adservices.concurrency.AdServicesExecutors;
import com.android.adservices.service.Flags;
import com.android.adservices.service.common.AllowLists;
import com.android.adservices.service.common.AppImportanceFilter;
import com.android.adservices.service.common.AppImportanceFilter.WrongCallingApplicationStateException;
import com.android.adservices.service.common.SdkRuntimeUtil;
import com.android.adservices.service.common.Throttler;
import com.android.adservices.service.stats.AdServicesLogger;
import com.android.adservices.service.stats.AdServicesStatsLog;
import com.android.adservices.service.stats.ApiCallStats;
import com.android.adservices.service.stats.Clock;

import java.util.concurrent.Executor;

/**
 * Implementation of {@link IAppSetIdService}.
 *
 * @hide
 */
public class AppSetIdServiceImpl extends IAppSetIdService.Stub {
    private final Context mContext;
    private final AppSetIdWorker mAppSetIdWorker;
    private static final Executor sBackgroundExecutor = AdServicesExecutors.getBackgroundExecutor();
    private final AdServicesLogger mAdServicesLogger;
    private final Clock mClock;
    private final Flags mFlags;
    private final Throttler mThrottler;
    private final AppImportanceFilter mAppImportanceFilter;

    public AppSetIdServiceImpl(
            Context context,
            AppSetIdWorker appsetidWorker,
            AdServicesLogger adServicesLogger,
            Clock clock,
            Flags flags,
            Throttler throttler,
            AppImportanceFilter appImportanceFilter) {
        mContext = context;
        mAppSetIdWorker = appsetidWorker;
        mAdServicesLogger = adServicesLogger;
        mClock = clock;
        mFlags = flags;
        mThrottler = throttler;
        mAppImportanceFilter = appImportanceFilter;
    }

    @Override
    public void getAppSetId(
            @NonNull GetAppSetIdParam appSetIdParam,
            @NonNull CallerMetadata callerMetadata,
            @NonNull IGetAppSetIdCallback callback) {

        if (isThrottled(appSetIdParam, callback)) return;

        final long startServiceTime = mClock.elapsedRealtime();
        final String packageName = appSetIdParam.getAppPackageName();
        final String sdkPackageName = appSetIdParam.getSdkPackageName();

        // We need to save the Calling Uid before offloading to the background executor. Otherwise
        // the Binder.getCallingUid will return the PPAPI process Uid. This also needs to be final
        // since it's used in the lambda.
        final int callingUid = Binder.getCallingUidOrThrow();

        sBackgroundExecutor.execute(
                () -> {
                    int resultCode = STATUS_SUCCESS;
                    try {
                        if (!canCallerInvokeAppSetIdService(appSetIdParam, callingUid, callback)) {
                            return;
                        }
                        mAppSetIdWorker.getAppSetId(packageName, callingUid, callback);

                    } catch (Exception e) {
                        LogUtil.e(e, "Unable to send result to the callback");
                        resultCode = STATUS_INTERNAL_ERROR;
                    } finally {
                        long binderCallStartTimeMillis = callerMetadata.getBinderElapsedTimestamp();
                        long serviceLatency = mClock.elapsedRealtime() - startServiceTime;
                        // Double it to simulate the return binder time is same to call binder time
                        long binderLatency = (startServiceTime - binderCallStartTimeMillis) * 2;

                        final int apiLatency = (int) (serviceLatency + binderLatency);
                        mAdServicesLogger.logApiCallStats(
                                new ApiCallStats.Builder()
                                        .setCode(AdServicesStatsLog.AD_SERVICES_API_CALLED)
                                        .setApiClass(AD_SERVICES_API_CALLED__API_CLASS__APPSETID)
                                        .setApiName(AD_SERVICES_API_CALLED__API_NAME__GET_APPSETID)
                                        .setAppPackageName(packageName)
                                        .setSdkPackageName(sdkPackageName)
                                        .setLatencyMillisecond(apiLatency)
                                        .setResultCode(resultCode)
                                        .build());
                    }
                });
    }

    // Throttle the AppSetId API.
    // Return true if we should throttle (don't allow the API call).
    private boolean isThrottled(GetAppSetIdParam appSetIdParam, IGetAppSetIdCallback callback) {
        boolean throttled =
                !mThrottler.tryAcquire(
                        Throttler.ApiKey.APPSETID_API_APP_PACKAGE_NAME,
                        appSetIdParam.getAppPackageName());

        if (throttled) {
            LogUtil.e("Rate Limit Reached for APPSETID_API");
            try {
                callback.onError(STATUS_RATE_LIMIT_REACHED);
            } catch (RemoteException e) {
                LogUtil.e(e, "Fail to call the callback on Rate Limit Reached.");
            }
            return true;
        }
        return false;
    }

    // Enforce whether caller is from foreground.
    private void enforceForeground(int callingUid) {
        // If caller calls AppSetId API from Sandbox, regard it as foreground.
        // Also enable a flag to force switch on/off this enforcing.
        if (Process.isSdkSandboxUid(callingUid)
                || !mFlags.getEnforceForegroundStatusForAppSetId()) {
            return;
        }

        // Call utility method in AppImportanceFilter to enforce foreground status
        //  Throw WrongCallingApplicationStateException  if the assertion fails.
        mAppImportanceFilter.assertCallerIsInForeground(
                callingUid, AD_SERVICES_API_CALLED__API_NAME__GET_APPSETID, null);
    }

    /**
     * Check whether caller can invoke the AppSetId API. The caller is not allowed to do it when one
     * of the following occurs:
     *
     * <ul>
     *   <li>Caller is not allowed - not present in the allowed list.
     * </ul>
     *
     * @param appSetIdParam {@link GetAppSetIdParam} to get information about the request.
     * @param callback {@link IGetAppSetIdCallback} to invoke when caller is not allowed.
     * @return true if caller is allowed to invoke AppSetId API, false otherwise.
     */
    private boolean canCallerInvokeAppSetIdService(
            GetAppSetIdParam appSetIdParam, int callingUid, IGetAppSetIdCallback callback) {
        // Enforce caller calls AppSetId API from foreground.
        try {
            enforceForeground(callingUid);
        } catch (WrongCallingApplicationStateException backgroundCaller) {
            invokeCallbackWithStatus(
                    callback, STATUS_BACKGROUND_CALLER, backgroundCaller.getMessage());
            return false;
        }

        // This needs to access PhFlag which requires READ_DEVICE_CONFIG which
        // is not granted for binder thread. So we have to check it with one
        // of non-binder thread of the PPAPI.
        boolean appCanUsePpapi =
                AllowLists.isPackageAllowListed(
                        mFlags.getPpapiAppAllowList(), appSetIdParam.getAppPackageName());
        if (!appCanUsePpapi) {
            invokeCallbackWithStatus(
                    callback,
                    STATUS_CALLER_NOT_ALLOWED,
                    "Unauthorized caller. Caller is not allowed.");
            return false;
        }

        // Check whether calling package belongs to the callingUid
        int resultCode =
                enforceCallingPackageBelongsToUid(appSetIdParam.getAppPackageName(), callingUid);
        if (resultCode != STATUS_SUCCESS) {
            invokeCallbackWithStatus(callback, resultCode, "Caller is not authorized.");
            return false;
        }
        return true;
    }

    private void invokeCallbackWithStatus(
            IGetAppSetIdCallback callback,
            @AdServicesStatusUtils.StatusCode int statusCode,
            String message) {
        LogUtil.e(message);
        try {
            callback.onError(statusCode);
        } catch (RemoteException e) {
            LogUtil.e(e, String.format("Fail to call the callback. %s", message));
        }
    }

    // Enforce that the callingPackage has the callingUid.
    private int enforceCallingPackageBelongsToUid(String callingPackage, int callingUid) {
        int appCallingUid = SdkRuntimeUtil.getCallingAppUid(callingUid);
        int packageUid;
        try {
            packageUid = mContext.getPackageManager().getPackageUid(callingPackage, /* flags */ 0);
        } catch (PackageManager.NameNotFoundException e) {
            LogUtil.e(e, callingPackage + " not found");
            return STATUS_UNAUTHORIZED;
        }
        if (packageUid != appCallingUid) {
            LogUtil.e(callingPackage + " does not belong to uid " + callingUid);
            return STATUS_UNAUTHORIZED;
        }
        return STATUS_SUCCESS;
    }
}