1 /*
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.adservices.service.adselection;
18 
19 import static android.adservices.common.AdServicesStatusUtils.STATUS_INTERNAL_ERROR;
20 import static android.adservices.common.AdServicesStatusUtils.STATUS_INVALID_ARGUMENT;
21 import static android.adservices.common.AdServicesStatusUtils.STATUS_KILLSWITCH_ENABLED;
22 import static android.adservices.common.AdServicesStatusUtils.STATUS_SUCCESS;
23 
24 import static com.android.adservices.service.stats.AdServicesStatsLog.AD_SERVICES_API_CALLED__API_CLASS__FLEDGE;
25 import static com.android.adservices.service.stats.AdServicesStatsLog.AD_SERVICES_API_CALLED__API_NAME__API_NAME_UNKNOWN;
26 import static com.android.adservices.service.stats.AdServicesStatsLog.AD_SERVICES_API_CALLED__API_NAME__OVERRIDE_AD_SELECTION_CONFIG_REMOTE_INFO;
27 import static com.android.adservices.service.stats.AdServicesStatsLog.AD_SERVICES_API_CALLED__API_NAME__REMOVE_AD_SELECTION_CONFIG_REMOTE_INFO_OVERRIDE;
28 import static com.android.adservices.service.stats.AdServicesStatsLog.AD_SERVICES_API_CALLED__API_NAME__REPORT_IMPRESSION;
29 import static com.android.adservices.service.stats.AdServicesStatsLog.AD_SERVICES_API_CALLED__API_NAME__REPORT_INTERACTION;
30 import static com.android.adservices.service.stats.AdServicesStatsLog.AD_SERVICES_API_CALLED__API_NAME__RESET_ALL_AD_SELECTION_CONFIG_REMOTE_OVERRIDES;
31 import static com.android.adservices.service.stats.AdServicesStatsLog.AD_SERVICES_API_CALLED__API_NAME__UPDATE_AD_COUNTER_HISTOGRAM;
32 
33 import android.adservices.adselection.AdSelectionCallback;
34 import android.adservices.adselection.AdSelectionConfig;
35 import android.adservices.adselection.AdSelectionFromOutcomesConfig;
36 import android.adservices.adselection.AdSelectionFromOutcomesInput;
37 import android.adservices.adselection.AdSelectionInput;
38 import android.adservices.adselection.AdSelectionOverrideCallback;
39 import android.adservices.adselection.AdSelectionService;
40 import android.adservices.adselection.GetAdSelectionDataCallback;
41 import android.adservices.adselection.GetAdSelectionDataInput;
42 import android.adservices.adselection.PerBuyerDecisionLogic;
43 import android.adservices.adselection.PersistAdSelectionResultCallback;
44 import android.adservices.adselection.PersistAdSelectionResultInput;
45 import android.adservices.adselection.RemoveAdCounterHistogramOverrideInput;
46 import android.adservices.adselection.ReportImpressionCallback;
47 import android.adservices.adselection.ReportImpressionInput;
48 import android.adservices.adselection.ReportInteractionCallback;
49 import android.adservices.adselection.ReportInteractionInput;
50 import android.adservices.adselection.SetAdCounterHistogramOverrideInput;
51 import android.adservices.adselection.SetAppInstallAdvertisersCallback;
52 import android.adservices.adselection.SetAppInstallAdvertisersInput;
53 import android.adservices.adselection.UpdateAdCounterHistogramCallback;
54 import android.adservices.adselection.UpdateAdCounterHistogramInput;
55 import android.adservices.common.AdSelectionSignals;
56 import android.adservices.common.AdServicesPermissions;
57 import android.adservices.common.CallerMetadata;
58 import android.annotation.NonNull;
59 import android.content.Context;
60 import android.os.Binder;
61 import android.os.Build;
62 import android.os.RemoteException;
63 
64 import androidx.annotation.Nullable;
65 import androidx.annotation.RequiresApi;
66 
67 import com.android.adservices.LoggerFactory;
68 import com.android.adservices.concurrency.AdServicesExecutors;
69 import com.android.adservices.data.adselection.AdSelectionDatabase;
70 import com.android.adservices.data.adselection.AdSelectionDebugReportDao;
71 import com.android.adservices.data.adselection.AdSelectionDebugReportingDatabase;
72 import com.android.adservices.data.adselection.AdSelectionEntryDao;
73 import com.android.adservices.data.adselection.AppInstallDao;
74 import com.android.adservices.data.adselection.FrequencyCapDao;
75 import com.android.adservices.data.adselection.SharedStorageDatabase;
76 import com.android.adservices.data.customaudience.CustomAudienceDao;
77 import com.android.adservices.data.customaudience.CustomAudienceDatabase;
78 import com.android.adservices.data.encryptionkey.EncryptionKeyDao;
79 import com.android.adservices.data.enrollment.EnrollmentDao;
80 import com.android.adservices.data.signals.EncodedPayloadDao;
81 import com.android.adservices.data.signals.ProtectedSignalsDatabase;
82 import com.android.adservices.service.DebugFlags;
83 import com.android.adservices.service.Flags;
84 import com.android.adservices.service.FlagsFactory;
85 import com.android.adservices.service.adid.AdIdWorker;
86 import com.android.adservices.service.adselection.debug.ConsentedDebugConfigurationGeneratorFactory;
87 import com.android.adservices.service.common.AdRenderIdValidator;
88 import com.android.adservices.service.common.AdSelectionServiceFilter;
89 import com.android.adservices.service.common.AppImportanceFilter;
90 import com.android.adservices.service.common.BinderFlagReader;
91 import com.android.adservices.service.common.CallingAppUidSupplier;
92 import com.android.adservices.service.common.CallingAppUidSupplierBinderImpl;
93 import com.android.adservices.service.common.FledgeAllowListsFilter;
94 import com.android.adservices.service.common.FledgeApiThrottleFilter;
95 import com.android.adservices.service.common.FledgeAuthorizationFilter;
96 import com.android.adservices.service.common.FledgeConsentFilter;
97 import com.android.adservices.service.common.RetryStrategyFactory;
98 import com.android.adservices.service.common.Throttler;
99 import com.android.adservices.service.common.cache.CacheProviderFactory;
100 import com.android.adservices.service.common.httpclient.AdServicesHttpsClient;
101 import com.android.adservices.service.consent.ConsentManager;
102 import com.android.adservices.service.devapi.AdSelectionOverrider;
103 import com.android.adservices.service.devapi.DevContext;
104 import com.android.adservices.service.devapi.DevContextFilter;
105 import com.android.adservices.service.js.JSSandboxIsNotAvailableException;
106 import com.android.adservices.service.js.JSScriptEngine;
107 import com.android.adservices.service.kanon.KAnonSignJoinFactory;
108 import com.android.adservices.service.measurement.MeasurementImpl;
109 import com.android.adservices.service.profiling.Tracing;
110 import com.android.adservices.service.signals.EgressConfigurationGenerator;
111 import com.android.adservices.service.stats.AdSelectionExecutionLogger;
112 import com.android.adservices.service.stats.AdServicesLogger;
113 import com.android.adservices.service.stats.AdServicesLoggerImpl;
114 import com.android.adservices.service.stats.AdServicesStatsLog;
115 import com.android.adservices.service.stats.AdsRelevanceExecutionLogger;
116 import com.android.adservices.service.stats.AdsRelevanceExecutionLoggerFactory;
117 import com.android.adservices.service.stats.ReportImpressionExecutionLogger;
118 import com.android.adservices.service.stats.ReportImpressionExecutionLoggerFactory;
119 import com.android.adservices.service.stats.SelectAdsFromOutcomesExecutionLogger;
120 import com.android.adservices.service.stats.SelectAdsFromOutcomesExecutionLoggerFactory;
121 import com.android.adservices.shared.util.Clock;
122 import com.android.internal.annotations.VisibleForTesting;
123 
124 import com.google.common.util.concurrent.FluentFuture;
125 import com.google.common.util.concurrent.FutureCallback;
126 import com.google.common.util.concurrent.ListenableFuture;
127 
128 import java.util.Arrays;
129 import java.util.HashSet;
130 import java.util.Objects;
131 import java.util.Set;
132 import java.util.concurrent.ExecutorService;
133 import java.util.concurrent.ScheduledThreadPoolExecutor;
134 
135 /**
136  * Implementation of {@link AdSelectionService}.
137  *
138  * @hide
139  */
140 @RequiresApi(Build.VERSION_CODES.S)
141 public class AdSelectionServiceImpl extends AdSelectionService.Stub {
142     @VisibleForTesting
143     static final String AUCTION_SERVER_API_IS_NOT_AVAILABLE =
144             "Auction Server API is not available!";
145 
146     @VisibleForTesting
147     public static final Set<String> PERMISSIONS_SET =
148             new HashSet<>(
149                     Arrays.asList(
150                             AdServicesPermissions.ACCESS_ADSERVICES_CUSTOM_AUDIENCE,
151                             AdServicesPermissions.ACCESS_ADSERVICES_PROTECTED_SIGNALS,
152                             AdServicesPermissions.ACCESS_ADSERVICES_AD_SELECTION));
153 
154     private static final LoggerFactory.Logger sLogger = LoggerFactory.getFledgeLogger();
155     @NonNull private final AdSelectionEntryDao mAdSelectionEntryDao;
156     @NonNull private final AppInstallDao mAppInstallDao;
157     @NonNull private final CustomAudienceDao mCustomAudienceDao;
158     @NonNull private final EncodedPayloadDao mEncodedPayloadDao;
159     @NonNull private final FrequencyCapDao mFrequencyCapDao;
160     @NonNull private final EncryptionKeyDao mEncryptionKeyDao;
161     @NonNull private final EnrollmentDao mEnrollmentDao;
162     @NonNull private final AdServicesHttpsClient mAdServicesHttpsClient;
163     @NonNull private final ExecutorService mLightweightExecutor;
164     @NonNull private final ExecutorService mBackgroundExecutor;
165     @NonNull private final ScheduledThreadPoolExecutor mScheduledExecutor;
166     @NonNull private final Context mContext;
167     @NonNull private final DevContextFilter mDevContextFilter;
168     @NonNull private final AdServicesLogger mAdServicesLogger;
169     @NonNull private final Flags mFlags;
170     @NonNull private final CallingAppUidSupplier mCallingAppUidSupplier;
171     @NonNull private final FledgeAuthorizationFilter mFledgeAuthorizationFilter;
172     @NonNull private final AdSelectionServiceFilter mAdSelectionServiceFilter;
173     @NonNull private final AdFilteringFeatureFactory mAdFilteringFeatureFactory;
174     @NonNull private final ConsentManager mConsentManager;
175     @NonNull private final AdRenderIdValidator mAdRenderIdValidator;
176     @NonNull private final AdSelectionDebugReportDao mAdSelectionDebugReportDao;
177     @NonNull private final AdIdFetcher mAdIdFetcher;
178     @NonNull private final MultiCloudSupportStrategy mMultiCloudSupportStrategy;
179     @NonNull KAnonSignJoinFactory mKAnonSignJoinFactory;
180     private final boolean mShouldUseUnifiedTables;
181     private static final String API_NOT_AUTHORIZED_MSG =
182             "This API is not enabled for the given app because either dev options are disabled or"
183                     + " the app is not debuggable.";
184     @NonNull private final RetryStrategyFactory mRetryStrategyFactory;
185 
186     @NonNull
187     private final ConsentedDebugConfigurationGeneratorFactory
188             mConsentedDebugConfigurationGeneratorFactory;
189 
190     @NonNull private final EgressConfigurationGenerator mEgressConfigurationGenerator;
191     private final boolean mConsoleMessageInLogsEnabled;
192 
193     @VisibleForTesting
AdSelectionServiceImpl( @onNull AdSelectionEntryDao adSelectionEntryDao, @NonNull AppInstallDao appInstallDao, @NonNull CustomAudienceDao customAudienceDao, @NonNull EncodedPayloadDao encodedPayloadDao, @NonNull FrequencyCapDao frequencyCapDao, @NonNull EncryptionKeyDao encryptionKeyDao, @NonNull EnrollmentDao enrollmentDao, @NonNull AdServicesHttpsClient adServicesHttpsClient, @NonNull DevContextFilter devContextFilter, @NonNull ExecutorService lightweightExecutorService, @NonNull ExecutorService backgroundExecutorService, @NonNull ScheduledThreadPoolExecutor scheduledExecutor, @NonNull Context context, @NonNull AdServicesLogger adServicesLogger, @NonNull Flags flags, @NonNull CallingAppUidSupplier callingAppUidSupplier, @NonNull FledgeAuthorizationFilter fledgeAuthorizationFilter, @NonNull AdSelectionServiceFilter adSelectionServiceFilter, @NonNull AdFilteringFeatureFactory adFilteringFeatureFactory, @NonNull ConsentManager consentManager, @NonNull MultiCloudSupportStrategy multiCloudSupportStrategy, @NonNull AdSelectionDebugReportDao adSelectionDebugReportDao, @NonNull AdIdFetcher adIdFetcher, @NonNull KAnonSignJoinFactory kAnonSignJoinFactory, boolean shouldUseUnifiedTables, @NonNull RetryStrategyFactory retryStrategyFactory, @NonNull ConsentedDebugConfigurationGeneratorFactory consentedDebugConfigurationGeneratorFactory, @NonNull EgressConfigurationGenerator egressConfigurationGenerator, boolean consoleMessageInLogsEnabled)194     public AdSelectionServiceImpl(
195             @NonNull AdSelectionEntryDao adSelectionEntryDao,
196             @NonNull AppInstallDao appInstallDao,
197             @NonNull CustomAudienceDao customAudienceDao,
198             @NonNull EncodedPayloadDao encodedPayloadDao,
199             @NonNull FrequencyCapDao frequencyCapDao,
200             @NonNull EncryptionKeyDao encryptionKeyDao,
201             @NonNull EnrollmentDao enrollmentDao,
202             @NonNull AdServicesHttpsClient adServicesHttpsClient,
203             @NonNull DevContextFilter devContextFilter,
204             @NonNull ExecutorService lightweightExecutorService,
205             @NonNull ExecutorService backgroundExecutorService,
206             @NonNull ScheduledThreadPoolExecutor scheduledExecutor,
207             @NonNull Context context,
208             @NonNull AdServicesLogger adServicesLogger,
209             @NonNull Flags flags,
210             @NonNull CallingAppUidSupplier callingAppUidSupplier,
211             @NonNull FledgeAuthorizationFilter fledgeAuthorizationFilter,
212             @NonNull AdSelectionServiceFilter adSelectionServiceFilter,
213             @NonNull AdFilteringFeatureFactory adFilteringFeatureFactory,
214             @NonNull ConsentManager consentManager,
215             @NonNull MultiCloudSupportStrategy multiCloudSupportStrategy,
216             @NonNull AdSelectionDebugReportDao adSelectionDebugReportDao,
217             @NonNull AdIdFetcher adIdFetcher,
218             @NonNull KAnonSignJoinFactory kAnonSignJoinFactory,
219             boolean shouldUseUnifiedTables,
220             @NonNull RetryStrategyFactory retryStrategyFactory,
221             @NonNull
222                     ConsentedDebugConfigurationGeneratorFactory
223                             consentedDebugConfigurationGeneratorFactory,
224             @NonNull EgressConfigurationGenerator egressConfigurationGenerator,
225             boolean consoleMessageInLogsEnabled) {
226         Objects.requireNonNull(context, "Context must be provided.");
227         Objects.requireNonNull(adSelectionEntryDao);
228         Objects.requireNonNull(appInstallDao);
229         Objects.requireNonNull(customAudienceDao);
230         Objects.requireNonNull(encodedPayloadDao);
231         Objects.requireNonNull(frequencyCapDao);
232         Objects.requireNonNull(encryptionKeyDao);
233         Objects.requireNonNull(enrollmentDao);
234         Objects.requireNonNull(adServicesHttpsClient);
235         Objects.requireNonNull(devContextFilter);
236         Objects.requireNonNull(lightweightExecutorService);
237         Objects.requireNonNull(backgroundExecutorService);
238         Objects.requireNonNull(scheduledExecutor);
239         Objects.requireNonNull(adServicesLogger);
240         Objects.requireNonNull(flags);
241         Objects.requireNonNull(adFilteringFeatureFactory);
242         Objects.requireNonNull(consentManager);
243         Objects.requireNonNull(multiCloudSupportStrategy);
244         Objects.requireNonNull(adSelectionDebugReportDao);
245         Objects.requireNonNull(adIdFetcher);
246         Objects.requireNonNull(kAnonSignJoinFactory);
247         Objects.requireNonNull(retryStrategyFactory);
248         Objects.requireNonNull(consentedDebugConfigurationGeneratorFactory);
249         Objects.requireNonNull(egressConfigurationGenerator);
250 
251         mAdSelectionEntryDao = adSelectionEntryDao;
252         mAppInstallDao = appInstallDao;
253         mCustomAudienceDao = customAudienceDao;
254         mEncodedPayloadDao = encodedPayloadDao;
255         mFrequencyCapDao = frequencyCapDao;
256         mEncryptionKeyDao = encryptionKeyDao;
257         mEnrollmentDao = enrollmentDao;
258         mAdServicesHttpsClient = adServicesHttpsClient;
259         mDevContextFilter = devContextFilter;
260         mLightweightExecutor = lightweightExecutorService;
261         mBackgroundExecutor = backgroundExecutorService;
262         mScheduledExecutor = scheduledExecutor;
263         mContext = context;
264         mAdServicesLogger = adServicesLogger;
265         mFlags = flags;
266         mCallingAppUidSupplier = callingAppUidSupplier;
267         mFledgeAuthorizationFilter = fledgeAuthorizationFilter;
268         mAdSelectionServiceFilter = adSelectionServiceFilter;
269         mAdFilteringFeatureFactory = adFilteringFeatureFactory;
270         mConsentManager = consentManager;
271         // No support for renderId on device
272         mAdRenderIdValidator = AdRenderIdValidator.AD_RENDER_ID_VALIDATOR_NO_OP;
273         mMultiCloudSupportStrategy = multiCloudSupportStrategy;
274         mAdSelectionDebugReportDao = adSelectionDebugReportDao;
275         mAdIdFetcher = adIdFetcher;
276         mShouldUseUnifiedTables = shouldUseUnifiedTables;
277         mKAnonSignJoinFactory = kAnonSignJoinFactory;
278         mRetryStrategyFactory = retryStrategyFactory;
279         mConsentedDebugConfigurationGeneratorFactory = consentedDebugConfigurationGeneratorFactory;
280         mEgressConfigurationGenerator = egressConfigurationGenerator;
281         mConsoleMessageInLogsEnabled = consoleMessageInLogsEnabled;
282     }
283 
284     /** Creates a new instance of {@link AdSelectionServiceImpl}. */
create(@onNull Context context)285     public static AdSelectionServiceImpl create(@NonNull Context context) {
286         return new AdSelectionServiceImpl(context);
287     }
288 
289     /** Creates an instance of {@link AdSelectionServiceImpl} to be used. */
AdSelectionServiceImpl(@onNull Context context)290     private AdSelectionServiceImpl(@NonNull Context context) {
291         this(
292                 AdSelectionDatabase.getInstance(context).adSelectionEntryDao(),
293                 SharedStorageDatabase.getInstance(context).appInstallDao(),
294                 CustomAudienceDatabase.getInstance(context).customAudienceDao(),
295                 ProtectedSignalsDatabase.getInstance().getEncodedPayloadDao(),
296                 SharedStorageDatabase.getInstance(context).frequencyCapDao(),
297                 EncryptionKeyDao.getInstance(),
298                 EnrollmentDao.getInstance(),
299                 new AdServicesHttpsClient(
300                         AdServicesExecutors.getBlockingExecutor(),
301                         CacheProviderFactory.create(context, FlagsFactory.getFlags())),
302                 DevContextFilter.create(context),
303                 AdServicesExecutors.getLightWeightExecutor(),
304                 AdServicesExecutors.getBackgroundExecutor(),
305                 AdServicesExecutors.getScheduler(),
306                 context,
307                 AdServicesLoggerImpl.getInstance(),
308                 FlagsFactory.getFlags(),
309                 CallingAppUidSupplierBinderImpl.create(),
310                 FledgeAuthorizationFilter.create(context, AdServicesLoggerImpl.getInstance()),
311                 new AdSelectionServiceFilter(
312                         context,
313                         new FledgeConsentFilter(
314                                 ConsentManager.getInstance(), AdServicesLoggerImpl.getInstance()),
315                         FlagsFactory.getFlags(),
316                         AppImportanceFilter.create(
317                                 context,
318                                 AD_SERVICES_API_CALLED__API_CLASS__FLEDGE,
319                                 () ->
320                                         FlagsFactory.getFlags()
321                                                 .getForegroundStatuslLevelForValidation()),
322                         FledgeAuthorizationFilter.create(
323                                 context, AdServicesLoggerImpl.getInstance()),
324                         new FledgeAllowListsFilter(
325                                 FlagsFactory.getFlags(), AdServicesLoggerImpl.getInstance()),
326                         new FledgeApiThrottleFilter(
327                                 Throttler.getInstance(FlagsFactory.getFlags()),
328                                 AdServicesLoggerImpl.getInstance())),
329                 new AdFilteringFeatureFactory(
330                         SharedStorageDatabase.getInstance(context).appInstallDao(),
331                         SharedStorageDatabase.getInstance(context).frequencyCapDao(),
332                         FlagsFactory.getFlags()),
333                 ConsentManager.getInstance(),
334                 MultiCloudSupportStrategyFactory.getStrategy(
335                         FlagsFactory.getFlags().getFledgeAuctionServerMultiCloudEnabled(),
336                         FlagsFactory.getFlags().getFledgeAuctionServerCoordinatorUrlAllowlist()),
337                 AdSelectionDebugReportingDatabase.getInstance(context)
338                         .getAdSelectionDebugReportDao(),
339                 new AdIdFetcher(
340                         context,
341                         AdIdWorker.getInstance(),
342                         AdServicesExecutors.getLightWeightExecutor(),
343                         AdServicesExecutors.getScheduler()),
344                 new KAnonSignJoinFactory(context),
345                 BinderFlagReader.readFlag(
346                         () ->
347                                 FlagsFactory.getFlags()
348                                         .getFledgeOnDeviceAuctionShouldUseUnifiedTables()),
349                 RetryStrategyFactory.createInstance(
350                         BinderFlagReader.readFlag(
351                                 () -> FlagsFactory.getFlags().getAdServicesRetryStrategyEnabled()),
352                         AdServicesExecutors.getLightWeightExecutor()),
353                 new ConsentedDebugConfigurationGeneratorFactory(
354                         BinderFlagReader.readFlag(
355                                 () ->
356                                         DebugFlags.getInstance()
357                                                 .getFledgeAuctionServerConsentedDebuggingEnabled()),
358                         AdSelectionDatabase.getInstance(context).consentedDebugConfigurationDao()),
359                 EgressConfigurationGenerator.createInstance(
360                         BinderFlagReader.readFlag(
361                                 () ->
362                                         FlagsFactory.getFlags()
363                                                 .getFledgeAuctionServerEnablePasUnlimitedEgress()),
364                         new AdIdFetcher(
365                                 context,
366                                 AdIdWorker.getInstance(),
367                                 AdServicesExecutors.getLightWeightExecutor(),
368                                 AdServicesExecutors.getScheduler()),
369                         BinderFlagReader.readFlag(
370                                 () ->
371                                         FlagsFactory.getFlags()
372                                                 .getFledgeAuctionServerAdIdFetcherTimeoutMs()),
373                         AdServicesExecutors.getLightWeightExecutor()),
374                 BinderFlagReader.readFlag(
375                         () ->
376                                 DebugFlags.getInstance()
377                                         .getAdServicesJsIsolateConsoleMessagesInLogsEnabled()));
378     }
379 
380     @Override
getAdSelectionData( GetAdSelectionDataInput inputParams, CallerMetadata callerMetadata, GetAdSelectionDataCallback callback)381     public void getAdSelectionData(
382             GetAdSelectionDataInput inputParams,
383             CallerMetadata callerMetadata,
384             GetAdSelectionDataCallback callback)
385             throws RemoteException {
386         int e2eTraceCookie = Tracing.beginAsyncSection(Tracing.GET_AD_SELECTION_DATA);
387         int apiName = AdServicesStatsLog.AD_SERVICES_API_CALLED__API_NAME__GET_AD_SELECTION_DATA;
388 
389         AdsRelevanceExecutionLoggerFactory adsRelevanceExecutionLoggerFactory =
390                 new AdsRelevanceExecutionLoggerFactory(
391                         inputParams.getCallerPackageName(),
392                         callerMetadata,
393                         Clock.getInstance(),
394                         mAdServicesLogger,
395                         mFlags,
396                         apiName);
397         final AdsRelevanceExecutionLogger adsRelevanceExecutionLogger =
398                 adsRelevanceExecutionLoggerFactory.getAdsRelevanceExecutionLogger();
399 
400         if (BinderFlagReader.readFlag(mFlags::getFledgeAuctionServerKillSwitch)) {
401             mAdServicesLogger.logFledgeApiCallStats(
402                     apiName,
403                     inputParams.getCallerPackageName(),
404                     STATUS_KILLSWITCH_ENABLED,
405                     /*latencyMs=*/ 0);
406             throw new IllegalStateException(AUCTION_SERVER_API_IS_NOT_AVAILABLE);
407         }
408 
409         try {
410             Objects.requireNonNull(inputParams);
411             Objects.requireNonNull(inputParams.getSeller());
412             Objects.requireNonNull(callback);
413         } catch (NullPointerException e) {
414             sLogger.v("The getAdSelectionData() arguments should not be null!");
415             mAdServicesLogger.logFledgeApiCallStats(
416                     apiName,
417                     inputParams.getCallerPackageName(),
418                     STATUS_INVALID_ARGUMENT,
419                     /*latencyMs=*/ 0);
420             // Rethrow because we want to fail fast
421             throw e;
422         }
423 
424         // Caller permissions must be checked in the binder thread, before anything else
425         mFledgeAuthorizationFilter.assertAppDeclaredAnyPermission(
426                 mContext, inputParams.getCallerPackageName(), apiName, PERMISSIONS_SET);
427 
428         int callingUid = getCallingUid(apiName);
429         final DevContext devContext = mDevContextFilter.createDevContext();
430         mLightweightExecutor.execute(
431                 () -> {
432                     runGetAdSelectionData(
433                             inputParams,
434                             callback,
435                             callingUid,
436                             devContext,
437                             adsRelevanceExecutionLogger,
438                             e2eTraceCookie);
439                 });
440     }
441 
442     @Override
persistAdSelectionResult( PersistAdSelectionResultInput inputParams, CallerMetadata callerMetadata, PersistAdSelectionResultCallback callback)443     public void persistAdSelectionResult(
444             PersistAdSelectionResultInput inputParams,
445             CallerMetadata callerMetadata,
446             PersistAdSelectionResultCallback callback)
447             throws RemoteException {
448         int traceCookie = Tracing.beginAsyncSection(Tracing.PERSIST_AD_SELECTION_RESULT);
449         int apiName =
450                 AdServicesStatsLog.AD_SERVICES_API_CALLED__API_NAME__PERSIST_AD_SELECTION_RESULT;
451 
452         AdsRelevanceExecutionLoggerFactory adsRelevanceExecutionLoggerFactory =
453                 new AdsRelevanceExecutionLoggerFactory(
454                         inputParams.getCallerPackageName(),
455                         callerMetadata,
456                         Clock.getInstance(),
457                         mAdServicesLogger,
458                         mFlags,
459                         apiName);
460         final AdsRelevanceExecutionLogger adsRelevanceExecutionLogger =
461                 adsRelevanceExecutionLoggerFactory.getAdsRelevanceExecutionLogger();
462 
463         if (BinderFlagReader.readFlag(mFlags::getFledgeAuctionServerKillSwitch)) {
464             mAdServicesLogger.logFledgeApiCallStats(
465                     apiName,
466                     inputParams.getCallerPackageName(),
467                     STATUS_KILLSWITCH_ENABLED,
468                     /* latencyMs= */ 0);
469             throw new IllegalStateException(AUCTION_SERVER_API_IS_NOT_AVAILABLE);
470         }
471 
472         try {
473             Objects.requireNonNull(inputParams);
474             Objects.requireNonNull(inputParams.getSeller());
475             Objects.requireNonNull(callback);
476         } catch (NullPointerException e) {
477             sLogger.v("The processAdSelectionResult() arguments should not be null!");
478             mAdServicesLogger.logFledgeApiCallStats(
479                     apiName,
480                     inputParams.getCallerPackageName(),
481                     STATUS_INVALID_ARGUMENT,
482                     /*latencyMs=*/ 0);
483             // Rethrow because we want to fail fast
484             throw e;
485         }
486 
487         // Caller permissions must be checked in the binder thread, before anything else
488         mFledgeAuthorizationFilter.assertAppDeclaredAnyPermission(
489                 mContext, inputParams.getCallerPackageName(), apiName, PERMISSIONS_SET);
490 
491         int callingUid = getCallingUid(apiName);
492         final DevContext devContext = mDevContextFilter.createDevContext();
493         final long overallTimeout =
494                 BinderFlagReader.readFlag(mFlags::getFledgeAuctionServerOverallTimeoutMs);
495         final boolean forceSearchOnAbsentOwner =
496                 BinderFlagReader.readFlag(
497                         mFlags::getFledgeAuctionServerForceSearchWhenOwnerIsAbsentEnabled);
498         final boolean auctionServerEnabledForUpdateHistogram =
499                 BinderFlagReader.readFlag(mFlags::getFledgeAuctionServerEnabledForUpdateHistogram);
500 
501         PersistAdSelectionResultRunner.ReportingRegistrationLimits limits =
502                 PersistAdSelectionResultRunner.ReportingRegistrationLimits.builder()
503                         .setMaxRegisteredAdBeaconsTotalCount(
504                                 BinderFlagReader.readFlag(
505                                         mFlags
506                                                 ::getFledgeReportImpressionMaxRegisteredAdBeaconsTotalCount))
507                         .setMaxInteractionKeySize(
508                                 BinderFlagReader.readFlag(
509                                         mFlags
510                                                 ::getFledgeReportImpressionRegisteredAdBeaconsMaxInteractionKeySizeB))
511                         .setMaxInteractionReportingUriSize(
512                                 BinderFlagReader.readFlag(
513                                         mFlags
514                                                 ::getFledgeReportImpressionMaxInteractionReportingUriSizeB))
515                         .setMaxRegisteredAdBeaconsPerAdTechCount(
516                                 BinderFlagReader.readFlag(
517                                         mFlags
518                                                 ::getFledgeReportImpressionMaxRegisteredAdBeaconsPerAdTechCount))
519                         .build();
520         AuctionResultValidator auctionResultValidator =
521                 new AuctionResultValidator(
522                         mFledgeAuthorizationFilter,
523                         BinderFlagReader.readFlag(mFlags::getDisableFledgeEnrollmentCheck));
524         mLightweightExecutor.execute(
525                 () -> {
526                     PersistAdSelectionResultRunner runner =
527                             new PersistAdSelectionResultRunner(
528                                     mMultiCloudSupportStrategy.getObliviousHttpEncryptor(
529                                             mContext, mFlags),
530                                     mAdSelectionEntryDao,
531                                     mCustomAudienceDao,
532                                     mAdSelectionServiceFilter,
533                                     mBackgroundExecutor,
534                                     mLightweightExecutor,
535                                     mScheduledExecutor,
536                                     callingUid,
537                                     devContext,
538                                     overallTimeout,
539                                     forceSearchOnAbsentOwner,
540                                     limits,
541                                     mAdFilteringFeatureFactory.getAdCounterHistogramUpdater(
542                                             mAdSelectionEntryDao,
543                                             auctionServerEnabledForUpdateHistogram),
544                                     auctionResultValidator,
545                                     mFlags,
546                                     mAdServicesLogger,
547                                     adsRelevanceExecutionLogger,
548                                     mKAnonSignJoinFactory);
549                     runner.run(inputParams, callback);
550                     Tracing.endAsyncSection(Tracing.PERSIST_AD_SELECTION_RESULT, traceCookie);
551                 });
552     }
553 
554     // TODO(b/233116758): Validate all the fields inside the adSelectionConfig.
555     @Override
selectAds( @onNull AdSelectionInput inputParams, @NonNull CallerMetadata callerMetadata, @NonNull AdSelectionCallback callback)556     public void selectAds(
557             @NonNull AdSelectionInput inputParams,
558             @NonNull CallerMetadata callerMetadata,
559             @NonNull AdSelectionCallback callback) {
560         selectAds(inputParams, callerMetadata, callback, null);
561     }
562 
563     /**
564      * This method takes an extra callback which is triggered once all background tasks for ad
565      * selection are complete. Only required for testing.
566      */
567     @VisibleForTesting
selectAds( @onNull AdSelectionInput inputParams, @NonNull CallerMetadata callerMetadata, @NonNull AdSelectionCallback partialCallback, @Nullable AdSelectionCallback fullCallback)568     public void selectAds(
569             @NonNull AdSelectionInput inputParams,
570             @NonNull CallerMetadata callerMetadata,
571             @NonNull AdSelectionCallback partialCallback,
572             @Nullable AdSelectionCallback fullCallback) {
573         final AdSelectionExecutionLogger adSelectionExecutionLogger =
574                 new AdSelectionExecutionLogger(
575                         callerMetadata, Clock.getInstance(), mContext, mAdServicesLogger, mFlags);
576         int apiName = AdServicesStatsLog.AD_SERVICES_API_CALLED__API_NAME__SELECT_ADS;
577 
578         try {
579             Objects.requireNonNull(inputParams);
580             Objects.requireNonNull(partialCallback);
581         } catch (NullPointerException exception) {
582             int overallLatencyMs = adSelectionExecutionLogger.getRunAdSelectionOverallLatencyInMs();
583             sLogger.v(
584                     "The selectAds(AdSelectionConfig) arguments should not be null, failed with"
585                             + " overall latency %d in ms.",
586                     overallLatencyMs);
587             mAdServicesLogger.logFledgeApiCallStats(
588                     apiName,
589                     inputParams.getCallerPackageName(),
590                     STATUS_INVALID_ARGUMENT,
591                     overallLatencyMs);
592             // Rethrow because we want to fail fast
593             throw exception;
594         }
595 
596         // Caller permissions must be checked in the binder thread, before anything else
597         mFledgeAuthorizationFilter.assertAppDeclaredAnyPermission(
598                 mContext, inputParams.getCallerPackageName(), apiName, PERMISSIONS_SET);
599 
600         int callingUid = getCallingUid(apiName);
601 
602         DevContext devContext = mDevContextFilter.createDevContext();
603         final boolean auctionServerEnabledForUpdateHistogram =
604                 BinderFlagReader.readFlag(mFlags::getFledgeAuctionServerEnabledForUpdateHistogram);
605         mLightweightExecutor.execute(
606                 () ->
607                         runAdSelection(
608                                 inputParams,
609                                 partialCallback,
610                                 fullCallback,
611                                 adSelectionExecutionLogger,
612                                 callingUid,
613                                 devContext,
614                                 auctionServerEnabledForUpdateHistogram));
615     }
616 
runGetAdSelectionData( GetAdSelectionDataInput inputParams, GetAdSelectionDataCallback callback, int callingUid, DevContext devContext, AdsRelevanceExecutionLogger adsRelevanceExecutionLogger, int e2eTraceCookie)617     private void runGetAdSelectionData(
618             GetAdSelectionDataInput inputParams,
619             GetAdSelectionDataCallback callback,
620             int callingUid,
621             DevContext devContext,
622             AdsRelevanceExecutionLogger adsRelevanceExecutionLogger,
623             int e2eTraceCookie) {
624         ListenableFuture<AuctionServerDebugReporting> auctionServerDebugReportingFuture =
625                 AuctionServerDebugReporting.createInstance(
626                         mFlags,
627                         mAdIdFetcher,
628                         inputParams.getCallerPackageName(),
629                         callingUid,
630                         mLightweightExecutor);
631 
632         FluentFuture.from(auctionServerDebugReportingFuture)
633                 .addCallback(
634                         new FutureCallback<>() {
635                             @Override
636                             public void onSuccess(
637                                     AuctionServerDebugReporting auctionServerDebugReporting) {
638                                 sLogger.v(
639                                         "Auction Server Debug reporting enabled: %b",
640                                         auctionServerDebugReporting.isEnabled());
641 
642                                 GetAdSelectionDataRunner runner =
643                                         new GetAdSelectionDataRunner(
644                                                 mContext,
645                                                 e2eTraceCookie,
646                                                 mMultiCloudSupportStrategy,
647                                                 mAdSelectionEntryDao,
648                                                 mCustomAudienceDao,
649                                                 mEncodedPayloadDao,
650                                                 mAdSelectionServiceFilter,
651                                                 mAdFilteringFeatureFactory
652                                                         .getFrequencyCapAdFilterer(),
653                                                 mBackgroundExecutor,
654                                                 mLightweightExecutor,
655                                                 AdServicesExecutors.getBlockingExecutor(),
656                                                 mScheduledExecutor,
657                                                 mFlags,
658                                                 callingUid,
659                                                 devContext,
660                                                 auctionServerDebugReporting,
661                                                 adsRelevanceExecutionLogger,
662                                                 mAdServicesLogger,
663                                                 getAuctionServerPayloadMetricsStrategy(mFlags),
664                                                 mConsentedDebugConfigurationGeneratorFactory
665                                                         .create(),
666                                                 mEgressConfigurationGenerator,
667                                                 mAdFilteringFeatureFactory
668                                                         .getAppInstallAdFilterer());
669                                 runner.run(inputParams, callback);
670                             }
671 
672                             @Override
673                             public void onFailure(Throwable t) {
674                                 sLogger.e(
675                                         t,
676                                         "Failed to create Auction Server Debug Reporting instance,"
677                                                 + " debug reporting is disabled");
678                                 GetAdSelectionDataRunner runner =
679                                         new GetAdSelectionDataRunner(
680                                                 mContext,
681                                                 e2eTraceCookie,
682                                                 mMultiCloudSupportStrategy,
683                                                 mAdSelectionEntryDao,
684                                                 mCustomAudienceDao,
685                                                 mEncodedPayloadDao,
686                                                 mAdSelectionServiceFilter,
687                                                 mAdFilteringFeatureFactory
688                                                         .getFrequencyCapAdFilterer(),
689                                                 mBackgroundExecutor,
690                                                 mLightweightExecutor,
691                                                 AdServicesExecutors.getBlockingExecutor(),
692                                                 mScheduledExecutor,
693                                                 mFlags,
694                                                 callingUid,
695                                                 devContext,
696                                                 AuctionServerDebugReporting
697                                                         .createForDebugReportingDisabled(),
698                                                 adsRelevanceExecutionLogger,
699                                                 mAdServicesLogger,
700                                                 getAuctionServerPayloadMetricsStrategy(mFlags),
701                                                 mConsentedDebugConfigurationGeneratorFactory
702                                                         .create(),
703                                                 mEgressConfigurationGenerator,
704                                                 mAdFilteringFeatureFactory
705                                                         .getAppInstallAdFilterer());
706                                 runner.run(inputParams, callback);
707                             }
708                         },
709                         mLightweightExecutor);
710     }
711 
getAuctionServerPayloadMetricsStrategy( Flags flags)712     private AuctionServerPayloadMetricsStrategy getAuctionServerPayloadMetricsStrategy(
713             Flags flags) {
714         if (flags.getFledgeAuctionServerGetAdSelectionDataPayloadMetricsEnabled()) {
715             if (flags.getFledgeAuctionServerKeyFetchMetricsEnabled()) {
716                 return new AuctionServerPayloadMetricsStrategyWithKeyFetchEnabled(
717                         mAdServicesLogger);
718             }
719             return new AuctionServerPayloadMetricsStrategyEnabled(mAdServicesLogger);
720         }
721         return new AuctionServerPayloadMetricsStrategyDisabled();
722     }
723 
runAdSelection( AdSelectionInput inputParams, AdSelectionCallback partialCallback, @Nullable AdSelectionCallback fullCallback, AdSelectionExecutionLogger adSelectionExecutionLogger, int callingUid, DevContext devContext, boolean auctionServerEnabledForUpdateHistogram)724     private void runAdSelection(
725             AdSelectionInput inputParams,
726             AdSelectionCallback partialCallback,
727             @Nullable AdSelectionCallback fullCallback,
728             AdSelectionExecutionLogger adSelectionExecutionLogger,
729             int callingUid,
730             DevContext devContext,
731             boolean auctionServerEnabledForUpdateHistogram) {
732 
733         ListenableFuture<DebugReporting> debugReportingFuture =
734                 DebugReporting.createInstance(
735                         mContext,
736                         mFlags,
737                         mAdServicesHttpsClient,
738                         devContext,
739                         mAdSelectionDebugReportDao,
740                         mLightweightExecutor,
741                         mAdIdFetcher,
742                         inputParams.getCallerPackageName(),
743                         callingUid);
744 
745         FluentFuture.from(debugReportingFuture)
746                 .addCallback(
747                         new FutureCallback<>() {
748                             @Override
749                             public void onSuccess(DebugReporting debugReporting) {
750                                 sLogger.v(
751                                         "Debug reporting enabled: %b", debugReporting.isEnabled());
752                                 runAdSelectionWithDebugReporting(
753                                         inputParams,
754                                         partialCallback,
755                                         fullCallback,
756                                         adSelectionExecutionLogger,
757                                         callingUid,
758                                         devContext,
759                                         auctionServerEnabledForUpdateHistogram,
760                                         debugReporting);
761                             }
762 
763                             @Override
764                             public void onFailure(Throwable t) {
765                                 sLogger.e(
766                                         t,
767                                         "Failed to create Debug Reporting instance, debug reporting"
768                                                 + " is disabled");
769                                 runAdSelectionWithDebugReporting(
770                                         inputParams,
771                                         partialCallback,
772                                         fullCallback,
773                                         adSelectionExecutionLogger,
774                                         callingUid,
775                                         devContext,
776                                         auctionServerEnabledForUpdateHistogram,
777                                         new DebugReportingDisabled());
778                             }
779                         },
780                         mLightweightExecutor);
781     }
782 
runAdSelectionWithDebugReporting( AdSelectionInput inputParams, AdSelectionCallback partialCallback, @Nullable AdSelectionCallback fullCallback, AdSelectionExecutionLogger adSelectionExecutionLogger, int callingUid, DevContext devContext, boolean auctionServerEnabledForUpdateHistogram, @NonNull DebugReporting debugReporting)783     private void runAdSelectionWithDebugReporting(
784             AdSelectionInput inputParams,
785             AdSelectionCallback partialCallback,
786             @Nullable AdSelectionCallback fullCallback,
787             AdSelectionExecutionLogger adSelectionExecutionLogger,
788             int callingUid,
789             DevContext devContext,
790             boolean auctionServerEnabledForUpdateHistogram,
791             @NonNull DebugReporting debugReporting) {
792 
793         OnDeviceAdSelectionRunner runner =
794                 new OnDeviceAdSelectionRunner(
795                         mCustomAudienceDao,
796                         mAdSelectionEntryDao,
797                         mEncryptionKeyDao,
798                         mEnrollmentDao,
799                         mAdServicesHttpsClient,
800                         mLightweightExecutor,
801                         mBackgroundExecutor,
802                         mScheduledExecutor,
803                         mAdServicesLogger,
804                         devContext,
805                         mFlags,
806                         adSelectionExecutionLogger,
807                         mAdSelectionServiceFilter,
808                         mAdFilteringFeatureFactory.getFrequencyCapAdFilterer(),
809                         mAdFilteringFeatureFactory.getAdCounterKeyCopier(),
810                         mAdFilteringFeatureFactory.getAdCounterHistogramUpdater(
811                                 mAdSelectionEntryDao, auctionServerEnabledForUpdateHistogram),
812                         mAdFilteringFeatureFactory.getFrequencyCapAdDataValidator(),
813                         debugReporting,
814                         callingUid,
815                         mShouldUseUnifiedTables,
816                         mRetryStrategyFactory.createRetryStrategy(
817                                 mFlags.getAdServicesJsScriptEngineMaxRetryAttempts()),
818                         mKAnonSignJoinFactory,
819                         mAdFilteringFeatureFactory.getAppInstallAdFilterer(),
820                         mConsoleMessageInLogsEnabled);
821         runner.runAdSelection(inputParams, partialCallback, devContext, fullCallback);
822     }
823 
824     /**
825      * Returns an ultimate winner ad of given list of previous winner ads.
826      *
827      * @param inputParams includes list of outcomes, signals and uri to download selection logic
828      * @param callerMetadata caller's metadata for stat logging
829      * @param callback delivers the results via OutcomeReceiver
830      */
831     @Override
selectAdsFromOutcomes( @onNull AdSelectionFromOutcomesInput inputParams, @NonNull CallerMetadata callerMetadata, @NonNull AdSelectionCallback callback)832     public void selectAdsFromOutcomes(
833             @NonNull AdSelectionFromOutcomesInput inputParams,
834             @NonNull CallerMetadata callerMetadata,
835             @NonNull AdSelectionCallback callback)
836             throws RemoteException {
837         int apiName = AdServicesStatsLog.AD_SERVICES_API_CALLED__API_NAME__SELECT_ADS_FROM_OUTCOMES;
838 
839         SelectAdsFromOutcomesExecutionLogger selectAdsFromOutcomesExecutionLogger =
840                 new SelectAdsFromOutcomesExecutionLoggerFactory(
841                                 Clock.getInstance(), mAdServicesLogger, mFlags)
842                         .getSelectAdsFromOutcomesExecutionLogger();
843 
844         try {
845             Objects.requireNonNull(inputParams);
846             Objects.requireNonNull(callback);
847         } catch (NullPointerException e) {
848             sLogger.v(
849                     "The selectAds(AdSelectionFromOutcomesConfig) arguments should not be null,"
850                             + " failed");
851             mAdServicesLogger.logFledgeApiCallStats(
852                     apiName,
853                     inputParams.getCallerPackageName(),
854                     STATUS_INVALID_ARGUMENT,
855                     /*latencyMs=*/ 0);
856             // Rethrow because we want to fail fast
857             throw e;
858         }
859 
860         // Caller permissions must be checked in the binder thread, before anything else
861         mFledgeAuthorizationFilter.assertAppDeclaredAnyPermission(
862                 mContext, inputParams.getCallerPackageName(), apiName, PERMISSIONS_SET);
863 
864         int callingUid = getCallingUid(apiName);
865 
866         DevContext devContext = mDevContextFilter.createDevContext();
867         mLightweightExecutor.execute(
868                 () -> {
869                     OutcomeSelectionRunner runner =
870                             new OutcomeSelectionRunner(
871                                     mAdSelectionEntryDao,
872                                     mBackgroundExecutor,
873                                     mLightweightExecutor,
874                                     mScheduledExecutor,
875                                     mAdServicesHttpsClient,
876                                     mAdServicesLogger,
877                                     devContext,
878                                     mContext,
879                                     mFlags,
880                                     mAdSelectionServiceFilter,
881                                     mAdFilteringFeatureFactory.getAdCounterKeyCopier(),
882                                     callingUid,
883                                     mShouldUseUnifiedTables,
884                                     mRetryStrategyFactory.createRetryStrategy(
885                                             mFlags.getAdServicesJsScriptEngineMaxRetryAttempts()),
886                                     mConsoleMessageInLogsEnabled);
887                     runner.runOutcomeSelection(
888                             inputParams, callback, selectAdsFromOutcomesExecutionLogger);
889                 });
890     }
891 
892     @Override
reportImpression( @onNull ReportImpressionInput requestParams, @NonNull ReportImpressionCallback callback)893     public void reportImpression(
894             @NonNull ReportImpressionInput requestParams,
895             @NonNull ReportImpressionCallback callback) {
896         int apiName = AD_SERVICES_API_CALLED__API_NAME__REPORT_IMPRESSION;
897 
898         try {
899             Objects.requireNonNull(requestParams);
900             Objects.requireNonNull(callback);
901         } catch (NullPointerException exception) {
902             mAdServicesLogger.logFledgeApiCallStats(
903                     apiName, STATUS_INVALID_ARGUMENT, /*latencyMs=*/ 0);
904             // Rethrow because we want to fail fast
905             throw exception;
906         }
907 
908         // Caller permissions must be checked in the binder thread, before anything else
909         mFledgeAuthorizationFilter.assertAppDeclaredAnyPermission(
910                 mContext, requestParams.getCallerPackageName(), apiName, PERMISSIONS_SET);
911 
912         DevContext devContext = mDevContextFilter.createDevContext();
913 
914         int callingUid = getCallingUid(apiName);
915 
916         ReportImpressionExecutionLogger reportImpressionExecutionLogger =
917                 new ReportImpressionExecutionLoggerFactory(mAdServicesLogger, mFlags)
918                         .getReportImpressionExecutionLogger();
919 
920         // ImpressionReporter enables Auction Server flow reporting and sets the stage for Phase 2
921         // in go/rb-rm-unified-flow-reporting whereas ImpressionReporterLegacy is the logic before
922         // Phase 1. FLEDGE_AUCTION_SERVER_REPORTING_ENABLED flag controls which logic is called.
923         if (BinderFlagReader.readFlag(mFlags::getFledgeAuctionServerEnabledForReportImpression)) {
924             ImpressionReporter reporter =
925                     new ImpressionReporter(
926                             mLightweightExecutor,
927                             mBackgroundExecutor,
928                             mScheduledExecutor,
929                             mAdSelectionEntryDao,
930                             mCustomAudienceDao,
931                             mAdServicesHttpsClient,
932                             devContext,
933                             mAdServicesLogger,
934                             mFlags,
935                             mAdSelectionServiceFilter,
936                             mFledgeAuthorizationFilter,
937                             mAdFilteringFeatureFactory.getFrequencyCapAdDataValidator(),
938                             callingUid,
939                             mRetryStrategyFactory.createRetryStrategy(
940                                     BinderFlagReader.readFlag(
941                                             mFlags::getAdServicesJsScriptEngineMaxRetryAttempts)),
942                             mShouldUseUnifiedTables,
943                             reportImpressionExecutionLogger);
944             reporter.reportImpression(requestParams, callback);
945         } else {
946             ImpressionReporterLegacy reporter =
947                     new ImpressionReporterLegacy(
948                             mLightweightExecutor,
949                             mBackgroundExecutor,
950                             mScheduledExecutor,
951                             mAdSelectionEntryDao,
952                             mCustomAudienceDao,
953                             mAdServicesHttpsClient,
954                             devContext,
955                             mAdServicesLogger,
956                             mFlags,
957                             mAdSelectionServiceFilter,
958                             mFledgeAuthorizationFilter,
959                             mAdFilteringFeatureFactory.getFrequencyCapAdDataValidator(),
960                             callingUid,
961                             mShouldUseUnifiedTables,
962                             mRetryStrategyFactory.createRetryStrategy(
963                                     BinderFlagReader.readFlag(
964                                             mFlags::getAdServicesJsScriptEngineMaxRetryAttempts)),
965                             reportImpressionExecutionLogger);
966             reporter.reportImpression(requestParams, callback);
967         }
968     }
969 
970     @Override
reportInteraction( @onNull ReportInteractionInput inputParams, @NonNull ReportInteractionCallback callback)971     public void reportInteraction(
972             @NonNull ReportInteractionInput inputParams,
973             @NonNull ReportInteractionCallback callback) {
974         int apiName = AD_SERVICES_API_CALLED__API_NAME__REPORT_INTERACTION;
975 
976         try {
977             Objects.requireNonNull(inputParams);
978             Objects.requireNonNull(callback);
979         } catch (NullPointerException exception) {
980             mAdServicesLogger.logFledgeApiCallStats(
981                     apiName, STATUS_INVALID_ARGUMENT, /*latencyMs=*/ 0);
982             // Rethrow because we want to fail fast
983             throw exception;
984         }
985 
986         // Caller permissions must be checked in the binder thread, before anything else
987         mFledgeAuthorizationFilter.assertAppDeclaredAnyPermission(
988                 mContext, inputParams.getCallerPackageName(), apiName, PERMISSIONS_SET);
989 
990         int callerUid = getCallingUid(apiName);
991         DevContext devContext = mDevContextFilter.createDevContext();
992 
993         // Get an instance of measurement service
994         // Binder identity is cleared and eventually restored to allow reading values of device
995         // config flags.
996         MeasurementImpl measurementService;
997         final long token = Binder.clearCallingIdentity();
998         try {
999             measurementService = MeasurementImpl.getInstance(mContext);
1000         } finally {
1001             Binder.restoreCallingIdentity(token);
1002         }
1003 
1004         // Get an instance of the event reporter
1005         EventReporter eventReporter =
1006                 new EventReporterFactory(
1007                                 mAdSelectionEntryDao,
1008                                 mAdServicesHttpsClient,
1009                                 mLightweightExecutor,
1010                                 mBackgroundExecutor,
1011                                 mAdServicesLogger,
1012                                 mFlags,
1013                                 mAdSelectionServiceFilter,
1014                                 callerUid,
1015                                 mFledgeAuthorizationFilter,
1016                                 devContext,
1017                                 measurementService,
1018                                 mConsentManager,
1019                                 mContext,
1020                                 mShouldUseUnifiedTables)
1021                         .getEventReporter();
1022 
1023         eventReporter.reportInteraction(inputParams, callback);
1024     }
1025 
1026     @Override
setAppInstallAdvertisers( @onNull SetAppInstallAdvertisersInput request, @NonNull SetAppInstallAdvertisersCallback callback)1027     public void setAppInstallAdvertisers(
1028             @NonNull SetAppInstallAdvertisersInput request,
1029             @NonNull SetAppInstallAdvertisersCallback callback)
1030             throws RemoteException {
1031         int apiName =
1032                 AdServicesStatsLog.AD_SERVICES_API_CALLED__API_NAME__SET_APP_INSTALL_ADVERTISERS;
1033 
1034         try {
1035             Objects.requireNonNull(request);
1036             Objects.requireNonNull(callback);
1037         } catch (NullPointerException exception) {
1038             mAdServicesLogger.logFledgeApiCallStats(
1039                     apiName, STATUS_INVALID_ARGUMENT, /*latencyMs=*/ 0);
1040             // Rethrow because we want to fail fast
1041             throw exception;
1042         }
1043 
1044         // Caller permissions must be checked in the binder thread, before anything else
1045         mFledgeAuthorizationFilter.assertAppDeclaredAnyPermission(
1046                 mContext, request.getCallerPackageName(), apiName, PERMISSIONS_SET);
1047 
1048         AppInstallAdvertisersSetter setter =
1049                 new AppInstallAdvertisersSetter(
1050                         mAppInstallDao,
1051                         mBackgroundExecutor,
1052                         mAdServicesLogger,
1053                         mFlags,
1054                         mAdSelectionServiceFilter,
1055                         mConsentManager,
1056                         getCallingUid(apiName),
1057                         mDevContextFilter.createDevContext());
1058         setter.setAppInstallAdvertisers(request, callback);
1059     }
1060 
1061     @Override
updateAdCounterHistogram( @onNull UpdateAdCounterHistogramInput inputParams, @NonNull UpdateAdCounterHistogramCallback callback)1062     public void updateAdCounterHistogram(
1063             @NonNull UpdateAdCounterHistogramInput inputParams,
1064             @NonNull UpdateAdCounterHistogramCallback callback) {
1065         int apiName = AD_SERVICES_API_CALLED__API_NAME__UPDATE_AD_COUNTER_HISTOGRAM;
1066 
1067         try {
1068             Objects.requireNonNull(inputParams);
1069             Objects.requireNonNull(callback);
1070         } catch (NullPointerException exception) {
1071             mAdServicesLogger.logFledgeApiCallStats(
1072                     apiName, STATUS_INVALID_ARGUMENT, /*latencyMs=*/ 0);
1073             // Rethrow because we want to fail fast
1074             throw exception;
1075         }
1076 
1077         // Caller permissions must be checked in the binder thread, before anything else
1078         mFledgeAuthorizationFilter.assertAppDeclaredAnyPermission(
1079                 mContext, inputParams.getCallerPackageName(), apiName, PERMISSIONS_SET);
1080 
1081         final int callingUid = getCallingUid(apiName);
1082         final int adCounterHistogramAbsoluteMaxTotalEventCount =
1083                 BinderFlagReader.readFlag(
1084                         mFlags::getFledgeAdCounterHistogramAbsoluteMaxTotalEventCount);
1085         final int adCounterHistogramLowerMaxTotalEventCount =
1086                 BinderFlagReader.readFlag(
1087                         mFlags::getFledgeAdCounterHistogramLowerMaxTotalEventCount);
1088         final int adCounterHistogramAbsoluteMaxPerBuyerEventCount =
1089                 BinderFlagReader.readFlag(
1090                         mFlags::getFledgeAdCounterHistogramAbsoluteMaxPerBuyerEventCount);
1091         final int adCounterHistogramLowerMaxPerBuyerEventCount =
1092                 BinderFlagReader.readFlag(
1093                         mFlags::getFledgeAdCounterHistogramLowerMaxPerBuyerEventCount);
1094         final boolean auctionServerEnabledForUpdateHistogram =
1095                 BinderFlagReader.readFlag(mFlags::getFledgeAuctionServerEnabledForUpdateHistogram);
1096 
1097         final UpdateAdCounterHistogramWorker worker =
1098                 new UpdateAdCounterHistogramWorker(
1099                         new AdCounterHistogramUpdaterImpl(
1100                                 mAdSelectionEntryDao,
1101                                 mFrequencyCapDao,
1102                                 adCounterHistogramAbsoluteMaxTotalEventCount,
1103                                 adCounterHistogramLowerMaxTotalEventCount,
1104                                 adCounterHistogramAbsoluteMaxPerBuyerEventCount,
1105                                 adCounterHistogramLowerMaxPerBuyerEventCount,
1106                                 auctionServerEnabledForUpdateHistogram,
1107                                 mShouldUseUnifiedTables),
1108                         mBackgroundExecutor,
1109                         // TODO(b/235841960): Use the same injected clock as AdSelectionRunner
1110                         //  after aligning on Clock usage
1111                         java.time.Clock.systemUTC(),
1112                         mAdServicesLogger,
1113                         mFlags,
1114                         mAdSelectionServiceFilter,
1115                         mConsentManager,
1116                         callingUid,
1117                         mDevContextFilter.createDevContext());
1118 
1119         worker.updateAdCounterHistogram(inputParams, callback);
1120     }
1121 
1122     @Override
overrideAdSelectionConfigRemoteInfo( @onNull AdSelectionConfig adSelectionConfig, @NonNull String decisionLogicJS, @NonNull AdSelectionSignals trustedScoringSignals, @NonNull PerBuyerDecisionLogic perBuyerDecisionLogic, @NonNull AdSelectionOverrideCallback callback)1123     public void overrideAdSelectionConfigRemoteInfo(
1124             @NonNull AdSelectionConfig adSelectionConfig,
1125             @NonNull String decisionLogicJS,
1126             @NonNull AdSelectionSignals trustedScoringSignals,
1127             @NonNull PerBuyerDecisionLogic perBuyerDecisionLogic,
1128             @NonNull AdSelectionOverrideCallback callback) {
1129         int apiName = AD_SERVICES_API_CALLED__API_NAME__OVERRIDE_AD_SELECTION_CONFIG_REMOTE_INFO;
1130 
1131         try {
1132             Objects.requireNonNull(adSelectionConfig);
1133             Objects.requireNonNull(decisionLogicJS);
1134             Objects.requireNonNull(perBuyerDecisionLogic);
1135             Objects.requireNonNull(callback);
1136         } catch (NullPointerException exception) {
1137             mAdServicesLogger.logFledgeApiCallStats(
1138                     apiName, STATUS_INVALID_ARGUMENT, /*latencyMs=*/ 0);
1139             // Rethrow because we want to fail fast
1140             throw exception;
1141         }
1142 
1143         DevContext devContext = mDevContextFilter.createDevContext();
1144 
1145         if (!devContext.getDevOptionsEnabled()) {
1146             mAdServicesLogger.logFledgeApiCallStats(
1147                     apiName,
1148                     devContext.getCallingAppPackageName(),
1149                     STATUS_INTERNAL_ERROR,
1150                     /*latencyMs=*/ 0);
1151             throw new SecurityException(API_NOT_AUTHORIZED_MSG);
1152         }
1153 
1154         // Caller permissions must be checked with a non-null callingAppPackageName
1155         mFledgeAuthorizationFilter.assertAppDeclaredAnyPermission(
1156                 mContext, devContext.getCallingAppPackageName(), apiName, PERMISSIONS_SET);
1157 
1158         int callingUid = getCallingUid(apiName);
1159 
1160         AdSelectionOverrider overrider =
1161                 new AdSelectionOverrider(
1162                         devContext,
1163                         mAdSelectionEntryDao,
1164                         mLightweightExecutor,
1165                         mBackgroundExecutor,
1166                         mContext.getPackageManager(),
1167                         ConsentManager.getInstance(),
1168                         mAdServicesLogger,
1169                         AppImportanceFilter.create(
1170                                 mContext,
1171                                 AD_SERVICES_API_CALLED__API_CLASS__FLEDGE,
1172                                 () ->
1173                                         FlagsFactory.getFlags()
1174                                                 .getForegroundStatuslLevelForValidation()),
1175                         mFlags,
1176                         callingUid);
1177 
1178         overrider.addOverride(
1179                 adSelectionConfig,
1180                 decisionLogicJS,
1181                 trustedScoringSignals,
1182                 perBuyerDecisionLogic,
1183                 callback);
1184     }
1185 
getCallingUid(int apiNameLoggingId)1186     private int getCallingUid(int apiNameLoggingId) throws IllegalStateException {
1187         return getCallingUid(apiNameLoggingId, null);
1188     }
1189 
getCallingUid(int apiNameLoggingId, String callerAppPackageName)1190     private int getCallingUid(int apiNameLoggingId, String callerAppPackageName) {
1191         try {
1192             return mCallingAppUidSupplier.getCallingAppUid();
1193         } catch (IllegalStateException illegalStateException) {
1194             mAdServicesLogger.logFledgeApiCallStats(
1195                     apiNameLoggingId,
1196                     callerAppPackageName,
1197                     STATUS_INTERNAL_ERROR,
1198                     /*latencyMs=*/ 0);
1199             throw illegalStateException;
1200         }
1201     }
1202 
1203     @Override
removeAdSelectionConfigRemoteInfoOverride( @onNull AdSelectionConfig adSelectionConfig, @NonNull AdSelectionOverrideCallback callback)1204     public void removeAdSelectionConfigRemoteInfoOverride(
1205             @NonNull AdSelectionConfig adSelectionConfig,
1206             @NonNull AdSelectionOverrideCallback callback) {
1207         // Auto-generated variable name is too long for lint check
1208         int apiName =
1209                 AD_SERVICES_API_CALLED__API_NAME__REMOVE_AD_SELECTION_CONFIG_REMOTE_INFO_OVERRIDE;
1210 
1211         try {
1212             Objects.requireNonNull(adSelectionConfig);
1213             Objects.requireNonNull(callback);
1214         } catch (NullPointerException exception) {
1215             mAdServicesLogger.logFledgeApiCallStats(
1216                     apiName, STATUS_INVALID_ARGUMENT, /*latencyMs=*/ 0);
1217             // Rethrow because we want to fail fast
1218             throw exception;
1219         }
1220 
1221         DevContext devContext = mDevContextFilter.createDevContext();
1222 
1223         if (!devContext.getDevOptionsEnabled()) {
1224             mAdServicesLogger.logFledgeApiCallStats(
1225                     apiName,
1226                     devContext.getCallingAppPackageName(),
1227                     STATUS_INTERNAL_ERROR,
1228                     /*latencyMs=*/ 0);
1229             throw new SecurityException(API_NOT_AUTHORIZED_MSG);
1230         }
1231 
1232         // Caller permissions must be checked with a non-null callingAppPackageName
1233         mFledgeAuthorizationFilter.assertAppDeclaredAnyPermission(
1234                 mContext, devContext.getCallingAppPackageName(), apiName, PERMISSIONS_SET);
1235 
1236         int callingUid = getCallingUid(apiName);
1237 
1238         AdSelectionOverrider overrider =
1239                 new AdSelectionOverrider(
1240                         devContext,
1241                         mAdSelectionEntryDao,
1242                         mLightweightExecutor,
1243                         mBackgroundExecutor,
1244                         mContext.getPackageManager(),
1245                         ConsentManager.getInstance(),
1246                         mAdServicesLogger,
1247                         AppImportanceFilter.create(
1248                                 mContext,
1249                                 AD_SERVICES_API_CALLED__API_CLASS__FLEDGE,
1250                                 () ->
1251                                         FlagsFactory.getFlags()
1252                                                 .getForegroundStatuslLevelForValidation()),
1253                         mFlags,
1254                         callingUid);
1255 
1256         overrider.removeOverride(adSelectionConfig, callback);
1257     }
1258 
1259     @Override
resetAllAdSelectionConfigRemoteOverrides( @onNull AdSelectionOverrideCallback callback)1260     public void resetAllAdSelectionConfigRemoteOverrides(
1261             @NonNull AdSelectionOverrideCallback callback) {
1262         // Auto-generated variable name is too long for lint check
1263         int apiName =
1264                 AD_SERVICES_API_CALLED__API_NAME__RESET_ALL_AD_SELECTION_CONFIG_REMOTE_OVERRIDES;
1265 
1266         try {
1267             Objects.requireNonNull(callback);
1268         } catch (NullPointerException exception) {
1269             mAdServicesLogger.logFledgeApiCallStats(
1270                     apiName, STATUS_INVALID_ARGUMENT, /*latencyMs=*/ 0);
1271             // Rethrow because we want to fail fast
1272             throw exception;
1273         }
1274 
1275         DevContext devContext = mDevContextFilter.createDevContext();
1276 
1277         if (!devContext.getDevOptionsEnabled()) {
1278             mAdServicesLogger.logFledgeApiCallStats(
1279                     apiName,
1280                     devContext.getCallingAppPackageName(),
1281                     STATUS_INTERNAL_ERROR,
1282                     /*latencyMs=*/ 0);
1283             throw new SecurityException(API_NOT_AUTHORIZED_MSG);
1284         }
1285 
1286         // Caller permissions must be checked with a non-null callingAppPackageName
1287         mFledgeAuthorizationFilter.assertAppDeclaredAnyPermission(
1288                 mContext, devContext.getCallingAppPackageName(), apiName, PERMISSIONS_SET);
1289 
1290         int callingUid = getCallingUid(apiName);
1291 
1292         AdSelectionOverrider overrider =
1293                 new AdSelectionOverrider(
1294                         devContext,
1295                         mAdSelectionEntryDao,
1296                         mLightweightExecutor,
1297                         mBackgroundExecutor,
1298                         mContext.getPackageManager(),
1299                         ConsentManager.getInstance(),
1300                         mAdServicesLogger,
1301                         AppImportanceFilter.create(
1302                                 mContext,
1303                                 AD_SERVICES_API_CALLED__API_CLASS__FLEDGE,
1304                                 () ->
1305                                         FlagsFactory.getFlags()
1306                                                 .getForegroundStatuslLevelForValidation()),
1307                         mFlags,
1308                         callingUid);
1309 
1310         overrider.removeAllOverridesForAdSelectionConfig(callback);
1311     }
1312 
1313     @Override
overrideAdSelectionFromOutcomesConfigRemoteInfo( @onNull AdSelectionFromOutcomesConfig config, @NonNull String selectionLogicJs, @NonNull AdSelectionSignals selectionSignals, @NonNull AdSelectionOverrideCallback callback)1314     public void overrideAdSelectionFromOutcomesConfigRemoteInfo(
1315             @NonNull AdSelectionFromOutcomesConfig config,
1316             @NonNull String selectionLogicJs,
1317             @NonNull AdSelectionSignals selectionSignals,
1318             @NonNull AdSelectionOverrideCallback callback) {
1319         int apiName = AD_SERVICES_API_CALLED__API_NAME__API_NAME_UNKNOWN;
1320 
1321         try {
1322             Objects.requireNonNull(config);
1323             Objects.requireNonNull(selectionLogicJs);
1324             Objects.requireNonNull(selectionSignals);
1325             Objects.requireNonNull(callback);
1326         } catch (NullPointerException exception) {
1327             mAdServicesLogger.logFledgeApiCallStats(
1328                     apiName, STATUS_INVALID_ARGUMENT, /*latencyMs=*/ 0);
1329             // Rethrow because we want to fail fast
1330             throw exception;
1331         }
1332 
1333         DevContext devContext = mDevContextFilter.createDevContext();
1334 
1335         if (!devContext.getDevOptionsEnabled()) {
1336             mAdServicesLogger.logFledgeApiCallStats(
1337                     apiName,
1338                     devContext.getCallingAppPackageName(),
1339                     STATUS_INTERNAL_ERROR,
1340                     /*latencyMs=*/ 0);
1341             throw new SecurityException(API_NOT_AUTHORIZED_MSG);
1342         }
1343 
1344         // Caller permissions must be checked with a non-null callingAppPackageName
1345         mFledgeAuthorizationFilter.assertAppDeclaredAnyPermission(
1346                 mContext, devContext.getCallingAppPackageName(), apiName, PERMISSIONS_SET);
1347 
1348         int callingUid = getCallingUid(apiName);
1349 
1350         AdSelectionOverrider overrider =
1351                 new AdSelectionOverrider(
1352                         devContext,
1353                         mAdSelectionEntryDao,
1354                         mLightweightExecutor,
1355                         mBackgroundExecutor,
1356                         mContext.getPackageManager(),
1357                         ConsentManager.getInstance(),
1358                         mAdServicesLogger,
1359                         AppImportanceFilter.create(
1360                                 mContext,
1361                                 AD_SERVICES_API_CALLED__API_CLASS__FLEDGE,
1362                                 () ->
1363                                         FlagsFactory.getFlags()
1364                                                 .getForegroundStatuslLevelForValidation()),
1365                         mFlags,
1366                         callingUid);
1367 
1368         overrider.addOverride(config, selectionLogicJs, selectionSignals, callback);
1369     }
1370 
1371     @Override
removeAdSelectionFromOutcomesConfigRemoteInfoOverride( @onNull AdSelectionFromOutcomesConfig config, @NonNull AdSelectionOverrideCallback callback)1372     public void removeAdSelectionFromOutcomesConfigRemoteInfoOverride(
1373             @NonNull AdSelectionFromOutcomesConfig config,
1374             @NonNull AdSelectionOverrideCallback callback) {
1375         // Auto-generated variable name is too long for lint check
1376         int apiName = AD_SERVICES_API_CALLED__API_NAME__API_NAME_UNKNOWN;
1377 
1378         try {
1379             Objects.requireNonNull(config);
1380             Objects.requireNonNull(callback);
1381         } catch (NullPointerException exception) {
1382             mAdServicesLogger.logFledgeApiCallStats(
1383                     apiName, STATUS_INVALID_ARGUMENT, /*latencyMs=*/ 0);
1384             // Rethrow because we want to fail fast
1385             throw exception;
1386         }
1387 
1388         DevContext devContext = mDevContextFilter.createDevContext();
1389 
1390         if (!devContext.getDevOptionsEnabled()) {
1391             mAdServicesLogger.logFledgeApiCallStats(
1392                     apiName,
1393                     devContext.getCallingAppPackageName(),
1394                     STATUS_INTERNAL_ERROR,
1395                     /*latencyMs=*/ 0);
1396             throw new SecurityException(API_NOT_AUTHORIZED_MSG);
1397         }
1398 
1399         // Caller permissions must be checked with a non-null callingAppPackageName
1400         mFledgeAuthorizationFilter.assertAppDeclaredAnyPermission(
1401                 mContext, devContext.getCallingAppPackageName(), apiName, PERMISSIONS_SET);
1402 
1403         int callingUid = getCallingUid(apiName);
1404 
1405         AdSelectionOverrider overrider =
1406                 new AdSelectionOverrider(
1407                         devContext,
1408                         mAdSelectionEntryDao,
1409                         mLightweightExecutor,
1410                         mBackgroundExecutor,
1411                         mContext.getPackageManager(),
1412                         ConsentManager.getInstance(),
1413                         mAdServicesLogger,
1414                         AppImportanceFilter.create(
1415                                 mContext,
1416                                 AD_SERVICES_API_CALLED__API_CLASS__FLEDGE,
1417                                 () ->
1418                                         FlagsFactory.getFlags()
1419                                                 .getForegroundStatuslLevelForValidation()),
1420                         mFlags,
1421                         callingUid);
1422 
1423         overrider.removeOverride(config, callback);
1424     }
1425 
1426     @Override
resetAllAdSelectionFromOutcomesConfigRemoteOverrides( @onNull AdSelectionOverrideCallback callback)1427     public void resetAllAdSelectionFromOutcomesConfigRemoteOverrides(
1428             @NonNull AdSelectionOverrideCallback callback) {
1429         // Auto-generated variable name is too long for lint check
1430         int apiName = AD_SERVICES_API_CALLED__API_NAME__API_NAME_UNKNOWN;
1431 
1432         try {
1433             Objects.requireNonNull(callback);
1434         } catch (NullPointerException exception) {
1435             mAdServicesLogger.logFledgeApiCallStats(
1436                     apiName, STATUS_INVALID_ARGUMENT, /*latencyMs=*/ 0);
1437             // Rethrow because we want to fail fast
1438             throw exception;
1439         }
1440 
1441         DevContext devContext = mDevContextFilter.createDevContext();
1442 
1443         if (!devContext.getDevOptionsEnabled()) {
1444             mAdServicesLogger.logFledgeApiCallStats(
1445                     apiName,
1446                     devContext.getCallingAppPackageName(),
1447                     STATUS_INTERNAL_ERROR,
1448                     /*latencyMs=*/ 0);
1449             throw new SecurityException(API_NOT_AUTHORIZED_MSG);
1450         }
1451 
1452         // Caller permissions must be checked with a non-null callingAppPackageName
1453         mFledgeAuthorizationFilter.assertAppDeclaredAnyPermission(
1454                 mContext, devContext.getCallingAppPackageName(), apiName, PERMISSIONS_SET);
1455 
1456         int callingUid = getCallingUid(apiName);
1457 
1458         AdSelectionOverrider overrider =
1459                 new AdSelectionOverrider(
1460                         devContext,
1461                         mAdSelectionEntryDao,
1462                         mLightweightExecutor,
1463                         mBackgroundExecutor,
1464                         mContext.getPackageManager(),
1465                         ConsentManager.getInstance(),
1466                         mAdServicesLogger,
1467                         AppImportanceFilter.create(
1468                                 mContext,
1469                                 AD_SERVICES_API_CALLED__API_CLASS__FLEDGE,
1470                                 () ->
1471                                         FlagsFactory.getFlags()
1472                                                 .getForegroundStatuslLevelForValidation()),
1473                         mFlags,
1474                         callingUid);
1475 
1476         overrider.removeAllOverridesForAdSelectionFromOutcomes(callback);
1477     }
1478 
1479     @Override
setAdCounterHistogramOverride( @onNull SetAdCounterHistogramOverrideInput inputParams, @NonNull AdSelectionOverrideCallback callback)1480     public void setAdCounterHistogramOverride(
1481             @NonNull SetAdCounterHistogramOverrideInput inputParams,
1482             @NonNull AdSelectionOverrideCallback callback) {
1483         int apiName = AD_SERVICES_API_CALLED__API_NAME__API_NAME_UNKNOWN;
1484 
1485         try {
1486             Objects.requireNonNull(inputParams);
1487             Objects.requireNonNull(callback);
1488         } catch (NullPointerException exception) {
1489             mAdServicesLogger.logFledgeApiCallStats(
1490                     apiName, STATUS_INVALID_ARGUMENT, /*latencyMs=*/ 0);
1491             // Rethrow because we want to fail fast
1492             throw exception;
1493         }
1494 
1495         DevContext devContext = mDevContextFilter.createDevContext();
1496 
1497         if (!devContext.getDevOptionsEnabled()) {
1498             mAdServicesLogger.logFledgeApiCallStats(
1499                     apiName,
1500                     devContext.getCallingAppPackageName(),
1501                     STATUS_INTERNAL_ERROR,
1502                     /*latencyMs=*/ 0);
1503             throw new SecurityException(API_NOT_AUTHORIZED_MSG);
1504         }
1505 
1506         // Caller permissions must be checked with a non-null callingAppPackageName
1507         mFledgeAuthorizationFilter.assertAppDeclaredAnyPermission(
1508                 mContext, devContext.getCallingAppPackageName(), apiName, PERMISSIONS_SET);
1509 
1510         // TODO(b/265204820): Implement service
1511         int status = STATUS_SUCCESS;
1512         try {
1513             callback.onSuccess();
1514         } catch (RemoteException exception) {
1515             status = STATUS_INTERNAL_ERROR;
1516         } finally {
1517             mAdServicesLogger.logFledgeApiCallStats(
1518                     apiName, devContext.getCallingAppPackageName(), status, /*latencyMs=*/ 0);
1519         }
1520     }
1521 
1522     @Override
removeAdCounterHistogramOverride( @onNull RemoveAdCounterHistogramOverrideInput inputParams, @NonNull AdSelectionOverrideCallback callback)1523     public void removeAdCounterHistogramOverride(
1524             @NonNull RemoveAdCounterHistogramOverrideInput inputParams,
1525             @NonNull AdSelectionOverrideCallback callback) {
1526         int apiName = AD_SERVICES_API_CALLED__API_NAME__API_NAME_UNKNOWN;
1527 
1528         try {
1529             Objects.requireNonNull(inputParams);
1530             Objects.requireNonNull(callback);
1531         } catch (NullPointerException exception) {
1532             mAdServicesLogger.logFledgeApiCallStats(
1533                     apiName, STATUS_INVALID_ARGUMENT, /*latencyMs=*/ 0);
1534             // Rethrow because we want to fail fast
1535             throw exception;
1536         }
1537 
1538         DevContext devContext = mDevContextFilter.createDevContext();
1539 
1540         if (!devContext.getDevOptionsEnabled()) {
1541             mAdServicesLogger.logFledgeApiCallStats(
1542                     apiName,
1543                     devContext.getCallingAppPackageName(),
1544                     STATUS_INTERNAL_ERROR,
1545                     /*latencyMs=*/ 0);
1546             throw new SecurityException(API_NOT_AUTHORIZED_MSG);
1547         }
1548 
1549         // Caller permissions must be checked with a non-null callingAppPackageName
1550         mFledgeAuthorizationFilter.assertAppDeclaredAnyPermission(
1551                 mContext, devContext.getCallingAppPackageName(), apiName, PERMISSIONS_SET);
1552 
1553         // TODO(b/265204820): Implement service
1554         int status = STATUS_SUCCESS;
1555         try {
1556             callback.onSuccess();
1557         } catch (RemoteException exception) {
1558             status = STATUS_INTERNAL_ERROR;
1559         } finally {
1560             mAdServicesLogger.logFledgeApiCallStats(
1561                     apiName, devContext.getCallingAppPackageName(), status, /*latencyMs=*/ 0);
1562         }
1563     }
1564 
1565     @Override
resetAllAdCounterHistogramOverrides(@onNull AdSelectionOverrideCallback callback)1566     public void resetAllAdCounterHistogramOverrides(@NonNull AdSelectionOverrideCallback callback) {
1567         int apiName = AD_SERVICES_API_CALLED__API_NAME__API_NAME_UNKNOWN;
1568 
1569         try {
1570             Objects.requireNonNull(callback);
1571         } catch (NullPointerException exception) {
1572             mAdServicesLogger.logFledgeApiCallStats(
1573                     apiName, STATUS_INVALID_ARGUMENT, /*latencyMs=*/ 0);
1574             // Rethrow because we want to fail fast
1575             throw exception;
1576         }
1577 
1578         DevContext devContext = mDevContextFilter.createDevContext();
1579 
1580         if (!devContext.getDevOptionsEnabled()) {
1581             mAdServicesLogger.logFledgeApiCallStats(
1582                     apiName,
1583                     devContext.getCallingAppPackageName(),
1584                     STATUS_INTERNAL_ERROR,
1585                     /*latencyMs=*/ 0);
1586             throw new SecurityException(API_NOT_AUTHORIZED_MSG);
1587         }
1588 
1589         // Caller permissions must be checked with a non-null callingAppPackageName
1590         mFledgeAuthorizationFilter.assertAppDeclaredAnyPermission(
1591                 mContext, devContext.getCallingAppPackageName(), apiName, PERMISSIONS_SET);
1592 
1593         // TODO(b/265204820): Implement service
1594         int status = STATUS_SUCCESS;
1595         try {
1596             callback.onSuccess();
1597         } catch (RemoteException exception) {
1598             status = STATUS_INTERNAL_ERROR;
1599         } finally {
1600             mAdServicesLogger.logFledgeApiCallStats(
1601                     apiName, devContext.getCallingAppPackageName(), status, /*latencyMs=*/ 0);
1602         }
1603     }
1604 
1605     /** Close down method to be invoked when the PPAPI process is shut down. */
1606     @SuppressWarnings("FutureReturnValueIgnored")
destroy()1607     public void destroy() {
1608         sLogger.i("Shutting down AdSelectionService");
1609         try {
1610             JSScriptEngine jsScriptEngine = JSScriptEngine.getInstance(sLogger);
1611             jsScriptEngine.shutdown();
1612         } catch (JSSandboxIsNotAvailableException exception) {
1613             sLogger.i("Java script sandbox is not available, not shutting down JSScriptEngine.");
1614         }
1615     }
1616 }
1617