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