1 /*
2  * Copyright (C) 2023 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.encryptionkey;
18 
19 import static com.android.adservices.spe.AdServicesJobInfo.ENCRYPTION_KEY_PERIODIC_JOB;
20 
21 import android.app.job.JobInfo;
22 import android.app.job.JobParameters;
23 import android.app.job.JobScheduler;
24 import android.app.job.JobService;
25 import android.content.ComponentName;
26 import android.content.Context;
27 
28 import com.android.adservices.LogUtil;
29 import com.android.adservices.concurrency.AdServicesExecutors;
30 import com.android.adservices.data.encryptionkey.EncryptionKeyDao;
31 import com.android.adservices.data.enrollment.EnrollmentDao;
32 import com.android.adservices.service.Flags;
33 import com.android.adservices.service.FlagsFactory;
34 import com.android.adservices.service.common.compat.ServiceCompatUtils;
35 import com.android.adservices.service.stats.AdServicesEncryptionKeyFetchedStats.FetchJobType;
36 import com.android.adservices.spe.AdServicesJobServiceLogger;
37 import com.android.internal.annotations.VisibleForTesting;
38 
39 import com.google.common.util.concurrent.ListeningExecutorService;
40 
41 import java.util.concurrent.Future;
42 
43 /** Class schedules a periodic job to check all encryption keys in table and fetch updated keys. */
44 public class EncryptionKeyJobService extends JobService {
45 
46     private static final ListeningExecutorService sBlockingExecutor =
47             AdServicesExecutors.getBlockingExecutor();
48     private static final int ENCRYPTION_KEY_JOB_ID = ENCRYPTION_KEY_PERIODIC_JOB.getJobId();
49 
50     // This Future should only be accessed on the main thread.
51     private Future mExecutorFuture;
52 
53     @Override
onStartJob(JobParameters params)54     public boolean onStartJob(JobParameters params) {
55         // Always ensure that the first thing this job does is check if it should be running, and
56         // cancel itself if it's not supposed to be.
57         if (ServiceCompatUtils.shouldDisableExtServicesJobOnTPlus(this)) {
58             LogUtil.d(
59                     "Disabling EncryptionKeyJobService job because it's running in "
60                             + "ExtServices on T+");
61             return skipAndCancelBackgroundJob(params);
62         }
63 
64         AdServicesJobServiceLogger.getInstance().recordOnStartJob(ENCRYPTION_KEY_JOB_ID);
65 
66         if (FlagsFactory.getFlags().getEncryptionKeyPeriodicFetchKillSwitch()) {
67             LogUtil.e(
68                     "Encryption key fetch job service is disabled, skipping and cancelling"
69                             + " EncryptionKeyJobService");
70             return skipAndCancelBackgroundJob(params);
71         }
72 
73         LogUtil.d("EncryptionKeyJobService.onStartJob");
74         mExecutorFuture =
75                 sBlockingExecutor.submit(
76                         () -> {
77                             fetchAndUpdateEncryptionKeys();
78                             AdServicesJobServiceLogger.getInstance()
79                                     .recordJobFinished(
80                                             ENCRYPTION_KEY_JOB_ID,
81                                             /* isSuccessful */ true,
82                                             /* shouldRetry*/ false);
83                             jobFinished(params, /* wantsReschedule= */ false);
84                         });
85         return true;
86     }
87 
88     @Override
onStopJob(JobParameters params)89     public boolean onStopJob(JobParameters params) {
90         LogUtil.d("EncryptionKeyJobService.onStopJob");
91 
92         boolean shouldRetry = true;
93         if (mExecutorFuture != null) {
94             shouldRetry = mExecutorFuture.cancel(/* mayInterruptIfRunning */ true);
95         }
96         AdServicesJobServiceLogger.getInstance()
97                 .recordOnStopJob(params, ENCRYPTION_KEY_JOB_ID, shouldRetry);
98         return shouldRetry;
99     }
100 
101     /**
102      * Schedule Encryption key fetch job if it is not already scheduled.
103      *
104      * @param context the context
105      * @param forceSchedule flag to indicate whether to force rescheduling the job.
106      */
scheduleIfNeeded(Context context, boolean forceSchedule)107     public static boolean scheduleIfNeeded(Context context, boolean forceSchedule) {
108         Flags flags = FlagsFactory.getFlags();
109         if (FlagsFactory.getFlags().getEncryptionKeyPeriodicFetchKillSwitch()) {
110             LogUtil.e("Encryption key fetch job is disabled, skip scheduling.");
111             return false;
112         }
113 
114         final JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
115         if (jobScheduler == null) {
116             LogUtil.e("Cannot fetch Job Scheduler.");
117             return false;
118         }
119 
120         final JobInfo scheduledJob = jobScheduler.getPendingJob(ENCRYPTION_KEY_JOB_ID);
121         // Schedule if it hasn't been scheduled already or force rescheduling.
122         JobInfo jobInfo = buildJobInfo(context, flags);
123         if (forceSchedule || !jobInfo.equals(scheduledJob)) {
124             schedule(jobScheduler, jobInfo);
125             LogUtil.d("Scheduled EncryptionKeyJobService.");
126             return true;
127         } else {
128             LogUtil.d("EncryptionKeyJobService already scheduled, skipping reschedule.");
129             return false;
130         }
131     }
132 
133     /** Fetch encryption keys or update expired encryption keys. */
134     @VisibleForTesting
fetchAndUpdateEncryptionKeys()135     public void fetchAndUpdateEncryptionKeys() {
136         EncryptionKeyDao encryptionKeyDao = EncryptionKeyDao.getInstance();
137         EnrollmentDao enrollmentDao = EnrollmentDao.getInstance();
138         EncryptionKeyJobHandler encryptionKeyJobHandler =
139                 new EncryptionKeyJobHandler(
140                         encryptionKeyDao,
141                         enrollmentDao,
142                         new EncryptionKeyFetcher(FetchJobType.ENCRYPTION_KEY_DAILY_FETCH_JOB));
143         encryptionKeyJobHandler.fetchAndUpdateEncryptionKeys();
144     }
145 
146     /**
147      * Schedule Encryption key fetch job.
148      *
149      * @param jobScheduler the jobScheduler
150      * @param jobInfo the jobInfo for this job
151      */
152     @VisibleForTesting
schedule(JobScheduler jobScheduler, JobInfo jobInfo)153     public static void schedule(JobScheduler jobScheduler, JobInfo jobInfo) {
154         jobScheduler.schedule(jobInfo);
155     }
156 
buildJobInfo(Context context, Flags flags)157     private static JobInfo buildJobInfo(Context context, Flags flags) {
158         return new JobInfo.Builder(
159                         ENCRYPTION_KEY_JOB_ID,
160                         new ComponentName(context, EncryptionKeyJobService.class))
161                 .setRequiredNetworkType(flags.getEncryptionKeyJobRequiredNetworkType())
162                 .setPeriodic(flags.getEncryptionKeyJobPeriodMs())
163                 .build();
164     }
165 
skipAndCancelBackgroundJob(final JobParameters params)166     private boolean skipAndCancelBackgroundJob(final JobParameters params) {
167         final JobScheduler jobScheduler = this.getSystemService(JobScheduler.class);
168         if (jobScheduler != null) {
169             jobScheduler.cancel(ENCRYPTION_KEY_JOB_ID);
170         }
171 
172         // Tell the JobScheduler that the job has completed and does not need to be
173         // rescheduled.
174         jobFinished(params, /* wantsReschedule= */ false);
175 
176         // Returning false means that this job has completed its work.
177         return false;
178     }
179 
180     @VisibleForTesting
getFutureForTesting()181     public Future getFutureForTesting() {
182         return mExecutorFuture;
183     }
184 }
185