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