1// Copyright 2021 Google Inc. All rights reserved. 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15package build 16 17import ( 18 "os" 19 "testing" 20) 21 22func TestMain(m *testing.M) { 23 // set src dir of sandbox 24 sandboxConfig.srcDir = "/my/src/dir" 25 os.Exit(m.Run()) 26} 27 28func TestMountFlagsSrcDir(t *testing.T) { 29 testCases := []struct { 30 srcDirIsRO bool 31 expectedSrcDirFlag string 32 }{ 33 { 34 srcDirIsRO: false, 35 expectedSrcDirFlag: "-B", 36 }, 37 { 38 srcDirIsRO: true, 39 expectedSrcDirFlag: "-R", 40 }, 41 } 42 for _, testCase := range testCases { 43 c := testCmd() 44 c.config.sandboxConfig.SetSrcDirIsRO(testCase.srcDirIsRO) 45 c.wrapSandbox() 46 if !isExpectedMountFlag(c.Args, sandboxConfig.srcDir, testCase.expectedSrcDirFlag) { 47 t.Error("Mount flag of srcDir is not correct") 48 } 49 } 50} 51 52func TestMountFlagsSrcDirRWAllowlist(t *testing.T) { 53 testCases := []struct { 54 srcDirRWAllowlist []string 55 }{ 56 { 57 srcDirRWAllowlist: []string{}, 58 }, 59 { 60 srcDirRWAllowlist: []string{"my/path"}, 61 }, 62 { 63 srcDirRWAllowlist: []string{"my/path1", "my/path2"}, 64 }, 65 } 66 for _, testCase := range testCases { 67 c := testCmd() 68 c.config.sandboxConfig.SetSrcDirIsRO(true) 69 c.config.sandboxConfig.SetSrcDirRWAllowlist(testCase.srcDirRWAllowlist) 70 c.wrapSandbox() 71 for _, allowlistPath := range testCase.srcDirRWAllowlist { 72 if !isExpectedMountFlag(c.Args, allowlistPath, "-B") { 73 t.Error("Mount flag of srcDirRWAllowlist is not correct, expect -B") 74 } 75 } 76 } 77} 78 79// utils for setting up test 80func testConfig() Config { 81 // create a minimal testConfig 82 env := Environment([]string{}) 83 sandboxConfig := SandboxConfig{} 84 return Config{&configImpl{environ: &env, 85 sandboxConfig: &sandboxConfig}} 86} 87 88func testCmd() *Cmd { 89 return Command(testContext(), testConfig(), "sandbox_test", "path/to/nsjail") 90} 91 92func isExpectedMountFlag(cmdArgs []string, dirName string, expectedFlag string) bool { 93 indexOfSrcDir := index(cmdArgs, dirName) 94 return cmdArgs[indexOfSrcDir-1] == expectedFlag 95} 96 97func index(arr []string, target string) int { 98 for idx, element := range arr { 99 if element == target { 100 return idx 101 } 102 } 103 panic("element could not be located in input array") 104} 105