Exemple #1
0
func (s *BuySnapSuite) TestBuyInvalidCharacters(c *check.C) {
	_, err := snap.Parser().ParseArgs([]string{"buy", "a:b"})
	c.Assert(err, check.NotNil)
	c.Check(err.Error(), check.Equals, "cannot buy snap: invalid characters in name")
	c.Check(s.Stdout(), check.Equals, "")
	c.Check(s.Stderr(), check.Equals, "")

	_, err = snap.Parser().ParseArgs([]string{"buy", "c*d"})
	c.Assert(err, check.NotNil)
	c.Check(err.Error(), check.Equals, "cannot buy snap: invalid characters in name")
	c.Check(s.Stdout(), check.Equals, "")
	c.Check(s.Stderr(), check.Equals, "")
}
Exemple #2
0
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) TestCreateKeyInvalidCharacters(c *C) {
	_, err := snap.Parser().ParseArgs([]string{"create-key", "a b"})
	c.Assert(err, NotNil)
	c.Check(err.Error(), Equals, "key name \"a b\" is not valid; only ASCII letters, digits, and hyphens are allowed")
	c.Check(s.Stdout(), Equals, "")
	c.Check(s.Stderr(), Equals, "")
}
Exemple #4
0
func (s *SnapSuite) TestLoginAskEmail(c *C) {
	if err := archWithBrokenDevPtmx(); err != nil {
		c.Skip(err.Error())
	}

	n := 0
	s.RedirectClientToTestServer(makeLoginTestServer(c, &n))

	// send the email
	fmt.Fprint(s.stdin, "[email protected]\n")
	// send the password
	fmt.Fprint(s.term, "some-password\n")

	rest, err := snap.Parser().ParseArgs([]string{"login"})
	c.Assert(err, IsNil)
	c.Assert(rest, DeepEquals, []string{})
	// test slightly ugly, on a real system STDOUT will be:
	//    Email address: [email protected]\n
	// because the input to stdin is echoed
	c.Check(s.Stdout(), Equals, `Email address: Password of "*****@*****.**": 
Login successful
`)
	c.Check(s.Stderr(), Equals, "")
	c.Check(n, Equals, 1)
}
Exemple #5
0
func (s *SnapSuite) TestSnapRunAppIntegration(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("x2"),
	})
	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!
	rest, err := snaprun.Parser().ParseArgs([]string{"run", "snapname.app", "--arg1", "arg2"})
	c.Assert(err, check.IsNil)
	c.Assert(rest, check.DeepEquals, []string{"snapname.app", "--arg1", "arg2"})
	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"),
		"snapname.app", "--arg1", "arg2"})
	c.Check(execEnv, testutil.Contains, "SNAP_REVISION=x2")
}
func (s *SnapSuite) TestAutoImportAssertsHappyNotOnClassic(c *C) {
	restore := release.MockOnClassic(true)
	defer restore()

	fakeAssertData := []byte("my-assertion")
	s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) {
		c.Errorf("auto-import on classic is disabled, but something tried to do a %q with %s", r.Method, r.URL.Path)
	})

	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 - ext4 /dev/sdb2 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, "")
	c.Check(s.Stderr(), Equals, "auto-import is disabled on classic\n")
}
Exemple #7
0
func (s *SnapSuite) TestFindNothingFails(c *check.C) {
	s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) {
		c.Fatalf("it reached the server")
	})
	_, err := snap.Parser().ParseArgs([]string{"find"})
	c.Assert(err, check.ErrorMatches, `you need to specify a query. Try.*`)
}
Exemple #8
0
func (s *SnapSuite) TestFindHello(c *check.C) {
	n := 0
	s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) {
		switch n {
		case 0:
			c.Check(r.Method, check.Equals, "GET")
			c.Check(r.URL.Path, check.Equals, "/v2/find")
			q := r.URL.Query()
			c.Check(q.Get("q"), check.Equals, "hello")
			fmt.Fprintln(w, findHelloJSON)
		default:
			c.Fatalf("expected to get 1 requests, now on %d", n+1)
		}

		n++
	})
	rest, err := snap.Parser().ParseArgs([]string{"find", "hello"})
	c.Assert(err, check.IsNil)
	c.Assert(rest, check.DeepEquals, []string{})
	c.Check(s.Stdout(), check.Matches, `Name +Version +Developer +Notes +Summary
hello +2.10 +canonical +- +GNU Hello, the "hello world" snap
hello-huge +1.0 +noise +- +a really big snap
`)
	c.Check(s.Stderr(), check.Equals, "")
}
Exemple #9
0
func (s *SnapSuite) TestListWithNotes(c *check.C) {
	n := 0
	s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) {
		switch n {
		case 0:
			c.Check(r.Method, check.Equals, "GET")
			c.Check(r.URL.Path, check.Equals, "/v2/snaps")
			fmt.Fprintln(w, `{"type": "sync", "result": [
{"name": "foo", "status": "active", "version": "4.2", "developer": "bar", "revision":17, "trymode": true}
,{"name": "dm1", "status": "active", "version": "5", "revision":1, "devmode": true, "confinement": "devmode"}
,{"name": "dm2", "status": "active", "version": "5", "revision":1, "devmode": true, "confinement": "strict"}
,{"name": "cf1", "status": "active", "version": "6", "revision":2, "confinement": "devmode"}
]}`)
		default:
			c.Fatalf("expected to get 1 requests, now on %d", n+1)
		}

		n++
	})
	rest, err := snap.Parser().ParseArgs([]string{"list"})
	c.Assert(err, check.IsNil)
	c.Assert(rest, check.DeepEquals, []string{})
	c.Check(s.Stdout(), check.Matches, `(?ms)^Name +Version +Rev +Developer +Notes$`)
	c.Check(s.Stdout(), check.Matches, `(?ms).*^foo +4.2 +17 +bar +try$`)
	c.Check(s.Stdout(), check.Matches, `(?ms).*^dm1 +.* +devmode$`)
	c.Check(s.Stdout(), check.Matches, `(?ms).*^dm2 +.* +devmode$`)
	c.Check(s.Stdout(), check.Matches, `(?ms).*^cf1 +.* +jailmode$`)
	c.Check(s.Stderr(), check.Equals, "")
}
Exemple #10
0
func (s *SnapKeysSuite) TestDeleteKeyRequiresName(c *C) {
	_, err := snap.Parser().ParseArgs([]string{"delete-key"})
	c.Assert(err, NotNil)
	c.Check(err.Error(), Equals, "the required argument `<key-name>` was not provided")
	c.Check(s.Stdout(), Equals, "")
	c.Check(s.Stderr(), Equals, "")
}
Exemple #11
0
func (s *BuySnapSuite) TestBuyHelp(c *check.C) {
	_, err := snap.Parser().ParseArgs([]string{"buy"})
	c.Assert(err, check.NotNil)
	c.Check(err.Error(), check.Equals, "the required argument `<snap>` was not provided")
	c.Check(s.Stdout(), check.Equals, "")
	c.Check(s.Stderr(), check.Equals, "")
}
Exemple #12
0
func (s *SnapSignBuildSuite) TestSignBuildWorksDevelGrade(c *C) {
	snapFilename := "foo_1_amd64.snap"
	snapContent := []byte("sample")
	_err := ioutil.WriteFile(snapFilename, snapContent, 0644)
	c.Assert(_err, IsNil)
	defer os.Remove(snapFilename)

	tempdir := c.MkDir()
	for _, fileName := range []string{"pubring.gpg", "secring.gpg", "trustdb.gpg"} {
		data, err := ioutil.ReadFile(filepath.Join("test-data", fileName))
		c.Assert(err, IsNil)
		err = ioutil.WriteFile(filepath.Join(tempdir, fileName), data, 0644)
		c.Assert(err, IsNil)
	}
	os.Setenv("SNAP_GNUPG_HOME", tempdir)
	defer os.Unsetenv("SNAP_GNUPG_HOME")

	_, err := snap.Parser().ParseArgs([]string{"sign-build", snapFilename, "--developer-id", "dev-id1", "--snap-id", "snap-id-1", "--grade", "devel"})
	c.Assert(err, IsNil)
	assertion, err := asserts.Decode([]byte(s.Stdout()))
	c.Assert(err, IsNil)
	c.Check(assertion.Type(), Equals, asserts.SnapBuildType)
	c.Check(assertion.HeaderString("grade"), Equals, "devel")

	// check for valid signature ?!
	c.Check(s.Stderr(), Equals, "")
}
Exemple #13
0
func (s *SnapOpSuite) runTryTest(c *check.C, devmode bool) {
	// pass relative path to cmd
	tryDir := "some-dir"

	s.srv.checker = func(r *http.Request) {
		// ensure the client always sends the absolute path
		fullTryDir, err := filepath.Abs(tryDir)
		c.Assert(err, check.IsNil)

		c.Check(r.URL.Path, check.Equals, "/v2/snaps")
		postData, err := ioutil.ReadAll(r.Body)
		c.Assert(err, check.IsNil)
		c.Assert(string(postData), check.Matches, "(?s).*Content-Disposition: form-data; name=\"action\"\r\n\r\ntry\r\n.*")
		c.Assert(string(postData), check.Matches, fmt.Sprintf("(?s).*Content-Disposition: form-data; name=\"snap-path\"\r\n\r\n%s\r\n.*", regexp.QuoteMeta(fullTryDir)))
		c.Assert(string(postData), check.Matches, fmt.Sprintf("(?s).*Content-Disposition: form-data; name=\"devmode\"\r\n\r\n%s\r\n.*", strconv.FormatBool(devmode)))
	}

	s.RedirectClientToTestServer(s.srv.handle)

	cmd := []string{"try", tryDir}
	if devmode {
		cmd = append(cmd, "--devmode")
	}

	rest, err := snap.Parser().ParseArgs(cmd)
	c.Assert(err, check.IsNil)
	c.Assert(rest, check.DeepEquals, []string{})
	c.Check(s.Stdout(), check.Matches, fmt.Sprintf(`(?sm).*foo 1.0 mounted from .*%s`, tryDir))
	c.Check(s.Stderr(), check.Equals, "")
	// ensure that the fake server api was actually hit
	c.Check(s.srv.n, check.Equals, s.srv.total)
}
func (s *SnapSuite) TestAutoImportAssertsNotImportedFromLoop(c *C) {
	restore := release.MockOnClassic(false)
	defer restore()

	fakeAssertData := []byte("bad-assertion")

	s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) {
		// assertion is ignored, nothing is posted to this endpoint
		panic("not reached")
	})

	fakeAssertsFn := filepath.Join(c.MkDir(), "auto-import.assert")
	err := ioutil.WriteFile(fakeAssertsFn, fakeAssertData, 0644)
	c.Assert(err, IsNil)

	mockMountInfoFmtWithLoop := `
24 0 8:18 / %s rw,relatime shared:1 - squashfs /dev/loop1 rw,errors=remount-ro,data=ordered`
	content := fmt.Sprintf(mockMountInfoFmtWithLoop, 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, "")
	c.Check(s.Stderr(), Equals, "")
}
Exemple #15
0
func (s *SnapKeysSuite) TestExportKeyAccount(c *C) {
	rootPrivKey, _ := assertstest.GenerateKey(1024)
	storePrivKey, _ := assertstest.GenerateKey(752)
	storeSigning := assertstest.NewStoreStack("canonical", rootPrivKey, storePrivKey)
	manager := asserts.NewGPGKeypairManager()
	assertstest.NewAccount(storeSigning, "developer1", nil, "")
	rest, err := snap.Parser().ParseArgs([]string{"export-key", "another", "--account=developer1"})
	c.Assert(err, IsNil)
	c.Assert(rest, DeepEquals, []string{})
	assertion, err := asserts.Decode(s.stdout.Bytes())
	c.Assert(err, IsNil)
	c.Check(assertion.Type(), Equals, asserts.AccountKeyRequestType)
	c.Check(assertion.Revision(), Equals, 0)
	c.Check(assertion.HeaderString("account-id"), Equals, "developer1")
	c.Check(assertion.HeaderString("name"), Equals, "another")
	c.Check(assertion.HeaderString("public-key-sha3-384"), Equals, "DVQf1U4mIsuzlQqAebjjTPYtYJ-GEhJy0REuj3zvpQYTZ7EJj7adBxIXLJ7Vmk3L")
	since, err := time.Parse(time.RFC3339, assertion.HeaderString("since"))
	c.Assert(err, IsNil)
	zone, offset := since.Zone()
	c.Check(zone, Equals, "UTC")
	c.Check(offset, Equals, 0)
	c.Check(s.Stderr(), Equals, "")
	privKey, err := manager.Get(assertion.HeaderString("public-key-sha3-384"))
	c.Assert(err, IsNil)
	err = asserts.SignatureCheck(assertion, privKey.PublicKey())
	c.Assert(err, IsNil)
}
Exemple #16
0
func (s *SnapSuite) TestKnownRemote(c *check.C) {
	var server *httptest.Server

	restorer := snap.MockStoreNew(func(cfg *store.Config, auth auth.AuthContext) *store.Store {
		if cfg == nil {
			cfg = store.DefaultConfig()
		}
		serverURL, err := url.Parse(server.URL + "/assertions/")
		c.Assert(err, check.IsNil)
		cfg.AssertionsURI = serverURL
		return store.New(cfg, auth)
	})
	defer restorer()

	n := 0
	server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch n {
		case 0:
			c.Check(r.Method, check.Equals, "GET")
			c.Check(r.URL.Path, check.Equals, "/assertions/model/16/canonical/pi99")
			fmt.Fprintln(w, mockModelAssertion)
		default:
			c.Fatalf("expected to get 1 requests, now on %d", n+1)
		}

		n++
	}))

	rest, err := snap.Parser().ParseArgs([]string{"known", "--remote", "model", "series=16", "brand-id=canonical", "model=pi99"})
	c.Assert(err, check.IsNil)
	c.Assert(rest, check.DeepEquals, []string{})
	c.Check(s.Stdout(), check.Equals, mockModelAssertion)
	c.Check(s.Stderr(), check.Equals, "")
}
Exemple #17
0
func (s *SnapKeysSuite) TestExportKeyNonexistent(c *C) {
	_, err := snap.Parser().ParseArgs([]string{"export-key", "nonexistent"})
	c.Assert(err, NotNil)
	c.Check(err.Error(), Equals, "cannot find key named \"nonexistent\" in GPG keyring")
	c.Check(s.Stdout(), Equals, "")
	c.Check(s.Stderr(), Equals, "")
}
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")
}
Exemple #19
0
func (s *SnapSignBuildSuite) TestSignBuildMissingSnap(c *C) {
	_, err := snap.Parser().ParseArgs([]string{"sign-build", "foo_1_amd64.snap", "--developer-id", "dev-id1", "--snap-id", "snap-id-1"})
	c.Assert(err, NotNil)
	c.Check(err.Error(), Equals, "cannot compute snap \"foo_1_amd64.snap\" digest: open foo_1_amd64.snap: no such file or directory")
	c.Check(s.Stdout(), Equals, "")
	c.Check(s.Stderr(), Equals, "")
}
Exemple #20
0
func (s *SnapSignBuildSuite) TestSignBuildWorks(c *C) {
	snapFilename := "foo_1_amd64.snap"
	snapContent := []byte("sample")
	_err := ioutil.WriteFile(snapFilename, snapContent, 0644)
	c.Assert(_err, IsNil)
	defer os.Remove(snapFilename)

	tempdir := c.MkDir()
	for _, fileName := range []string{"pubring.gpg", "secring.gpg", "trustdb.gpg"} {
		data, err := ioutil.ReadFile(filepath.Join("test-data", fileName))
		c.Assert(err, IsNil)
		err = ioutil.WriteFile(filepath.Join(tempdir, fileName), data, 0644)
		c.Assert(err, IsNil)
	}
	os.Setenv("SNAP_GNUPG_HOME", tempdir)
	defer os.Unsetenv("SNAP_GNUPG_HOME")

	_, err := snap.Parser().ParseArgs([]string{"sign-build", snapFilename, "--developer-id", "dev-id1", "--snap-id", "snap-id-1"})
	c.Assert(err, IsNil)

	assertion, err := asserts.Decode([]byte(s.Stdout()))
	c.Assert(err, IsNil)
	c.Check(assertion.Type(), Equals, asserts.SnapBuildType)
	c.Check(assertion.Revision(), Equals, 0)
	c.Check(assertion.HeaderString("authority-id"), Equals, "dev-id1")
	c.Check(assertion.HeaderString("developer-id"), Equals, "dev-id1")
	c.Check(assertion.HeaderString("grade"), Equals, "stable")
	c.Check(assertion.HeaderString("snap-id"), Equals, "snap-id-1")
	c.Check(assertion.HeaderString("snap-size"), Equals, fmt.Sprintf("%d", len(snapContent)))
	c.Check(assertion.HeaderString("snap-sha3-384"), Equals, "jyP7dUgb8HiRNd1SdYPp_il-YNrl6P6PgNAe-j6_7WytjKslENhMD3Of5XBU5bQK")

	// check for valid signature ?!
	c.Check(s.Stderr(), Equals, "")
}
Exemple #21
0
func (s *SnapSignBuildSuite) TestSignBuildMandatoryFlags(c *C) {
	_, err := snap.Parser().ParseArgs([]string{"sign-build", "foo_1_amd64.snap"})
	c.Assert(err, NotNil)
	c.Check(err.Error(), Equals, "the required flags `--developer-id' and `--snap-id' were not specified")
	c.Check(s.Stdout(), Equals, "")
	c.Check(s.Stderr(), Equals, "")
}
Exemple #22
0
func (s *BuySnapSuite) TestBuySnapFailsOutOfRangeMethodID(c *check.C) {
	mockServer := &buyTestMockSnapServer{
		ExpectedMethods: expectedMethods{
			"GET": &expectedMethod{
				"/v2/find": buySnapFindURL(c),
				"/v2/buy/methods": &expectedURL{
					Body: buyMethodsSelectPaymentMethodJson,
				},
			},
		},
		Checker: c,
	}
	defer mockServer.checkCounts()
	s.RedirectClientToTestServer(mockServer.serveHttp)

	// Payment method selection out of range
	fmt.Fprint(s.stdin, "5\n")

	rest, err := snap.Parser().ParseArgs([]string{"buy", "hello"})
	c.Assert(err, check.NotNil)
	c.Check(err.Error(), check.Equals, `cannot buy snap "hello": unknown payment method selection 5`)
	c.Check(rest, check.DeepEquals, []string{"hello"})
	c.Check(s.Stdout(), check.Equals, `  Selection  Description
  1          **** **** **** 1111 (exp 23/2020)
  2          **** **** **** 2222 (exp 23/2025)
  3          **** **** **** 3333 (exp 30/2027)
Type a number to select payment method: `)
	c.Check(s.Stderr(), check.Equals, "")
}
Exemple #23
0
func (s *SnapSuite) TestRefreshList(c *check.C) {
	n := 0
	s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) {
		switch n {
		case 0:
			c.Check(r.Method, check.Equals, "GET")
			c.Check(r.URL.Path, check.Equals, "/v2/find")
			c.Check(r.URL.Query().Get("select"), check.Equals, "refresh")
			fmt.Fprintln(w, `{"type": "sync", "result": [{"name": "foo", "status": "active", "version": "4.2update1", "developer": "bar", "revision":17,"summary":"some summary"}]}`)
		default:
			c.Fatalf("expected to get 1 requests, now on %d", n+1)
		}

		n++
	})
	rest, err := snap.Parser().ParseArgs([]string{"refresh", "--list"})
	c.Assert(err, check.IsNil)
	c.Assert(rest, check.DeepEquals, []string{})
	c.Check(s.Stdout(), check.Matches, `Name +Version +Rev +Developer +Notes
foo +4.2update1 +17 +bar +-.*
`)
	c.Check(s.Stderr(), check.Equals, "")
	// ensure that the fake server api was actually hit
	c.Check(n, check.Equals, 1)
}
Exemple #24
0
func (s *SnapSuite) TestInvalidParameters(c *check.C) {
	invalidParameters := []string{"run", "--hook=apply-config", "--command=command-name", "snap-name"}
	_, err := snaprun.Parser().ParseArgs(invalidParameters)
	c.Check(err, check.ErrorMatches, ".*cannot use --hook and --command together.*")

	invalidParameters = []string{"run", "-r=1", "--command=command-name", "snap-name"}
	_, err = snaprun.Parser().ParseArgs(invalidParameters)
	c.Check(err, check.ErrorMatches, ".*-r can only be used with --hook.*")

	invalidParameters = []string{"run", "-r=1", "snap-name"}
	_, err = snaprun.Parser().ParseArgs(invalidParameters)
	c.Check(err, check.ErrorMatches, ".*-r can only be used with --hook.*")

	invalidParameters = []string{"run", "--hook=apply-config", "foo", "bar", "snap-name"}
	_, err = snaprun.Parser().ParseArgs(invalidParameters)
	c.Check(err, check.ErrorMatches, ".*too many arguments for hook \"apply-config\": bar.*")
}
func (s *SnapSuite) TestCreateUser(c *check.C) {
	n := 0
	s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) {
		switch n {
		case 0, 1:
			c.Check(r.Method, check.Equals, "POST")
			c.Check(r.URL.Path, check.Equals, "/v2/create-user")
			var body map[string]interface{}
			dec := json.NewDecoder(r.Body)
			err := dec.Decode(&body)
			c.Assert(err, check.IsNil)
			c.Check(body, check.DeepEquals, map[string]interface{}{
				"email":  "*****@*****.**",
				"sudoer": false,
			})
			fmt.Fprintln(w, `{"type": "sync", "result": {"username": "******", "ssh-key-count": 1}}`)
		default:
			c.Fatalf("expected to get 2 requests, now on %d", n+1)
		}

		n++
	})

	rest, err := snap.Parser().ParseArgs([]string{"create-user", "*****@*****.**"})
	c.Assert(err, check.IsNil)
	c.Check(rest, check.DeepEquals, []string{})
	c.Check(n, check.Equals, 1)
	c.Assert(s.Stdout(), check.Equals, `Created user "karl" and imported SSH keys.`+"\n")
	c.Assert(s.Stderr(), check.Equals, "")

	s.stdout.Reset()

	expectedResponse := &client.CreateUserResult{
		Username:    "******",
		SSHKeyCount: 1,
	}
	actualResponse := &client.CreateUserResult{}

	rest, err = snap.Parser().ParseArgs([]string{"create-user", "--json", "*****@*****.**"})
	c.Assert(err, check.IsNil)
	c.Check(rest, check.DeepEquals, []string{})
	c.Check(n, check.Equals, 2)
	json.Unmarshal(s.stdout.Bytes(), actualResponse)
	c.Assert(actualResponse, check.DeepEquals, expectedResponse)
	c.Assert(s.Stderr(), check.Equals, "")
}
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)
}
Exemple #27
0
func (s *BuySnapSuite) TestBuySnapSelectPaymentMethodWithDefault(c *check.C) {
	mockServer := &buyTestMockSnapServer{
		ExpectedMethods: expectedMethods{
			"GET": &expectedMethod{
				"/v2/find": buySnapFindURL(c),
				"/v2/buy/methods": &expectedURL{
					Body: buyMethodsSelectPaymentMethodWithDefaultJson,
				},
			},
			"POST": &expectedMethod{
				"/v2/buy": &expectedURL{
					Body: buySnapJson,
					Checker: func(r *http.Request) {
						var postData struct {
							SnapID    string  `json:"snap-id"`
							SnapName  string  `json:"snap-name"`
							Price     float64 `json:"price"`
							Currency  string  `json:"currency"`
							MethodID  int     `json:"method-id"`
							BackendID string  `json:"backend-id"`
						}
						decoder := json.NewDecoder(r.Body)
						err := decoder.Decode(&postData)
						c.Assert(err, check.IsNil)

						c.Check(postData.SnapID, check.Equals, "mVyGrEwiqSi5PugCwyH7WgpoQLemtTd6")
						c.Check(postData.SnapName, check.Equals, "hello")
						c.Check(postData.Price, check.Equals, 2.99)
						c.Check(postData.Currency, check.Equals, "GBP")

						// Confirm the correct details for card #1
						c.Check(postData.MethodID, check.Equals, 123)
						c.Check(postData.BackendID, check.Equals, "credit_card")
					},
				},
			},
		},
		Checker: c,
	}
	defer mockServer.checkCounts()
	s.RedirectClientToTestServer(mockServer.serveHttp)

	// Select the default card
	fmt.Fprint(s.stdin, "\n")
	// Confirm "yes" to the purchase
	fmt.Fprint(s.stdin, "\n")

	rest, err := snap.Parser().ParseArgs([]string{"buy", "hello"})
	c.Check(err, check.IsNil)
	c.Check(rest, check.DeepEquals, []string{})
	c.Check(s.Stdout(), check.Equals, `   Selection  Description
*  1          **** **** **** 1111 (exp 23/2020)
   2          **** **** **** 2222 (exp 23/2025)
   3          **** **** **** 3333 (exp 30/2027)
Press <enter> to use your default[*], or type a number to select payment method: Do you want to buy "hello" from "canonical" for 2.99GBP? (Y/n): hello bought
`)
	c.Check(s.Stderr(), check.Equals, "")
}
func (s *SnapSuite) TestAutoImportAssertsHappy(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)
		}

	})

	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 - ext4 /dev/sdb2 rw,errors=remount-ro,data=ordered`
	content := fmt.Sprintf(mockMountInfoFmt, filepath.Dir(fakeAssertsFn))
	restore = snap.MockMountInfoPath(makeMockMountInfo(c, content))
	defer restore()

	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)
}
Exemple #29
0
func (s *SnapKeysSuite) TestKeysJSONEmpty(c *C) {
	err := os.RemoveAll(os.Getenv("SNAP_GNUPG_HOME"))
	c.Assert(err, IsNil)
	rest, err := snap.Parser().ParseArgs([]string{"keys", "--json"})
	c.Assert(err, IsNil)
	c.Assert(rest, DeepEquals, []string{})
	c.Check(s.Stdout(), Equals, "[]\n")
	c.Check(s.Stderr(), Equals, "")
}
Exemple #30
0
func (s *SnapKeysSuite) TestExportKeyNonDefault(c *C) {
	rest, err := snap.Parser().ParseArgs([]string{"export-key", "another"})
	c.Assert(err, IsNil)
	c.Assert(rest, DeepEquals, []string{})
	pubKey, err := asserts.DecodePublicKey(s.stdout.Bytes())
	c.Assert(err, IsNil)
	c.Check(pubKey.ID(), Equals, "DVQf1U4mIsuzlQqAebjjTPYtYJ-GEhJy0REuj3zvpQYTZ7EJj7adBxIXLJ7Vmk3L")
	c.Check(s.Stderr(), Equals, "")
}