summaryrefslogtreecommitdiff
path: root/adservices/service-core/java/com/android/adservices/service/devapi/AdSelectionOverrider.java
blob: 414d688ccb8f3ad3afa001ade98ebcbdf050e1b2 (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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
/*
 * 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.devapi;

import static com.android.adservices.service.stats.AdServicesStatsLog.AD_SERVICES_API_CALLED__API_NAME__OVERRIDE_AD_SELECTION_CONFIG_REMOTE_INFO;
import static com.android.adservices.service.stats.AdServicesStatsLog.AD_SERVICES_API_CALLED__API_NAME__REMOVE_AD_SELECTION_CONFIG_REMOTE_INFO_OVERRIDE;
import static com.android.adservices.service.stats.AdServicesStatsLog.AD_SERVICES_API_CALLED__API_NAME__RESET_ALL_AD_SELECTION_CONFIG_REMOTE_OVERRIDES;

import android.adservices.adselection.AdSelectionConfig;
import android.adservices.adselection.AdSelectionOverrideCallback;
import android.adservices.common.AdSelectionSignals;
import android.adservices.common.AdServicesStatusUtils;
import android.adservices.common.FledgeErrorResponse;
import android.annotation.NonNull;
import android.content.pm.PackageManager;
import android.os.RemoteException;

import com.android.adservices.LogUtil;
import com.android.adservices.data.adselection.AdSelectionEntryDao;
import com.android.adservices.service.Flags;
import com.android.adservices.service.common.AppImportanceFilter;
import com.android.adservices.service.common.AppImportanceFilter.WrongCallingApplicationStateException;
import com.android.adservices.service.consent.ConsentManager;
import com.android.adservices.service.stats.AdServicesLogger;

import com.google.common.util.concurrent.FluentFuture;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;

import java.util.Objects;
import java.util.concurrent.ExecutorService;

/** Encapsulates the AdSelection Override Logic */
public class AdSelectionOverrider {
    @NonNull private final AdSelectionEntryDao mAdSelectionEntryDao;
    @NonNull private final ListeningExecutorService mLightweightExecutorService;
    @NonNull private final ListeningExecutorService mBackgroundExecutorService;
    @NonNull private final AdSelectionDevOverridesHelper mAdSelectionDevOverridesHelper;
    @NonNull private final PackageManager mPackageManager;
    @NonNull private final ConsentManager mConsentManager;
    @NonNull private final AdServicesLogger mAdServicesLogger;
    @NonNull private final Flags mFlags;
    @NonNull private final AppImportanceFilter mAppImportanceFilter;
    private final int mCallerUid;

    /**
     * Creates an instance of {@link AdSelectionOverrider} with the given {@link DevContext}, {@link
     * AdSelectionEntryDao}, executor, and {@link AdSelectionDevOverridesHelper}.
     */
    public AdSelectionOverrider(
            @NonNull DevContext devContext,
            @NonNull AdSelectionEntryDao adSelectionEntryDao,
            @NonNull ExecutorService lightweightExecutorService,
            @NonNull ExecutorService backgroundExecutorService,
            @NonNull PackageManager packageManager,
            @NonNull ConsentManager consentManager,
            @NonNull AdServicesLogger adServicesLogger,
            @NonNull AppImportanceFilter appImportanceFilter,
            @NonNull final Flags flags,
            int callerUid) {
        Objects.requireNonNull(devContext);
        Objects.requireNonNull(adSelectionEntryDao);
        Objects.requireNonNull(lightweightExecutorService);
        Objects.requireNonNull(backgroundExecutorService);
        Objects.requireNonNull(packageManager);
        Objects.requireNonNull(consentManager);
        Objects.requireNonNull(adServicesLogger);
        Objects.requireNonNull(appImportanceFilter);
        Objects.requireNonNull(flags);

        this.mAdSelectionEntryDao = adSelectionEntryDao;
        this.mLightweightExecutorService =
                MoreExecutors.listeningDecorator(lightweightExecutorService);
        this.mBackgroundExecutorService =
                MoreExecutors.listeningDecorator(backgroundExecutorService);
        this.mAdSelectionDevOverridesHelper =
                new AdSelectionDevOverridesHelper(devContext, mAdSelectionEntryDao);
        this.mPackageManager = packageManager;
        this.mConsentManager = consentManager;
        this.mAdServicesLogger = adServicesLogger;
        mFlags = flags;
        mAppImportanceFilter = appImportanceFilter;
        mCallerUid = callerUid;
    }

    /**
     * Configures our fetching logic relating to {@code adSelectionConfig} to use {@code
     * decisionLogicJS} instead of fetching from remote servers
     *
     * @param callback callback function to be called in case of success or failure
     */
    public void addOverride(
            @NonNull AdSelectionConfig adSelectionConfig,
            @NonNull String decisionLogicJS,
            @NonNull AdSelectionSignals trustedScoringSignals,
            @NonNull AdSelectionOverrideCallback callback) {
        // Auto-generated variable name is too long for lint check
        int shortApiName =
                AD_SERVICES_API_CALLED__API_NAME__OVERRIDE_AD_SELECTION_CONFIG_REMOTE_INFO;

        FluentFuture.from(
                        mLightweightExecutorService.submit(
                                () -> {
                                    // Cannot read pH flags in the binder thread so this
                                    // checks will be done in a spawn thread.
                                    if (mFlags.getEnforceForegroundStatusForFledgeOverrides()) {
                                        mAppImportanceFilter.assertCallerIsInForeground(
                                                mCallerUid, shortApiName, null);
                                    }

                                    return null;
                                }))
                .transformAsync(
                        ignoredVoid ->
                                callAddOverride(
                                        adSelectionConfig, decisionLogicJS, trustedScoringSignals),
                        mLightweightExecutorService)
                .addCallback(
                        new FutureCallback<Integer>() {
                            @Override
                            public void onSuccess(Integer result) {
                                LogUtil.d("Add dev override succeeded!");
                                invokeSuccess(callback, shortApiName, result);
                            }

                            @Override
                            public void onFailure(Throwable t) {
                                LogUtil.e(t, "Add dev override failed!");
                                notifyFailureToCaller(callback, t, shortApiName);
                            }
                        },
                        mLightweightExecutorService);
    }

    /**
     * Removes a decision logic override matching this {@code adSelectionConfig} and {@code
     * appPackageName}
     *
     * @param callback callback function to be called in case of success or failure
     */
    public void removeOverride(
            @NonNull AdSelectionConfig adSelectionConfig,
            @NonNull AdSelectionOverrideCallback callback) {
        // Auto-generated variable name is too long for lint check
        int shortApiName =
                AD_SERVICES_API_CALLED__API_NAME__REMOVE_AD_SELECTION_CONFIG_REMOTE_INFO_OVERRIDE;

        FluentFuture.from(
                        mLightweightExecutorService.submit(
                                () -> {
                                    // Cannot read pH flags in the binder thread so this
                                    // checks will be done in a spawn thread.
                                    if (mFlags.getEnforceForegroundStatusForFledgeOverrides()) {
                                        mAppImportanceFilter.assertCallerIsInForeground(
                                                mCallerUid, shortApiName, null);
                                    }

                                    return null;
                                }))
                .transformAsync(
                        ignoredVoid -> callRemoveOverride(adSelectionConfig),
                        mLightweightExecutorService)
                .addCallback(
                        new FutureCallback<Integer>() {
                            @Override
                            public void onSuccess(Integer result) {
                                LogUtil.d("Removing dev override succeeded!");
                                invokeSuccess(callback, shortApiName, result);
                            }

                            @Override
                            public void onFailure(Throwable t) {
                                LogUtil.e(t, "Removing dev override failed!");
                                notifyFailureToCaller(callback, t, shortApiName);
                            }
                        },
                        mLightweightExecutorService);
    }

    /**
     * Removes all ad selection overrides matching the {@code appPackageName}
     *
     * @param callback callback function to be called in case of success or failure
     */
    public void removeAllOverrides(@NonNull AdSelectionOverrideCallback callback) {
        // Auto-generated variable name is too long for lint check
        int shortApiName =
                AD_SERVICES_API_CALLED__API_NAME__RESET_ALL_AD_SELECTION_CONFIG_REMOTE_OVERRIDES;

        FluentFuture.from(
                        mLightweightExecutorService.submit(
                                () -> {
                                    // Cannot read pH flags in the binder thread so this
                                    // checks will be done in a spawn thread.
                                    if (mFlags.getEnforceForegroundStatusForFledgeOverrides()) {
                                        mAppImportanceFilter.assertCallerIsInForeground(
                                                mCallerUid, shortApiName, null);
                                    }

                                    return null;
                                }))
                .transformAsync(
                        ignoredVoid -> callRemoveAllOverrides(), mLightweightExecutorService)
                .addCallback(
                        new FutureCallback<Integer>() {
                            @Override
                            public void onSuccess(Integer result) {
                                LogUtil.d("Removing all dev overrides succeeded!");
                                invokeSuccess(callback, shortApiName, result);
                            }

                            @Override
                            public void onFailure(Throwable t) {
                                LogUtil.e(t, "Removing all dev overrides failed!");
                                notifyFailureToCaller(callback, t, shortApiName);
                            }
                        },
                        mLightweightExecutorService);
    }

    private FluentFuture<Integer> callAddOverride(
            @NonNull AdSelectionConfig adSelectionConfig,
            @NonNull String decisionLogicJS,
            @NonNull AdSelectionSignals trustedScoringSignals) {
        return FluentFuture.from(
                mBackgroundExecutorService.submit(
                        () -> {
                            if (!mConsentManager.getConsent(mPackageManager).isGiven()) {
                                return AdServicesStatusUtils.STATUS_USER_CONSENT_REVOKED;
                            }

                            mAdSelectionDevOverridesHelper.addAdSelectionSellerOverride(
                                    adSelectionConfig, decisionLogicJS, trustedScoringSignals);
                            return AdServicesStatusUtils.STATUS_SUCCESS;
                        }));
    }

    private FluentFuture<Integer> callRemoveOverride(@NonNull AdSelectionConfig adSelectionConfig) {
        return FluentFuture.from(
                mBackgroundExecutorService.submit(
                        () -> {
                            if (!mConsentManager.getConsent(mPackageManager).isGiven()) {
                                return AdServicesStatusUtils.STATUS_USER_CONSENT_REVOKED;
                            }

                            mAdSelectionDevOverridesHelper.removeAdSelectionSellerOverride(
                                    adSelectionConfig);
                            return AdServicesStatusUtils.STATUS_SUCCESS;
                        }));
    }

    private FluentFuture<Integer> callRemoveAllOverrides() {
        return FluentFuture.from(
                mBackgroundExecutorService.submit(
                        () -> {
                            if (!mConsentManager.getConsent(mPackageManager).isGiven()) {
                                return AdServicesStatusUtils.STATUS_USER_CONSENT_REVOKED;
                            }

                            mAdSelectionDevOverridesHelper.removeAllDecisionLogicOverrides();
                            return AdServicesStatusUtils.STATUS_SUCCESS;
                        }));
    }

    /** Invokes the onFailure function from the callback and handles the exception. */
    private void invokeFailure(
            @NonNull AdSelectionOverrideCallback callback,
            int statusCode,
            String errorMessage,
            int apiName) {
        int resultCode = statusCode;
        try {
            callback.onFailure(
                    new FledgeErrorResponse.Builder()
                            .setStatusCode(statusCode)
                            .setErrorMessage(errorMessage)
                            .build());
        } catch (RemoteException e) {
            LogUtil.e(e, "Unable to send failed result to the callback");
            resultCode = AdServicesStatusUtils.STATUS_UNKNOWN_ERROR;
            throw e.rethrowFromSystemServer();
        } finally {
            mAdServicesLogger.logFledgeApiCallStats(apiName, resultCode);
        }
    }

    /** Invokes the onSuccess function from the callback and handles the exception. */
    private void invokeSuccess(
            @NonNull AdSelectionOverrideCallback callback, int apiName, Integer resultCode) {
        int resultCodeInt = AdServicesStatusUtils.STATUS_UNSET;
        if (resultCode != null) {
            resultCodeInt = resultCode;
        }
        try {
            callback.onSuccess();
        } catch (RemoteException e) {
            LogUtil.e(e, "Unable to send successful result to the callback");
            resultCodeInt = AdServicesStatusUtils.STATUS_UNKNOWN_ERROR;
            throw e.rethrowFromSystemServer();
        } finally {
            mAdServicesLogger.logFledgeApiCallStats(apiName, resultCodeInt);
        }
    }

    private void notifyFailureToCaller(
            @NonNull AdSelectionOverrideCallback callback, @NonNull Throwable t, int apiName) {
        if (t instanceof IllegalArgumentException) {
            invokeFailure(
                    callback,
                    AdServicesStatusUtils.STATUS_INVALID_ARGUMENT,
                    t.getMessage(),
                    apiName);
        } else if (t instanceof WrongCallingApplicationStateException) {
            invokeFailure(
                    callback,
                    AdServicesStatusUtils.STATUS_BACKGROUND_CALLER,
                    t.getMessage(),
                    apiName);
        } else if (t instanceof IllegalStateException) {
            invokeFailure(
                    callback, AdServicesStatusUtils.STATUS_INTERNAL_ERROR, t.getMessage(), apiName);
        } else {
            invokeFailure(
                    callback, AdServicesStatusUtils.STATUS_UNAUTHORIZED, t.getMessage(), apiName);
        }
    }
}