xref: /aosp_15_r20/system/apex/apexd/apexd_test_utils.h (revision 33f3758387333dbd2962d7edbd98681940d895da)
1 /*
2  * Copyright (C) 2019 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 #include <filesystem>
18 #include <fstream>
19 
20 #include <gmock/gmock.h>
21 #include <gtest/gtest.h>
22 #include <linux/loop.h>
23 #include <sched.h>
24 #include <sys/mount.h>
25 
26 #include <android-base/errors.h>
27 #include <android-base/logging.h>
28 #include <android-base/macros.h>
29 #include <android-base/result.h>
30 #include <android-base/stringprintf.h>
31 #include <android-base/strings.h>
32 #include <android-base/unique_fd.h>
33 #include <android/apex/ApexInfo.h>
34 #include <android/apex/ApexSessionInfo.h>
35 #include <binder/IServiceManager.h>
36 #include <fstab/fstab.h>
37 #include <libdm/dm.h>
38 #include <selinux/android.h>
39 
40 #include "apex_file.h"
41 #include "apexd_loop.h"
42 #include "apexd_utils.h"
43 #include "session_state.pb.h"
44 
45 #include "com_android_apex.h"
46 
47 namespace android {
48 namespace apex {
49 namespace testing {
50 
IsOk(const android::binder::Status & status)51 inline ::testing::AssertionResult IsOk(const android::binder::Status& status) {
52   if (status.isOk()) {
53     return ::testing::AssertionSuccess() << " is Ok";
54   } else {
55     return ::testing::AssertionFailure()
56            << " failed with " << status.exceptionMessage().c_str();
57   }
58 }
59 
60 MATCHER_P(SessionInfoEq, other, "") {
61   using ::testing::AllOf;
62   using ::testing::Eq;
63   using ::testing::Field;
64 
65   return ExplainMatchResult(
66       AllOf(
67           Field("sessionId", &ApexSessionInfo::sessionId, Eq(other.sessionId)),
68           Field("isUnknown", &ApexSessionInfo::isUnknown, Eq(other.isUnknown)),
69           Field("isVerified", &ApexSessionInfo::isVerified,
70                 Eq(other.isVerified)),
71           Field("isStaged", &ApexSessionInfo::isStaged, Eq(other.isStaged)),
72           Field("isActivated", &ApexSessionInfo::isActivated,
73                 Eq(other.isActivated)),
74           Field("isRevertInProgress", &ApexSessionInfo::isRevertInProgress,
75                 Eq(other.isRevertInProgress)),
76           Field("isActivationFailed", &ApexSessionInfo::isActivationFailed,
77                 Eq(other.isActivationFailed)),
78           Field("isSuccess", &ApexSessionInfo::isSuccess, Eq(other.isSuccess)),
79           Field("isReverted", &ApexSessionInfo::isReverted,
80                 Eq(other.isReverted)),
81           Field("isRevertFailed", &ApexSessionInfo::isRevertFailed,
82                 Eq(other.isRevertFailed))),
83       arg, result_listener);
84 }
85 
86 MATCHER_P(ApexInfoEq, other, "") {
87   using ::testing::AllOf;
88   using ::testing::Eq;
89   using ::testing::Field;
90 
91   return ExplainMatchResult(
92       AllOf(Field("moduleName", &ApexInfo::moduleName, Eq(other.moduleName)),
93             Field("modulePath", &ApexInfo::modulePath, Eq(other.modulePath)),
94             Field("preinstalledModulePath", &ApexInfo::preinstalledModulePath,
95                   Eq(other.preinstalledModulePath)),
96             Field("versionCode", &ApexInfo::versionCode, Eq(other.versionCode)),
97             Field("isFactory", &ApexInfo::isFactory, Eq(other.isFactory)),
98             Field("isActive", &ApexInfo::isActive, Eq(other.isActive)),
99             Field("partition", &ApexInfo::partition, Eq(other.partition))),
100       arg, result_listener);
101 }
102 
103 MATCHER_P(ApexFileEq, other, "") {
104   using ::testing::AllOf;
105   using ::testing::Eq;
106   using ::testing::Property;
107 
108   return ExplainMatchResult(
109       AllOf(Property("path", &ApexFile::GetPath, Eq(other.get().GetPath())),
110             Property("image_offset", &ApexFile::GetImageOffset,
111                      Eq(other.get().GetImageOffset())),
112             Property("image_size", &ApexFile::GetImageSize,
113                      Eq(other.get().GetImageSize())),
114             Property("fs_type", &ApexFile::GetFsType,
115                      Eq(other.get().GetFsType())),
116             Property("public_key", &ApexFile::GetBundledPublicKey,
117                      Eq(other.get().GetBundledPublicKey())),
118             Property("is_compressed", &ApexFile::IsCompressed,
119                      Eq(other.get().IsCompressed()))),
120       arg, result_listener);
121 }
122 
CreateSessionInfo(int session_id)123 inline ApexSessionInfo CreateSessionInfo(int session_id) {
124   ApexSessionInfo info;
125   info.sessionId = session_id;
126   info.isUnknown = false;
127   info.isVerified = false;
128   info.isStaged = false;
129   info.isActivated = false;
130   info.isRevertInProgress = false;
131   info.isActivationFailed = false;
132   info.isSuccess = false;
133   info.isReverted = false;
134   info.isRevertFailed = false;
135   return info;
136 }
137 
138 }  // namespace testing
139 
140 // Must be in apex::android namespace, otherwise gtest won't be able to find it.
PrintTo(const ApexSessionInfo & session,std::ostream * os)141 inline void PrintTo(const ApexSessionInfo& session, std::ostream* os) {
142   *os << "apex_session: {\n";
143   *os << "  sessionId : " << session.sessionId << "\n";
144   *os << "  isUnknown : " << session.isUnknown << "\n";
145   *os << "  isVerified : " << session.isVerified << "\n";
146   *os << "  isStaged : " << session.isStaged << "\n";
147   *os << "  isActivated : " << session.isActivated << "\n";
148   *os << "  isActivationFailed : " << session.isActivationFailed << "\n";
149   *os << "  isSuccess : " << session.isSuccess << "\n";
150   *os << "  isReverted : " << session.isReverted << "\n";
151   *os << "  isRevertFailed : " << session.isRevertFailed << "\n";
152   *os << "}";
153 }
154 
PrintTo(const ApexInfo & apex,std::ostream * os)155 inline void PrintTo(const ApexInfo& apex, std::ostream* os) {
156   *os << "apex_info: {\n";
157   *os << "  moduleName : " << apex.moduleName << "\n";
158   *os << "  modulePath : " << apex.modulePath << "\n";
159   *os << "  preinstalledModulePath : " << apex.preinstalledModulePath << "\n";
160   *os << "  versionCode : " << apex.versionCode << "\n";
161   *os << "  isFactory : " << apex.isFactory << "\n";
162   *os << "  isActive : " << apex.isActive << "\n";
163   *os << "  partition : " << toString(apex.partition) << "\n";
164   *os << "}";
165 }
166 
CompareFiles(const std::string & filename1,const std::string & filename2)167 inline android::base::Result<bool> CompareFiles(const std::string& filename1,
168                                                 const std::string& filename2) {
169   std::ifstream file1(filename1, std::ios::binary);
170   std::ifstream file2(filename2, std::ios::binary);
171 
172   if (file1.bad() || file2.bad()) {
173     return android::base::Error() << "Could not open one of the file";
174   }
175 
176   std::istreambuf_iterator<char> begin1(file1);
177   std::istreambuf_iterator<char> begin2(file2);
178 
179   return std::equal(begin1, std::istreambuf_iterator<char>(), begin2);
180 }
181 
GetCurrentMountNamespace()182 inline android::base::Result<std::string> GetCurrentMountNamespace() {
183   std::string result;
184   if (!android::base::Readlink("/proc/self/ns/mnt", &result)) {
185     return android::base::ErrnoError() << "Failed to read /proc/self/ns/mnt";
186   }
187   return result;
188 }
189 
190 // A helper class to switch back to the original mount namespace of a process
191 // upon exiting current scope.
192 class MountNamespaceRestorer final {
193  public:
MountNamespaceRestorer()194   explicit MountNamespaceRestorer() {
195     original_namespace_.reset(open("/proc/self/ns/mnt", O_RDONLY | O_CLOEXEC));
196     if (original_namespace_.get() < 0) {
197       PLOG(ERROR) << "Failed to open /proc/self/ns/mnt";
198     }
199   }
200 
~MountNamespaceRestorer()201   ~MountNamespaceRestorer() {
202     if (original_namespace_.get() != -1) {
203       // Since apexd is a multithread process. setns(fd, CLONE_NEWNS) may not
204       // work (fail with EINVAL). Retrying until success fixes it. This is
205       // acceptable since this class is for only tests. In the worst case tests
206       // will hang with bunch of logs.
207       while (setns(original_namespace_.get(), CLONE_NEWNS) == -1) {
208         PLOG(ERROR) << "Failed to switch back to " << original_namespace_.get();
209       }
210     }
211   }
212 
213  private:
214   android::base::unique_fd original_namespace_;
215   DISALLOW_COPY_AND_ASSIGN(MountNamespaceRestorer);
216 };
217 
GetApexMounts()218 inline std::vector<std::string> GetApexMounts() {
219   std::vector<std::string> apex_mounts;
220   std::string mount_info;
221   if (!android::base::ReadFileToString("/proc/self/mountinfo", &mount_info)) {
222     return apex_mounts;
223   }
224   for (const auto& line : android::base::Split(mount_info, "\n")) {
225     std::vector<std::string> tokens = android::base::Split(line, " ");
226     // line format:
227     // mnt_id parent_mnt_id major:minor source target option propagation_type
228     // ex) 33 260:19 / /apex rw,nosuid,nodev -
229     if (tokens.size() >= 7 && android::base::StartsWith(tokens[4], "/apex/")) {
230       apex_mounts.push_back(tokens[4]);
231     }
232   }
233   return apex_mounts;
234 }
235 
236 // Sets up a test environment for unit testing logic around mounting/unmounting
237 // apexes. For examples of usage see apexd_test.cpp
SetUpApexTestEnvironment()238 inline android::base::Result<void> SetUpApexTestEnvironment() {
239   using android::base::ErrnoError;
240 
241   // 1. Switch to new mount namespace.
242   if (unshare(CLONE_NEWNS) != 0) {
243     return ErrnoError() << "Failed to unshare";
244   }
245 
246   // 2. Make everything private, so that changes don't propagate.
247   if (mount(nullptr, "/", nullptr, MS_PRIVATE | MS_REC, nullptr) == -1) {
248     return ErrnoError() << "Failed to mount / as private";
249   }
250 
251   // 3. Unmount all apexes. This needs to happen in two phases:
252   // Note: unlike regular unmount flow in apexd, we don't destroy dm and loop
253   // devices, since that would've propagated outside of the test environment.
254   std::vector<std::string> apex_mounts = GetApexMounts();
255 
256   // 3a. First unmount all bind mounds (without @version_code).
257   for (const auto& mount : apex_mounts) {
258     if (mount.find('@') == std::string::npos) {
259       if (umount2(mount.c_str(), 0) != 0) {
260         return ErrnoError() << "Failed to unmount " << mount;
261       }
262     }
263   }
264 
265   // 3.b Now unmount versioned mounts.
266   for (const auto& mount : apex_mounts) {
267     if (mount.find('@') != std::string::npos) {
268       if (umount2(mount.c_str(), 0) != 0) {
269         return ErrnoError() << "Failed to unmount " << mount;
270       }
271     }
272   }
273 
274   static constexpr const char* kApexMountForTest = "/mnt/scratch-apex";
275 
276   // Clean up in case previous test left directory behind.
277   if (access(kApexMountForTest, F_OK) == 0) {
278     if (umount2(kApexMountForTest, MNT_FORCE | UMOUNT_NOFOLLOW) != 0) {
279       PLOG(WARNING) << "Failed to unmount " << kApexMountForTest;
280     }
281     if (rmdir(kApexMountForTest) != 0) {
282       return ErrnoError() << "Failed to rmdir " << kApexMountForTest;
283     }
284   }
285 
286   // 4. Create an empty tmpfs that will substitute /apex in tests.
287   if (mkdir(kApexMountForTest, 0755) != 0) {
288     return ErrnoError() << "Failed to mkdir " << kApexMountForTest;
289   }
290 
291   if (mount("tmpfs", kApexMountForTest, "tmpfs", 0, nullptr) == -1) {
292     return ErrnoError() << "Failed to mount " << kApexMountForTest;
293   }
294 
295   // 5. Overlay it  over /apex via bind mount.
296   if (mount(kApexMountForTest, "/apex", nullptr, MS_BIND, nullptr) == -1) {
297     return ErrnoError() << "Failed to bind mount " << kApexMountForTest
298                         << " over /apex";
299   }
300 
301   // Just in case, run restorecon -R on /apex.
302   if (selinux_android_restorecon("/apex", SELINUX_ANDROID_RESTORECON_RECURSE) <
303       0) {
304     return ErrnoError() << "Failed to restorecon /apex";
305   }
306 
307   return {};
308 }
309 
MountViaLoopDevice(const std::string & filepath,const std::string & mount_point)310 inline base::Result<loop::LoopbackDeviceUniqueFd> MountViaLoopDevice(
311     const std::string& filepath, const std::string& mount_point) {
312   auto loop_device = loop::CreateAndConfigureLoopDevice(filepath, 0, 0);
313   if (loop_device.ok()) {
314     close(open(mount_point.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC,
315                0644));
316     if (0 != mount(loop_device->name.c_str(), mount_point.c_str(), nullptr,
317                    MS_BIND, nullptr)) {
318       return base::ErrnoError() << "can't mount.";
319     }
320   }
321   return loop_device;
322 }
323 
324 // Represents a Block APEX in tests, which is represented as a loop-mounted
325 // file. Created with WriteBlockApex() below. On exit, it umounts the mountpoint
326 // first, and then frees the loop-device.
327 struct BlockApex {
328   loop::LoopbackDeviceUniqueFd loop_device;
329   std::string mount_point;
BlockApexBlockApex330   BlockApex(loop::LoopbackDeviceUniqueFd&& loop_device,
331             const std::string& mount_point)
332       : loop_device(std::move(loop_device)), mount_point(mount_point) {}
BlockApexBlockApex333   BlockApex(BlockApex&& other) noexcept {
334     loop_device = std::move(other.loop_device);
335     mount_point = std::move(other.mount_point);
336   }
337   BlockApex& operator=(BlockApex&& other) noexcept {
338     loop_device = std::move(other.loop_device);
339     mount_point = std::move(other.mount_point);
340     return *this;
341   }
~BlockApexBlockApex342   ~BlockApex() {
343     if (loop_device.Get() != -1) {
344       if (umount2(mount_point.c_str(), UMOUNT_NOFOLLOW) != 0) {
345         PLOG(ERROR) << "can't umount.";
346       }
347       loop_device.CloseGood();
348     }
349   }
350 };
351 
WriteBlockApex(const std::string & apex_file,const std::string & apex_path)352 inline base::Result<BlockApex> WriteBlockApex(const std::string& apex_file,
353                                               const std::string& apex_path) {
354   std::string intermediate_path = apex_path + ".intermediate";
355   std::filesystem::copy(apex_file, intermediate_path);
356   auto result = MountViaLoopDevice(intermediate_path, apex_path);
357   if (!result.ok()) {
358     return result.error();
359   }
360   return BlockApex(std::move(*result), apex_path);
361 }
362 
GetBlockDeviceForApex(const std::string & package_id)363 inline android::base::Result<std::string> GetBlockDeviceForApex(
364     const std::string& package_id) {
365   using android::fs_mgr::Fstab;
366   using android::fs_mgr::GetEntryForMountPoint;
367   using android::fs_mgr::ReadFstabFromFile;
368 
369   std::string mount_point = std::string(kApexRoot) + "/" + package_id;
370   Fstab fstab;
371   if (!ReadFstabFromFile("/proc/mounts", &fstab)) {
372     return android::base::Error() << "Failed to read /proc/mounts";
373   }
374   auto entry = GetEntryForMountPoint(&fstab, mount_point);
375   if (entry == nullptr) {
376     return android::base::Error()
377            << "Can't find " << mount_point << " in /proc/mounts";
378   }
379   return entry->blk_device;
380 }
381 
ReadDevice(const std::string & block_device)382 inline android::base::Result<void> ReadDevice(const std::string& block_device) {
383   static constexpr int kBlockSize = 4096;
384   static constexpr size_t kBufSize = 1024 * kBlockSize;
385   std::vector<uint8_t> buffer(kBufSize);
386 
387   android::base::unique_fd fd(
388       TEMP_FAILURE_RETRY(open(block_device.c_str(), O_RDONLY | O_CLOEXEC)));
389   if (fd.get() == -1) {
390     return android::base::ErrnoError() << "Can't open " << block_device;
391   }
392 
393   while (true) {
394     int n = read(fd.get(), buffer.data(), kBufSize);
395     if (n < 0) {
396       return android::base::ErrnoError() << "Failed to read " << block_device;
397     }
398     if (n == 0) {
399       break;
400     }
401   }
402   return {};
403 }
404 
ListChildLoopDevices(const std::string & name)405 inline android::base::Result<std::vector<std::string>> ListChildLoopDevices(
406     const std::string& name) {
407   using android::base::Error;
408   using android::dm::DeviceMapper;
409 
410   DeviceMapper& dm = DeviceMapper::Instance();
411   std::string dm_path;
412   if (!dm.GetDmDevicePathByName(name, &dm_path)) {
413     return Error() << "Failed to get path of dm device " << name;
414   }
415   // It's a little bit sad we can't use ConsumePrefix here :(
416   constexpr std::string_view kDevPrefix = "/dev/";
417   if (!android::base::StartsWith(dm_path, kDevPrefix)) {
418     return Error() << "Illegal path " << dm_path;
419   }
420   dm_path = dm_path.substr(kDevPrefix.length());
421   std::vector<std::string> children;
422   std::string dir = "/sys/" + dm_path + "/slaves";
423   auto status = WalkDir(dir, [&](const auto& entry) {
424     std::error_code ec;
425     if (entry.is_symlink(ec)) {
426       children.push_back("/dev/block/" + entry.path().filename().string());
427     }
428   });
429   if (!status.ok()) {
430     return status.error();
431   }
432   return children;
433 }
434 
GetLoopDeviceStatus(const std::string & loop_device)435 inline android::base::Result<struct loop_info64> GetLoopDeviceStatus(
436     const std::string& loop_device) {
437   android::base::unique_fd loop_fd(
438       open(loop_device.c_str(), O_RDONLY | O_CLOEXEC));
439   if (loop_fd < 0) {
440     return ErrnoErrorf("Failed to open loop device '{}'", loop_device);
441   }
442   struct loop_info64 loop_info;
443   if (ioctl(loop_fd, LOOP_GET_STATUS64, &loop_info) != 0) {
444     return ErrnoErrorf("Failed to get loop device status '{}'", loop_device);
445   }
446   return loop_info;
447 }
448 
449 }  // namespace apex
450 }  // namespace android
451 
452 namespace com {
453 namespace android {
454 namespace apex {
455 
456 namespace testing {
457 
458 // "preinstalledModulePath" is an optional in ApexInfoList.xsd.
459 // getPreinstalledModulePath() should be called when hasPreinstalledModulePath()
460 // returns true. Introducing a simple wrapper which returns optional<string>.
getPreinstalledModulePath(const ApexInfo & obj)461 inline std::optional<std::string> getPreinstalledModulePath(
462     const ApexInfo& obj) {
463   if (obj.hasPreinstalledModulePath()) {
464     return obj.getPreinstalledModulePath();
465   }
466   return std::nullopt;
467 }
468 
469 MATCHER_P(ApexInfoXmlEq, other, "") {
470   using ::testing::AllOf;
471   using ::testing::Eq;
472   using ::testing::ExplainMatchResult;
473   using ::testing::Field;
474   using ::testing::Property;
475   using ::testing::ResultOf;
476 
477   return ExplainMatchResult(
478       AllOf(
479           Property("moduleName", &ApexInfo::getModuleName,
480                    Eq(other.getModuleName())),
481           Property("modulePath", &ApexInfo::getModulePath,
482                    Eq(other.getModulePath())),
483           ResultOf(&getPreinstalledModulePath,
484                    Eq(getPreinstalledModulePath(other))),
485           Property("versionCode", &ApexInfo::getVersionCode,
486                    Eq(other.getVersionCode())),
487           Property("isFactory", &ApexInfo::getIsFactory,
488                    Eq(other.getIsFactory())),
489           Property("isActive", &ApexInfo::getIsActive, Eq(other.getIsActive())),
490           Property("lastUpdateMillis", &ApexInfo::getLastUpdateMillis,
491                    Eq(other.getLastUpdateMillis())),
492           Property("partition", &ApexInfo::getPartition,
493                    Eq(other.getPartition()))),
494       arg, result_listener);
495 }
496 
497 }  // namespace testing
498 
499 // Must be in com::android::apex namespace for gtest to pick it up.
PrintTo(const ApexInfo & apex,std::ostream * os)500 inline void PrintTo(const ApexInfo& apex, std::ostream* os) {
501   *os << "apex_info: {\n";
502   *os << "  moduleName : " << apex.getModuleName() << "\n";
503   *os << "  modulePath : " << apex.getModulePath() << "\n";
504   if (apex.hasPreinstalledModulePath()) {
505     *os << "  preinstalledModulePath : " << apex.getPreinstalledModulePath()
506         << "\n";
507   }
508   *os << "  versionCode : " << apex.getVersionCode() << "\n";
509   *os << "  isFactory : " << apex.getIsFactory() << "\n";
510   *os << "  isActive : " << apex.getIsActive() << "\n";
511   *os << "  partition : " << apex.getPartition() << "\n";
512   *os << "}";
513 }
514 
515 }  // namespace apex
516 }  // namespace android
517 }  // namespace com
518