func (s *SnapSuite) TestSnapRunHookUnsetRevisionIntegration(c *check.C) { // mock installed snap dirs.SetRootDir(c.MkDir()) defer func() { dirs.SetRootDir("/") }() si := snaptest.MockSnap(c, string(mockYaml), &snap.SideInfo{ Revision: snap.R(42), }) err := os.Symlink(si.MountDir(), filepath.Join(si.MountDir(), "../current")) c.Assert(err, check.IsNil) // redirect exec execArg0 := "" execArgs := []string{} execEnv := []string{} restorer := snaprun.MockSyscallExec(func(arg0 string, args []string, envv []string) error { execArg0 = arg0 execArgs = args execEnv = envv return nil }) defer restorer() // Specifically pass "unset" which would use the active version. _, err = snaprun.Parser().ParseArgs([]string{"run", "--hook=configure", "-r=unset", "snapname"}) c.Assert(err, check.IsNil) c.Check(execArg0, check.Equals, filepath.Join(dirs.LibExecDir, "snap-confine")) c.Check(execArgs, check.DeepEquals, []string{ filepath.Join(dirs.LibExecDir, "snap-confine"), "snap.snapname.hook.configure", filepath.Join(dirs.LibExecDir, "snap-exec"), "--hook=configure", "snapname"}) c.Check(execEnv, testutil.Contains, "SNAP_REVISION=42") }
func (s *SnapSuite) TestSnapRunAppWithCommandIntegration(c *check.C) { // mock installed snap dirs.SetRootDir(c.MkDir()) defer func() { dirs.SetRootDir("/") }() si := snaptest.MockSnap(c, string(mockYaml), &snap.SideInfo{ Revision: snap.R(42), }) err := os.Symlink(si.MountDir(), filepath.Join(si.MountDir(), "../current")) c.Assert(err, check.IsNil) // redirect exec execArg0 := "" execArgs := []string{} execEnv := []string{} restorer := snaprun.MockSyscallExec(func(arg0 string, args []string, envv []string) error { execArg0 = arg0 execArgs = args execEnv = envv return nil }) defer restorer() // and run it! err = snaprun.SnapRunApp("snapname.app", "my-command", []string{"arg1", "arg2"}) c.Assert(err, check.IsNil) c.Check(execArg0, check.Equals, filepath.Join(dirs.LibExecDir, "snap-confine")) c.Check(execArgs, check.DeepEquals, []string{ filepath.Join(dirs.LibExecDir, "snap-confine"), "snap.snapname.app", filepath.Join(dirs.LibExecDir, "snap-exec"), "--command=my-command", "snapname.app", "arg1", "arg2"}) c.Check(execEnv, testutil.Contains, "SNAP_REVISION=42") }
func (s *SnapSuite) TestAutoImportIntoSpoolUnhappyTooBig(c *C) { restore := release.MockOnClassic(false) defer restore() dirs.SetRootDir(c.MkDir()) defer dirs.SetRootDir("") l, err := logger.NewConsoleLog(s.stderr, 0) c.Assert(err, IsNil) logger.SetLogger(l) // fake data is bigger than the default assertion limit fakeAssertData := make([]byte, 641*1024) // ensure we can not connect snap.ClientConfig.BaseURL = "can-not-connect-to-this-url" fakeAssertsFn := filepath.Join(c.MkDir(), "auto-import.assert") err = ioutil.WriteFile(fakeAssertsFn, fakeAssertData, 0644) c.Assert(err, IsNil) mockMountInfoFmt := ` 24 0 8:18 / %s rw,relatime shared:1 - squashfs /dev/sc1 rw,errors=remount-ro,data=ordered` content := fmt.Sprintf(mockMountInfoFmt, filepath.Dir(fakeAssertsFn)) restore = snap.MockMountInfoPath(makeMockMountInfo(c, content)) defer restore() _, err = snap.Parser().ParseArgs([]string{"auto-import"}) c.Assert(err, ErrorMatches, "cannot queue .*, file size too big: 656384") }
func (s *SnapSuite) TestSnapRunHookMissingHookIntegration(c *check.C) { // mock installed snap dirs.SetRootDir(c.MkDir()) defer func() { dirs.SetRootDir("/") }() // Only create revision 42 snaptest.MockSnap(c, string(mockYaml), &snap.SideInfo{ Revision: snap.R(42), }) // and mock the server s.mockServer(c) // redirect exec called := false restorer := snaprun.MockSyscallExec(func(arg0 string, args []string, envv []string) error { called = true return nil }) defer restorer() err := snaprun.SnapRunHook("snapname", "unset", "missing-hook") c.Assert(err, check.IsNil) c.Check(called, check.Equals, false) }
func (s *SnapSuite) TestAutoImportFromSpoolHappy(c *C) { restore := release.MockOnClassic(false) defer restore() fakeAssertData := []byte("my-assertion") n := 0 total := 2 s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) { switch n { case 0: c.Check(r.Method, Equals, "POST") c.Check(r.URL.Path, Equals, "/v2/assertions") postData, err := ioutil.ReadAll(r.Body) c.Assert(err, IsNil) c.Check(postData, DeepEquals, fakeAssertData) fmt.Fprintln(w, `{"type": "sync", "result": {"ready": true, "status": "Done"}}`) n++ case 1: c.Check(r.Method, Equals, "POST") c.Check(r.URL.Path, Equals, "/v2/create-user") postData, err := ioutil.ReadAll(r.Body) c.Assert(err, IsNil) c.Check(string(postData), Equals, `{"sudoer":true,"known":true}`) fmt.Fprintln(w, `{"type": "sync", "result": [{"username": "******"}]}`) n++ default: c.Fatalf("unexpected request: %v (expected %d got %d)", r, total, n) } }) dirs.SetRootDir(c.MkDir()) defer dirs.SetRootDir("") fakeAssertsFn := filepath.Join(dirs.SnapAssertsSpoolDir, "1234343") err := os.MkdirAll(filepath.Dir(fakeAssertsFn), 0755) c.Assert(err, IsNil) err = ioutil.WriteFile(fakeAssertsFn, fakeAssertData, 0644) c.Assert(err, IsNil) l, err := logger.NewConsoleLog(s.stderr, 0) c.Assert(err, IsNil) logger.SetLogger(l) rest, err := snap.Parser().ParseArgs([]string{"auto-import"}) c.Assert(err, IsNil) c.Assert(rest, DeepEquals, []string{}) c.Check(s.Stdout(), Equals, `created user "foo"`+"\n") // matches because we may get a: // "WARNING: cannot create syslog logger\n" // in the output c.Check(s.Stderr(), Matches, fmt.Sprintf("(?ms).*imported %s\n", fakeAssertsFn)) c.Check(n, Equals, total) c.Check(osutil.FileExists(fakeAssertsFn), Equals, false) }
func (s *SnapSuite) TestSnapGetIntegrationMissingKey(c *check.C) { // mock installed snap dirs.SetRootDir(c.MkDir()) defer func() { dirs.SetRootDir("/") }() s.setupGetTests(c) // Get the config value for the active snap _, err := snapset.Parser().ParseArgs([]string{"get", "snapname", "missing-key"}) c.Check(err, check.IsNil) c.Check(s.Stdout(), check.Equals, "\n") }
func (s *FirstBootTestSuite) SetUpTest(c *C) { tempdir := c.MkDir() dirs.SetRootDir(tempdir) // mock the world! err := os.MkdirAll(filepath.Join(dirs.SnapSeedDir, "snaps"), 0755) c.Assert(err, IsNil) err = os.MkdirAll(filepath.Join(dirs.SnapSeedDir, "assertions"), 0755) c.Assert(err, IsNil) err = os.MkdirAll(dirs.SnapServicesDir, 0755) c.Assert(err, IsNil) os.Setenv("SNAPPY_SQUASHFS_UNPACK_FOR_TESTS", "1") s.systemctl = testutil.MockCommand(c, "systemctl", "") s.mockUdevAdm = testutil.MockCommand(c, "udevadm", "") err = ioutil.WriteFile(filepath.Join(dirs.SnapSeedDir, "seed.yaml"), nil, 0644) c.Assert(err, IsNil) rootPrivKey, _ := assertstest.GenerateKey(1024) storePrivKey, _ := assertstest.GenerateKey(752) s.storeSigning = assertstest.NewStoreStack("can0nical", rootPrivKey, storePrivKey) s.restore = sysdb.InjectTrusted(s.storeSigning.Trusted) s.brandPrivKey, _ = assertstest.GenerateKey(752) s.brandSigning = assertstest.NewSigningDB("my-brand", s.brandPrivKey) ovld, err := overlord.New() c.Assert(err, IsNil) s.overlord = ovld }
func (ms *mgrsSuite) SetUpTest(c *C) { ms.tempdir = c.MkDir() dirs.SetRootDir(ms.tempdir) err := os.MkdirAll(filepath.Dir(dirs.SnapStateFile), 0755) c.Assert(err, IsNil) os.Setenv("SNAPPY_SQUASHFS_UNPACK_FOR_TESTS", "1") // create a fake systemd environment os.MkdirAll(filepath.Join(dirs.SnapServicesDir, "multi-user.target.wants"), 0755) ms.prevctlCmd = systemd.SystemctlCmd systemd.SystemctlCmd = func(cmd ...string) ([]byte, error) { return []byte("ActiveState=inactive\n"), nil } ms.aa = testutil.MockCommand(c, "apparmor_parser", "") ms.udev = testutil.MockCommand(c, "udevadm", "") ms.umount = testutil.MockCommand(c, "umount", "") ms.snapDiscardNs = testutil.MockCommand(c, "snap-discard-ns", "") dirs.LibExecDir = ms.snapDiscardNs.BinDir() ms.storeSigning = assertstest.NewStoreStack("can0nical", rootPrivKey, storePrivKey) ms.restoreTrusted = sysdb.InjectTrusted(ms.storeSigning.Trusted) ms.devAcct = assertstest.NewAccount(ms.storeSigning, "devdevev", map[string]interface{}{ "account-id": "devdevdev", }, "") err = ms.storeSigning.Add(ms.devAcct) c.Assert(err, IsNil) o, err := overlord.New() c.Assert(err, IsNil) ms.o = o }
func (sdbs *sysDBSuite) SetUpTest(c *C) { tmpdir := c.MkDir() pk, _ := assertstest.GenerateKey(752) signingDB := assertstest.NewSigningDB("can0nical", pk) trustedAcct := assertstest.NewAccount(signingDB, "can0nical", map[string]interface{}{ "account-id": "can0nical", "validation": "certified", "timestamp": "2015-11-20T15:04:00Z", }, "") trustedAccKey := assertstest.NewAccountKey(signingDB, trustedAcct, map[string]interface{}{ "account-id": "can0nical", "since": "2015-11-20T15:04:00Z", "until": "2500-11-20T15:04:00Z", }, pk.PublicKey(), "") sdbs.extraTrusted = []asserts.Assertion{trustedAcct, trustedAccKey} fakeRoot := filepath.Join(tmpdir, "root") err := os.Mkdir(fakeRoot, os.ModePerm) c.Assert(err, IsNil) dirs.SetRootDir(fakeRoot) sdbs.probeAssert = assertstest.NewAccount(signingDB, "probe", nil, "") }
func (s *snapExecSuite) TestSnapExecHookRealIntegration(c *C) { // we need a lot of mocks dirs.SetRootDir(c.MkDir()) oldOsArgs := os.Args defer func() { os.Args = oldOsArgs }() os.Setenv("SNAP_REVISION", "42") defer os.Unsetenv("SNAP_REVISION") canaryFile := filepath.Join(c.MkDir(), "canary.txt") testSnap := snaptest.MockSnap(c, string(mockHookYaml), &snap.SideInfo{ Revision: snap.R("42"), }) hookPath := filepath.Join("meta", "hooks", "configure") hookPathAndContents := []string{hookPath, fmt.Sprintf(binaryTemplate, canaryFile)} snaptest.PopulateDir(testSnap.MountDir(), [][]string{hookPathAndContents}) hookPath = filepath.Join(testSnap.MountDir(), hookPath) c.Assert(os.Chmod(hookPath, 0755), IsNil) // we can not use the real syscall.execv here because it would // replace the entire test :) syscallExec = actuallyExec // run it os.Args = []string{"snap-exec", "--hook=configure", "snapname"} err := run() c.Assert(err, IsNil) output, err := ioutil.ReadFile(canaryFile) c.Assert(err, IsNil) c.Assert(string(output), Equals, "configure\n\n") }
func (s *deviceMgrSuite) SetUpTest(c *C) { dirs.SetRootDir(c.MkDir()) rootPrivKey, _ := assertstest.GenerateKey(1024) storePrivKey, _ := assertstest.GenerateKey(752) s.storeSigning = assertstest.NewStoreStack("canonical", rootPrivKey, storePrivKey) s.state = state.New(nil) db, err := asserts.OpenDatabase(&asserts.DatabaseConfig{ Backstore: asserts.NewMemoryBackstore(), Trusted: s.storeSigning.Trusted, }) c.Assert(err, IsNil) s.state.Lock() assertstate.ReplaceDB(s.state, db) s.state.Unlock() err = db.Add(s.storeSigning.StoreAccountKey("")) c.Assert(err, IsNil) mgr, err := devicestate.Manager(s.state) c.Assert(err, IsNil) s.db = db s.mgr = mgr s.state.Lock() snapstate.ReplaceStore(s.state, &fakeStore{ state: s.state, db: s.storeSigning, }) s.state.Unlock() }
func (s *assertMgrSuite) SetUpTest(c *C) { dirs.SetRootDir(c.MkDir()) rootPrivKey, _ := assertstest.GenerateKey(1024) storePrivKey, _ := assertstest.GenerateKey(752) s.storeSigning = assertstest.NewStoreStack("can0nical", rootPrivKey, storePrivKey) s.restore = sysdb.InjectTrusted(s.storeSigning.Trusted) dev1PrivKey, _ := assertstest.GenerateKey(752) s.dev1Acct = assertstest.NewAccount(s.storeSigning, "developer1", nil, "") err := s.storeSigning.Add(s.dev1Acct) c.Assert(err, IsNil) // developer signing dev1AcctKey := assertstest.NewAccountKey(s.storeSigning, s.dev1Acct, nil, dev1PrivKey.PublicKey(), "") err = s.storeSigning.Add(dev1AcctKey) c.Assert(err, IsNil) s.dev1Signing = assertstest.NewSigningDB(s.dev1Acct.AccountID(), dev1PrivKey) s.state = state.New(nil) mgr, err := assertstate.Manager(s.state) c.Assert(err, IsNil) s.mgr = mgr s.state.Lock() snapstate.ReplaceStore(s.state, &fakeStore{ state: s.state, db: s.storeSigning, }) s.state.Unlock() }
func (s *appArmorSuite) TestUnloadRemovesCachedProfile(c *C) { cmd := testutil.MockCommand(c, "apparmor_parser", "") defer cmd.Restore() dirs.SetRootDir(c.MkDir()) defer dirs.SetRootDir("") err := os.MkdirAll(dirs.AppArmorCacheDir, 0755) c.Assert(err, IsNil) fname := filepath.Join(dirs.AppArmorCacheDir, "profile") ioutil.WriteFile(fname, []byte("blob"), 0600) err = apparmor.UnloadProfile("profile") c.Assert(err, IsNil) _, err = os.Stat(fname) c.Check(os.IsNotExist(err), Equals, true) }
func (s *deviceMgrSuite) TearDownTest(c *C) { s.state.Lock() assertstate.ReplaceDB(s.state, nil) s.state.Unlock() dirs.SetRootDir("") release.OnClassic = true }
func (s *PartitionTestSuite) SetUpTest(c *C) { dirs.SetRootDir(c.MkDir()) err := os.MkdirAll((&grub{}).Dir(), 0755) c.Assert(err, IsNil) err = os.MkdirAll((&uboot{}).Dir(), 0755) c.Assert(err, IsNil) }
func (s *SnapSuite) TestSnapSetIntegrationJson(c *check.C) { // mock installed snap dirs.SetRootDir(c.MkDir()) defer func() { dirs.SetRootDir("/") }() snaptest.MockSnap(c, string(validApplyYaml), &snap.SideInfo{ Revision: snap.R(42), }) // and mock the server s.mockSetConfigServer(c, map[string]interface{}{"subkey": "value"}) // Set a config value for the active snap _, err := snapset.Parser().ParseArgs([]string{"set", "snapname", `key={"subkey":"value"}`}) c.Assert(err, check.IsNil) }
func (s *hookManagerSuite) SetUpTest(c *C) { dirs.SetRootDir(c.MkDir()) s.state = state.New(nil) manager, err := Manager(s.state) c.Assert(err, IsNil) s.manager = manager }
func (s *interfaceManagerSuite) TearDownTest(c *C) { if s.privateMgr != nil { s.privateMgr.Stop() } dirs.SetRootDir("") s.restoreBackends() }
func (s *patch6Suite) SetUpTest(c *C) { dirs.SetRootDir(c.MkDir()) err := os.MkdirAll(filepath.Dir(dirs.SnapStateFile), 0755) c.Assert(err, IsNil) err = ioutil.WriteFile(dirs.SnapStateFile, statePatch5JSON, 0644) c.Assert(err, IsNil) }
func (s *linkSuite) SetUpTest(c *C) { dirs.SetRootDir(c.MkDir()) s.prevctlCmd = systemd.SystemctlCmd systemd.SystemctlCmd = func(cmd ...string) ([]byte, error) { return []byte("ActiveState=inactive\n"), nil } }
func (s *FirstBootTestSuite) TearDownTest(c *C) { dirs.SetRootDir("/") os.Unsetenv("SNAPPY_SQUASHFS_UNPACK_FOR_TESTS") s.systemctl.Restore() s.mockUdevAdm.Restore() s.restore() }
func (s *imageSuite) TestInstallCloudConfigNoConfig(c *C) { targetDir := c.MkDir() emptyGadgetDir := c.MkDir() dirs.SetRootDir(targetDir) err := image.InstallCloudConfig(emptyGadgetDir) c.Assert(err, IsNil) c.Check(osutil.FileExists(filepath.Join(targetDir, "etc/cloud/cloud-init.disabled")), Equals, true) }
func (s *interfaceManagerSuite) SetUpTest(c *C) { dirs.SetRootDir(c.MkDir()) state := state.New(nil) s.state = state s.privateMgr = nil s.extraIfaces = nil s.secBackend = &interfaces.TestSecurityBackend{} s.restoreBackends = ifacestate.MockSecurityBackends([]interfaces.SecurityBackend{s.secBackend}) }
func (s *servicesTestSuite) SetUpTest(c *C) { s.tempdir = c.MkDir() dirs.SetRootDir(s.tempdir) s.prevctlCmd = systemd.SystemctlCmd systemd.SystemctlCmd = func(cmd ...string) ([]byte, error) { return []byte("ActiveState=inactive\n"), nil } }
func (s *FirstBootTestSuite) SetUpTest(c *C) { tempdir := c.MkDir() dirs.SetRootDir(tempdir) s.netplanConfigFile = netplanConfigFile netplanConfigFile = filepath.Join(c.MkDir(), "config.yaml") s.enableConfig = enableConfig enableConfig = []string{"/bin/true"} }
func (s *BackendSuite) SetUpTest(c *C) { // Isolate this test to a temporary directory s.RootDir = c.MkDir() dirs.SetRootDir(s.RootDir) // Create a fresh repository for each test s.Repo = interfaces.NewRepository() s.Iface = &interfaces.TestInterface{InterfaceName: "iface"} err := s.Repo.AddInterface(s.Iface) c.Assert(err, IsNil) }
func (ms *mgrsSuite) TearDownTest(c *C) { dirs.SetRootDir("") ms.restoreTrusted() os.Unsetenv("SNAPPY_SQUASHFS_UNPACK_FOR_TESTS") systemd.SystemctlCmd = ms.prevctlCmd ms.udev.Restore() ms.aa.Restore() ms.umount.Restore() ms.snapDiscardNs.Restore() }
func (s *snapExecSuite) TestSnapExecHookMissingHookIntegration(c *C) { dirs.SetRootDir(c.MkDir()) snaptest.MockSnap(c, string(mockHookYaml), &snap.SideInfo{ Revision: snap.R("42"), }) err := snapExecHook("snapname", "42", "missing-hook") c.Assert(err, NotNil) c.Assert(err, ErrorMatches, "cannot find hook \"missing-hook\" in \"snapname\"") }
func (s *setupSuite) SetUpTest(c *C) { dirs.SetRootDir(c.MkDir()) err := os.MkdirAll(filepath.Join(dirs.GlobalRootDir, "etc", "systemd", "system", "multi-user.target.wants"), 0755) c.Assert(err, IsNil) s.prevctlCmd = systemd.SystemctlCmd systemd.SystemctlCmd = func(cmd ...string) ([]byte, error) { return []byte("ActiveState=inactive\n"), nil } s.umount = testutil.MockCommand(c, "umount", "") }
func (s *SnapSuite) TestAutoImportIntoSpool(c *C) { restore := release.MockOnClassic(false) defer restore() dirs.SetRootDir(c.MkDir()) defer dirs.SetRootDir("") l, err := logger.NewConsoleLog(s.stderr, 0) c.Assert(err, IsNil) logger.SetLogger(l) fakeAssertData := []byte("good-assertion") // ensure we can not connect snap.ClientConfig.BaseURL = "can-not-connect-to-this-url" fakeAssertsFn := filepath.Join(c.MkDir(), "auto-import.assert") err = ioutil.WriteFile(fakeAssertsFn, fakeAssertData, 0644) c.Assert(err, IsNil) mockMountInfoFmt := ` 24 0 8:18 / %s rw,relatime shared:1 - squashfs /dev/sc1 rw,errors=remount-ro,data=ordered` content := fmt.Sprintf(mockMountInfoFmt, filepath.Dir(fakeAssertsFn)) restore = snap.MockMountInfoPath(makeMockMountInfo(c, content)) defer restore() rest, err := snap.Parser().ParseArgs([]string{"auto-import"}) c.Assert(err, IsNil) c.Assert(rest, DeepEquals, []string{}) c.Check(s.Stdout(), Equals, "") // matches because we may get a: // "WARNING: cannot create syslog logger\n" // in the output c.Check(s.Stderr(), Matches, "(?ms).*queuing for later.*\n") files, err := ioutil.ReadDir(dirs.SnapAssertsSpoolDir) c.Assert(err, IsNil) c.Check(files, HasLen, 1) c.Check(files[0].Name(), Equals, "iOkaeet50rajLvL-0Qsf2ELrTdn3XIXRIBlDewcK02zwRi3_TJlUOTl9AaiDXmDn.assert") }