• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2019 The Chromium OS Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "brillo/scoped_umask.h"
6 
7 #include <fcntl.h>
8 
9 #include <base/files/file_path.h>
10 #include <base/files/file_util.h>
11 #include <base/files/scoped_file.h>
12 #include <base/files/scoped_temp_dir.h>
13 #include <gtest/gtest.h>
14 
15 namespace brillo {
16 namespace {
17 
18 constexpr int kPermissions600 =
19     base::FILE_PERMISSION_READ_BY_USER | base::FILE_PERMISSION_WRITE_BY_USER;
20 constexpr int kPermissions700 = base::FILE_PERMISSION_USER_MASK;
21 constexpr mode_t kMask700 = ~(0700);
22 constexpr mode_t kMask600 = ~(0600);
23 
CheckFilePermissions(const base::FilePath & path,int expected_permissions)24 void CheckFilePermissions(const base::FilePath& path,
25                           int expected_permissions) {
26   int mode = 0;
27   // Try to create a file with broader permissions than the mask may provide.
28   base::ScopedFD fd(
29       HANDLE_EINTR(open(path.value().c_str(), O_WRONLY | O_CREAT, 0777)));
30   EXPECT_TRUE(fd.is_valid());
31   EXPECT_TRUE(base::GetPosixFilePermissions(path, &mode));
32   EXPECT_EQ(mode, expected_permissions);
33 }
34 
35 }  // namespace
36 
TEST(ScopedUmask,CheckUmaskScope)37 TEST(ScopedUmask, CheckUmaskScope) {
38   base::ScopedTempDir tmpdir;
39   CHECK(tmpdir.CreateUniqueTempDir());
40 
41   brillo::ScopedUmask outer_scoped_umask_(kMask700);
42   CheckFilePermissions(tmpdir.GetPath().AppendASCII("file1.txt"),
43                        kPermissions700);
44   {
45     // A new scoped umask should result in different permissions for files
46     // created in this scope.
47     brillo::ScopedUmask inner_scoped_umask_(kMask600);
48     CheckFilePermissions(tmpdir.GetPath().AppendASCII("file2.txt"),
49                          kPermissions600);
50   }
51   // Since inner_scoped_umask_ has been deconstructed, permissions on all new
52   // files should now use outer_scoped_umask_.
53   CheckFilePermissions(tmpdir.GetPath().AppendASCII("file3.txt"),
54                        kPermissions700);
55 }
56 
57 }  // namespace brillo
58