Example #1
0
func (s *modelManagerSuite) TestListModelsDenied(c *gc.C) {
	user := names.NewUserTag("external@remote")
	s.setAPIUser(c, user)
	other := names.NewUserTag("other@remote")
	_, err := s.modelmanager.ListModels(params.Entity{other.String()})
	c.Assert(err, gc.ErrorMatches, "permission denied")
}
Example #2
0
func (s *modelInfoSuite) SetUpTest(c *gc.C) {
	s.BaseSuite.SetUpTest(c)
	s.authorizer = apiservertesting.FakeAuthorizer{
		Tag: names.NewUserTag("admin@local"),
	}
	s.st = &mockState{
		uuid: coretesting.ModelTag.Id(),
	}
	s.st.model = &mockModel{
		owner: names.NewUserTag("bob@local"),
		cfg:   coretesting.ModelConfig(c),
		life:  state.Dying,
		status: status.StatusInfo{
			Status: status.StatusDestroying,
			Since:  &time.Time{},
		},
		users: []*mockModelUser{{
			userName: "******",
			access:   state.ModelAdminAccess,
		}, {
			userName:    "******",
			displayName: "Bob",
			access:      state.ModelReadAccess,
		}, {
			userName:    "******",
			displayName: "Charlotte",
			access:      state.ModelReadAccess,
		}},
	}
	var err error
	s.modelmanager, err = modelmanager.NewModelManagerAPI(s.st, &s.authorizer)
	c.Assert(err, jc.ErrorIsNil)
}
Example #3
0
func (s *Suite) TestMigration(c *gc.C) {
	masterClient := newStubMasterClient(s.stub)
	w := migrationmaster.New(masterClient)

	// Trigger migration.
	masterClient.watcher.changes <- migration.TargetInfo{
		ControllerTag: names.NewModelTag("uuid"),
		Addrs:         []string{"1.2.3.4:5"},
		CACert:        "cert",
		AuthTag:       names.NewUserTag("admin"),
		Password:      "******",
	}

	// This error is temporary while migrationmaster is a WIP.
	runWorkerAndWait(c, w, "migration seen and aborted")

	// Observe that the migration was seen, the model exported, an API
	// connection to the target controller was made, the model was
	// imported and then the migration aborted.
	s.stub.CheckCalls(c, []jujutesting.StubCall{
		{"masterClient.Watch", nil},
		{"masterClient.Export", nil},
		{"apiOpen", []interface{}{&api.Info{
			Addrs:    []string{"1.2.3.4:5"},
			CACert:   "cert",
			Tag:      names.NewUserTag("admin"),
			Password: "******",
		}, api.DefaultDialOpts()}},
		{"APICall:MigrationTarget.Import",
			[]interface{}{params.SerializedModel{Bytes: fakeSerializedModel}}},
		{"masterClient.SetPhase", []interface{}{migration.ABORT}},
		{"Connection.Close", nil},
	})
}
Example #4
0
func (s *ModelMigrationSuite) SetUpTest(c *gc.C) {
	s.ConnSuite.SetUpTest(c)
	s.clock = coretesting.NewClock(time.Now().Truncate(time.Second))
	s.PatchValue(&state.GetClock, func() clock.Clock {
		return s.clock
	})

	// Create a hosted model to migrate.
	s.State2 = s.Factory.MakeModel(c, nil)
	s.AddCleanup(func(*gc.C) { s.State2.Close() })

	targetControllerTag := names.NewModelTag(utils.MustNewUUID().String())

	// Plausible migration arguments to test with.
	s.stdSpec = state.ModelMigrationSpec{
		InitiatedBy: names.NewUserTag("admin"),
		TargetInfo: migration.TargetInfo{
			ControllerTag: targetControllerTag,
			Addrs:         []string{"1.2.3.4:5555", "4.3.2.1:6666"},
			CACert:        "cert",
			AuthTag:       names.NewUserTag("user"),
			Password:      "******",
		},
	}
}
Example #5
0
func (s *migrationWatcherSuite) TestWatch(c *gc.C) {
	// Create a state server
	m, password := s.Factory.MakeMachineReturningPassword(c, &factory.MachineParams{
		Jobs:  []state.MachineJob{state.JobManageModel},
		Nonce: "noncey",
	})

	// Create a model to migrate.
	hostedState := s.Factory.MakeModel(c, nil)

	// Connect as a state server to the hosted environment.
	apiInfo := s.APIInfo(c)
	apiInfo.Tag = m.Tag()
	apiInfo.Password = password
	apiInfo.ModelTag = hostedState.ModelTag()
	apiInfo.Nonce = "noncey"

	apiConn, err := api.Open(apiInfo, api.DialOpts{})
	c.Assert(err, jc.ErrorIsNil)
	defer apiConn.Close()

	// Start watching for a migration.
	client := migrationmaster.NewClient(apiConn)
	w, err := client.Watch()
	c.Assert(err, jc.ErrorIsNil)
	defer func() {
		c.Assert(worker.Stop(w), jc.ErrorIsNil)
	}()

	// Should be no initial events.
	select {
	case _, ok := <-w.Changes():
		c.Fatalf("watcher sent unexpected change: (_, %v)", ok)
	case <-time.After(coretesting.ShortWait):
	}

	// Now create a migration.
	targetInfo := migration.TargetInfo{
		ControllerTag: names.NewModelTag(utils.MustNewUUID().String()),
		Addrs:         []string{"1.2.3.4:5"},
		CACert:        "trust me I'm an authority",
		AuthTag:       names.NewUserTag("dog"),
		Password:      "******",
	}
	_, err = hostedState.CreateModelMigration(state.ModelMigrationSpec{
		InitiatedBy: names.NewUserTag("someone"),
		TargetInfo:  targetInfo,
	})
	c.Assert(err, jc.ErrorIsNil)

	// Event with correct target details should be emitted.
	select {
	case reportedTargetInfo, ok := <-w.Changes():
		c.Assert(ok, jc.IsTrue)
		c.Assert(reportedTargetInfo, jc.DeepEquals, targetInfo)
	case <-time.After(coretesting.LongWait):
		c.Fatalf("watcher didn't emit an event")
	}
}
Example #6
0
func (s *internalEnvUserSuite) TestCreateEnvUserOpAndDoc(c *gc.C) {
	tag := names.NewUserTag("UserName")
	op, doc := createEnvUserOpAndDoc("ignored", tag, names.NewUserTag("ignored"), "ignored")

	c.Assert(op.Id, gc.Equals, "username@local")
	c.Assert(doc.ID, gc.Equals, "username@local")
	c.Assert(doc.UserName, gc.Equals, "UserName@local")
}
Example #7
0
func (s *unshareSuite) TestPassesValues(c *gc.C) {
	sam := names.NewUserTag("sam")
	ralph := names.NewUserTag("ralph")

	_, err := s.run(c, "sam", "ralph")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(s.fake.removeUsers, jc.DeepEquals, []names.UserTag{sam, ralph})
}
Example #8
0
func (s *modelManagerSuite) TestListModelsForSelfLocalUser(c *gc.C) {
	// When the user's credentials cache stores the simple name, but the
	// api server converts it to a fully qualified name.
	user := names.NewUserTag("local-user")
	s.setAPIUser(c, names.NewUserTag("local-user@local"))
	result, err := s.modelmanager.ListModels(params.Entity{user.String()})
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(result.UserModels, gc.HasLen, 0)
}
Example #9
0
func (s *modelManagerSuite) TestGrantToModelNoAccess(c *gc.C) {
	apiUser := names.NewUserTag("bob@remote")
	s.setAPIUser(c, apiUser)

	st := s.Factory.MakeModel(c, nil)
	defer st.Close()

	other := names.NewUserTag("other@remote")
	err := s.grant(c, other, params.ModelReadAccess, st.ModelTag())
	c.Assert(err, gc.ErrorMatches, "permission denied")
}
Example #10
0
func (s *unshareSuite) TestInit(c *gc.C) {
	wrappedCommand, unshareCmd := model.NewUnshareCommandForTest(s.fake)
	err := testing.InitCommand(wrappedCommand, []string{})
	c.Assert(err, gc.ErrorMatches, "no users specified")

	err = testing.InitCommand(wrappedCommand, []string{"not valid/0"})
	c.Assert(err, gc.ErrorMatches, `invalid username: "******"`)

	err = testing.InitCommand(wrappedCommand, []string{"bob@local", "sam"})
	c.Assert(err, jc.ErrorIsNil)

	c.Assert(unshareCmd.Users[0], gc.Equals, names.NewUserTag("bob@local"))
	c.Assert(unshareCmd.Users[1], gc.Equals, names.NewUserTag("sam"))
}
Example #11
0
func (s *unshareSuite) TestInit(c *gc.C) {
	unshareCmd := &environment.UnshareCommand{}
	err := testing.InitCommand(unshareCmd, []string{})
	c.Assert(err, gc.ErrorMatches, "no users specified")

	err = testing.InitCommand(unshareCmd, []string{"not valid/0"})
	c.Assert(err, gc.ErrorMatches, `invalid username: "******"`)

	err = testing.InitCommand(unshareCmd, []string{"bob@local", "sam"})
	c.Assert(err, jc.ErrorIsNil)

	c.Assert(unshareCmd.Users[0], gc.Equals, names.NewUserTag("bob@local"))
	c.Assert(unshareCmd.Users[1], gc.Equals, names.NewUserTag("sam"))
}
Example #12
0
func (s *modelManagerSuite) TestGrantToModelReadAccess(c *gc.C) {
	apiUser := names.NewUserTag("bob@remote")
	s.setAPIUser(c, apiUser)

	st := s.Factory.MakeModel(c, nil)
	defer st.Close()
	stFactory := factory.NewFactory(st)
	stFactory.MakeModelUser(c, &factory.ModelUserParams{
		User: apiUser.Canonical(), Access: state.ModelReadAccess})

	other := names.NewUserTag("other@remote")
	err := s.grant(c, other, params.ModelReadAccess, st.ModelTag())
	c.Assert(err, gc.ErrorMatches, "permission denied")
}
Example #13
0
func (s *userManagerSuite) TestUserInfoUserExists(c *gc.C) {
	foobar := "foobar"
	fooTag := names.NewUserTag(foobar)
	user := s.Factory.MakeUser(factory.UserParams{Username: foobar, DisplayName: "Foo Bar"})

	args := params.Entities{
		Entities: []params.Entity{{Tag: fooTag.String()}},
	}
	results, err := s.usermanager.UserInfo(args)
	c.Assert(err, gc.IsNil)
	expected := params.UserInfoResults{
		Results: []params.UserInfoResult{
			{
				Result: &params.UserInfo{
					Username:       "******",
					DisplayName:    "Foo Bar",
					CreatedBy:      "admin",
					DateCreated:    user.DateCreated(),
					LastConnection: user.LastConnection(),
				},
			},
		},
	}

	c.Assert(results, gc.DeepEquals, expected)
}
Example #14
0
// MakeModelUser will create a modelUser with values defined by the params. For
// attributes of ModelUserParams that are the default empty values, some
// meaningful valid values are used instead. If params is not specified,
// defaults are used.
func (factory *Factory) MakeModelUser(c *gc.C, params *ModelUserParams) *state.ModelUser {
	if params == nil {
		params = &ModelUserParams{}
	}
	if params.User == "" {
		user := factory.MakeUser(c, &UserParams{NoModelUser: true})
		params.User = user.UserTag().Canonical()
	}
	if params.DisplayName == "" {
		params.DisplayName = uniqueString("display name")
	}
	if params.CreatedBy == nil {
		env, err := factory.st.Model()
		c.Assert(err, jc.ErrorIsNil)
		params.CreatedBy = env.Owner()
	}
	createdByUserTag := params.CreatedBy.(names.UserTag)
	modelUser, err := factory.st.AddModelUser(state.ModelUserSpec{
		User:        names.NewUserTag(params.User),
		CreatedBy:   createdByUserTag,
		DisplayName: params.DisplayName,
		ReadOnly:    params.ReadOnly,
	})
	c.Assert(err, jc.ErrorIsNil)
	return modelUser
}
Example #15
0
func (c *UseEnvironmentCommand) findMatchingEnvironment(ctx *cmd.Context, client UseEnvironmentAPI, creds configstore.APICredentials) (base.UserEnvironment, error) {

	var empty base.UserEnvironment

	envs, err := client.ListEnvironments(creds.User)
	if err != nil {
		return empty, errors.Annotate(err, "cannot list environments")
	}

	var owner string
	if c.Owner != "" {
		// The username always contains the provider aspect of the user.
		owner = names.NewUserTag(c.Owner).Username()
	}

	// If we have a UUID, we warn if the owner is different, but accept it.
	// We also trust that the environment UUIDs are unique
	if c.EnvUUID != "" {
		for _, env := range envs {
			if env.UUID == c.EnvUUID {
				if owner != "" && env.Owner != owner {
					ctx.Infof("Specified environment owned by %s, not %s", env.Owner, owner)
				}
				return env, nil
			}
		}
		return empty, errors.NotFoundf("matching environment")
	}

	var matches []base.UserEnvironment
	for _, env := range envs {
		match := env.Name == c.EnvName
		if match && owner != "" {
			match = env.Owner == owner
		}
		if match {
			matches = append(matches, env)
		}
	}

	// If there is only one match, that's the one.
	switch len(matches) {
	case 0:
		return empty, errors.NotFoundf("matching environment")
	case 1:
		return matches[0], nil
	}

	// We are going to return an error, but tell the user what the matches
	// were so they can make an informed decision. We are also going to assume
	// here that the resulting environment list has only one matching name for
	// each user. There are tests creating environments that enforce this.
	ctx.Infof("Multiple environments matched name %q:", c.EnvName)
	for _, env := range matches {
		ctx.Infof("  %s, owned by %s", env.UUID, env.Owner)
	}
	ctx.Infof("Please specify either the environment UUID or the owner to disambiguate.")

	return empty, errors.New("multiple environments matched")
}
Example #16
0
func (s *ModelSuite) TestNewModelNonExistentLocalUser(c *gc.C) {
	cfg, _ := s.createTestEnvConfig(c)
	owner := names.NewUserTag("non-existent@local")

	_, _, err := s.State.NewModel(state.ModelArgs{Config: cfg, Owner: owner})
	c.Assert(err, gc.ErrorMatches, `cannot create model: user "non-existent" not found`)
}
Example #17
0
func (s *apiclientSuite) TestOpenFailsIfUsernameAndUseMacaroon(c *gc.C) {
	info := s.APIInfo(c)
	info.Tag = names.NewUserTag("foobar")
	info.UseMacaroons = true
	_, err := api.Open(info, api.DialOpts{})
	c.Assert(err, gc.ErrorMatches, "open should specifiy UseMacaroons or a username & password. Not both")
}
Example #18
0
func (s *destroyTwoEnvironmentsSuite) SetUpTest(c *gc.C) {
	s.JujuConnSuite.SetUpTest(c)
	_, err := s.State.AddUser("jess", "jess", "", "test")
	c.Assert(err, jc.ErrorIsNil)
	s.otherEnvOwner = names.NewUserTag("jess")
	s.otherState = factory.NewFactory(s.State).MakeEnvironment(c, &factory.EnvParams{
		Owner:   s.otherEnvOwner,
		Prepare: true,
		ConfigAttrs: jujutesting.Attrs{
			"state-server": false,
		},
	})
	s.AddCleanup(func(*gc.C) { s.otherState.Close() })

	// get the client for the other environment
	auth := apiservertesting.FakeAuthorizer{
		Tag:            s.otherEnvOwner,
		EnvironManager: false,
	}
	s.otherEnvClient, err = client.NewClient(s.otherState, common.NewResources(), auth)
	c.Assert(err, jc.ErrorIsNil)

	s.metricSender = &testMetricSender{}
	s.PatchValue(common.SendMetrics, s.metricSender.SendMetrics)
}
Example #19
0
func (s *modelManagerSuite) TestListModelsForSelf(c *gc.C) {
	user := names.NewUserTag("external@remote")
	s.setAPIUser(c, user)
	result, err := s.modelmanager.ListModels(params.Entity{user.String()})
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(result.UserModels, gc.HasLen, 0)
}
Example #20
0
File: api.go Project: kapilt/juju
// apiInfoConnect looks for endpoint on the given environment and
// tries to connect to it, sending the result on the returned channel.
func apiInfoConnect(store configstore.Storage, info configstore.EnvironInfo, apiOpen apiOpenFunc, stop <-chan struct{}) (apiState, error) {
	endpoint := info.APIEndpoint()
	if info == nil || len(endpoint.Addresses) == 0 {
		return nil, &infoConnectError{fmt.Errorf("no cached addresses")}
	}
	logger.Infof("connecting to API addresses: %v", endpoint.Addresses)
	var environTag names.Tag
	if endpoint.EnvironUUID != "" {
		// Note: we should be validating that EnvironUUID contains a
		// valid UUID.
		environTag = names.NewEnvironTag(endpoint.EnvironUUID)
	}
	username := info.APICredentials().User
	if username == "" {
		username = "******"
	}
	apiInfo := &api.Info{
		Addrs:      endpoint.Addresses,
		CACert:     endpoint.CACert,
		Tag:        names.NewUserTag(username),
		Password:   info.APICredentials().Password,
		EnvironTag: environTag,
	}
	st, err := apiOpen(apiInfo, api.DefaultDialOpts())
	if err != nil {
		return nil, &infoConnectError{err}
	}
	return st, nil
}
Example #21
0
func (s *clientSuite) TestUnshareEnvironmentMissingUser(c *gc.C) {
	client := s.APIState.Client()
	user := names.NewUserTag("bob@local")
	cleanup := api.PatchClientFacadeCall(client,
		func(request string, paramsIn interface{}, response interface{}) error {
			if users, ok := paramsIn.(params.ModifyEnvironUsers); ok {
				c.Assert(users.Changes, gc.HasLen, 1)
				c.Logf(string(users.Changes[0].Action), gc.Equals, string(params.RemoveEnvUser))
				c.Logf(users.Changes[0].UserTag, gc.Equals, user.String())
			} else {
				c.Fatalf("wrong input structure")
			}
			if result, ok := response.(*params.ErrorResults); ok {
				err := &params.Error{
					Message: "error message",
					Code:    params.CodeNotFound,
				}
				*result = params.ErrorResults{Results: []params.ErrorResult{{Error: err}}}
			} else {
				c.Fatalf("wrong input structure")
			}
			return nil
		},
	)
	defer cleanup()

	err := client.UnshareEnvironment(user)
	c.Assert(err, jc.ErrorIsNil)
	logMsg := fmt.Sprintf("WARNING juju.api environment was not previously shared with user %s", user.Username())
	c.Assert(c.GetTestLog(), jc.Contains, logMsg)
}
Example #22
0
func (s *clientSuite) TestUnshareEnvironmentThreeUsers(c *gc.C) {
	client := s.APIState.Client()
	missingUser := s.Factory.MakeEnvUser(c, nil)
	localUser := s.Factory.MakeUser(c, nil)
	newUserTag := names.NewUserTag("foo@bar")
	cleanup := api.PatchClientFacadeCall(client,
		func(request string, paramsIn interface{}, response interface{}) error {
			if users, ok := paramsIn.(params.ModifyEnvironUsers); ok {
				c.Assert(users.Changes, gc.HasLen, 3)
				c.Assert(string(users.Changes[0].Action), gc.Equals, string(params.RemoveEnvUser))
				c.Assert(users.Changes[0].UserTag, gc.Equals, missingUser.UserTag().String())
				c.Assert(string(users.Changes[1].Action), gc.Equals, string(params.RemoveEnvUser))
				c.Assert(users.Changes[1].UserTag, gc.Equals, localUser.UserTag().String())
				c.Assert(string(users.Changes[2].Action), gc.Equals, string(params.RemoveEnvUser))
				c.Assert(users.Changes[2].UserTag, gc.Equals, newUserTag.String())
			} else {
				c.Log("wrong input structure")
				c.Fail()
			}
			if result, ok := response.(*params.ErrorResults); ok {
				err := &params.Error{Message: "error unsharing user"}
				*result = params.ErrorResults{Results: []params.ErrorResult{{Error: err}, {Error: nil}, {Error: nil}}}
			} else {
				c.Log("wrong output structure")
				c.Fail()
			}
			return nil
		},
	)
	defer cleanup()

	err := client.UnshareEnvironment(missingUser.UserTag(), localUser.UserTag(), newUserTag)
	c.Assert(err, gc.ErrorMatches, "error unsharing user")
}
Example #23
0
func (s *systemManagerSuite) TestAllEnvironments(c *gc.C) {
	admin := s.Factory.MakeUser(c, &factory.UserParams{Name: "foobar"})

	s.Factory.MakeEnvironment(c, &factory.EnvParams{
		Name: "owned", Owner: admin.UserTag()}).Close()
	remoteUserTag := names.NewUserTag("user@remote")
	st := s.Factory.MakeEnvironment(c, &factory.EnvParams{
		Name: "user", Owner: remoteUserTag})
	defer st.Close()
	st.AddEnvironmentUser(admin.UserTag(), remoteUserTag, "Foo Bar")

	s.Factory.MakeEnvironment(c, &factory.EnvParams{
		Name: "no-access", Owner: remoteUserTag}).Close()

	response, err := s.systemManager.AllEnvironments()
	c.Assert(err, jc.ErrorIsNil)
	// The results are sorted.
	expected := []string{"dummyenv", "no-access", "owned", "user"}
	var obtained []string
	for _, env := range response.UserEnvironments {
		obtained = append(obtained, env.Name)
		stateEnv, err := s.State.GetEnvironment(names.NewEnvironTag(env.UUID))
		c.Assert(err, jc.ErrorIsNil)
		s.checkEnvironmentMatches(c, env.Environment, stateEnv)
	}
	c.Assert(obtained, jc.DeepEquals, expected)
}
Example #24
0
// ListEnvironments returns the environments that the specified user
// has access to in the current server.  Only that state server owner
// can list environments for any user (at this stage).  Other users
// can only ask about their own environments.
func (c *Client) ListEnvironments(user string) ([]base.UserEnvironment, error) {
	var environments params.UserEnvironmentList
	if !names.IsValidUser(user) {
		return nil, errors.Errorf("invalid user name %q", user)
	}
	entity := params.Entity{names.NewUserTag(user).String()}
	err := c.facade.FacadeCall("ListEnvironments", entity, &environments)
	if err != nil {
		return nil, errors.Trace(err)
	}
	result := make([]base.UserEnvironment, len(environments.UserEnvironments))
	for i, env := range environments.UserEnvironments {
		owner, err := names.ParseUserTag(env.OwnerTag)
		if err != nil {
			return nil, errors.Annotatef(err, "OwnerTag %q at position %d", env.OwnerTag, i)
		}
		result[i] = base.UserEnvironment{
			Name:           env.Name,
			UUID:           env.UUID,
			Owner:          owner.Username(),
			LastConnection: env.LastConnection,
		}
	}
	return result, nil
}
Example #25
0
// MakeUser will create a user with values defined by the params.
// For attributes of UserParams that are the default empty values,
// some meaningful valid values are used instead.
// If params is not specified, defaults are used.
func (factory *Factory) MakeUser(c *gc.C, params *UserParams) *state.User {
	if params == nil {
		params = &UserParams{}
	}
	if params.Name == "" {
		params.Name = uniqueString("username")
	}
	if params.DisplayName == "" {
		params.DisplayName = uniqueString("display name")
	}
	if params.Password == "" {
		params.Password = "******"
	}
	if params.Creator == nil {
		env, err := factory.st.Environment()
		c.Assert(err, jc.ErrorIsNil)
		params.Creator = env.Owner()
	}
	creatorUserTag := params.Creator.(names.UserTag)
	user, err := factory.st.AddUser(
		params.Name, params.DisplayName, params.Password, creatorUserTag.Name())
	c.Assert(err, jc.ErrorIsNil)
	if !params.NoEnvUser {
		_, err := factory.st.AddEnvironmentUser(user.UserTag(), names.NewUserTag(user.CreatedBy()), params.DisplayName)
		c.Assert(err, jc.ErrorIsNil)
	}
	if params.Disabled {
		err := user.Disable()
		c.Assert(err, jc.ErrorIsNil)
	}
	return user
}
Example #26
0
func (s *ImportSuite) TestStreamCharmsTools(c *gc.C) {
	model := description.NewModel(description.ModelArgs{
		Owner: names.NewUserTag("me"),
	})
	model.AddService(description.ServiceArgs{
		Tag:      names.NewServiceTag("magic"),
		CharmURL: "local:trusty/magic",
	})
	model.AddService(description.ServiceArgs{
		Tag:      names.NewServiceTag("magic"),
		CharmURL: "cs:trusty/postgresql-42",
	})

	uploader := &fakeUploader{charms: make(map[string]string)}
	config := migration.UploadBinariesConfig{
		State:            &fakeStateStorage{},
		Model:            model,
		Target:           &fakeAPIConnection{},
		GetCharmUploader: func(api.Connection) migration.CharmUploader { return uploader },
		GetToolsUploader: func(target api.Connection) migration.ToolsUploader { return &noOpUploader{} },
		GetStateStorage:  func(migration.UploadBackend) storage.Storage { return &fakeCharmsStorage{} },
		GetCharmStoragePath: func(_ migration.UploadBackend, u *charm.URL) (string, error) {
			return "/path/for/" + u.String(), nil
		},
	}
	err := migration.UploadBinaries(config)
	c.Assert(err, jc.ErrorIsNil)

	c.Assert(uploader.charms, jc.DeepEquals, map[string]string{
		"local:trusty/magic":      "fake file at /path/for/local:trusty/magic",
		"cs:trusty/postgresql-42": "fake file at /path/for/cs:trusty/postgresql-42",
	})
}
Example #27
0
func (c *UserInfoCommand) Run(ctx *cmd.Context) (err error) {
	client, err := getUserInfoAPI(c)
	if err != nil {
		return err
	}
	defer client.Close()
	username := c.Username
	if username == "" {
		// No username given, get current user
		store, err := configstore.Default()
		if err != nil {
			return err
		}
		info, err := store.ReadInfo(c.EnvName)
		if err != nil {
			return err
		}
		username = info.APICredentials().User
	}
	userTag := names.NewUserTag(username)
	result, err := client.UserInfo(userTag.Id())
	if err != nil {
		return err
	}
	info := UserInfo{
		Username:       result.Result.Username,
		DisplayName:    result.Result.DisplayName,
		DateCreated:    result.Result.DateCreated.String(),
		LastConnection: result.Result.LastConnection.String(),
	}
	if err = c.out.Write(ctx, info); err != nil {
		return err
	}
	return nil
}
Example #28
0
func (s *userManagerSuite) TestBlockEnableUser(c *gc.C) {
	alex := s.Factory.MakeUser(c, &factory.UserParams{Name: "alex"})
	barb := s.Factory.MakeUser(c, &factory.UserParams{Name: "barb", Disabled: true})

	args := params.Entities{
		Entities: []params.Entity{
			{alex.Tag().String()},
			{barb.Tag().String()},
			{names.NewLocalUserTag("ellie").String()},
			{names.NewUserTag("fred@remote").String()},
			{"not-a-tag"},
		}}

	s.BlockAllChanges(c, "TestBlockEnableUser")
	_, err := s.usermanager.EnableUser(args)
	// Check that the call is blocked
	s.AssertBlocked(c, err, "TestBlockEnableUser")

	err = alex.Refresh()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(alex.IsDisabled(), jc.IsFalse)

	err = barb.Refresh()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(barb.IsDisabled(), jc.IsTrue)
}
Example #29
0
func (s *modelManagerSuite) TestNewAPIAcceptsClient(c *gc.C) {
	anAuthoriser := s.authoriser
	anAuthoriser.Tag = names.NewUserTag("external@remote")
	endPoint, err := modelmanager.NewModelManagerAPI(s.State, s.resources, anAuthoriser)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(endPoint, gc.NotNil)
}
Example #30
0
func (s *controllerSuite) TestAllModels(c *gc.C) {
	admin := s.Factory.MakeUser(c, &factory.UserParams{Name: "foobar"})

	s.Factory.MakeModel(c, &factory.ModelParams{
		Name: "owned", Owner: admin.UserTag()}).Close()
	remoteUserTag := names.NewUserTag("user@remote")
	st := s.Factory.MakeModel(c, &factory.ModelParams{
		Name: "user", Owner: remoteUserTag})
	defer st.Close()
	st.AddModelUser(state.ModelUserSpec{
		User:        admin.UserTag(),
		CreatedBy:   remoteUserTag,
		DisplayName: "Foo Bar"})

	s.Factory.MakeModel(c, &factory.ModelParams{
		Name: "no-access", Owner: remoteUserTag}).Close()

	response, err := s.controller.AllModels()
	c.Assert(err, jc.ErrorIsNil)
	// The results are sorted.
	expected := []string{"dummymodel", "no-access", "owned", "user"}
	var obtained []string
	for _, env := range response.UserModels {
		obtained = append(obtained, env.Name)
		stateEnv, err := s.State.GetModel(names.NewModelTag(env.UUID))
		c.Assert(err, jc.ErrorIsNil)
		s.checkEnvironmentMatches(c, env.Model, stateEnv)
	}
	c.Assert(obtained, jc.DeepEquals, expected)
}