func (s *UserSuite) TestUserAddGrantModel(c *gc.C) { sharedModelState := s.Factory.MakeModel(c, &factory.ModelParams{ Name: "amodel", }) defer sharedModelState.Close() ctx, err := s.RunUserCommand(c, "", "add-user", "test", "--models", "amodel") c.Assert(err, jc.ErrorIsNil) c.Assert(testing.Stdout(ctx), jc.HasPrefix, `User "test" added`) user, err := s.State.User(names.NewLocalUserTag("test")) c.Assert(err, jc.ErrorIsNil) c.Assert(user.IsDisabled(), jc.IsFalse) // Check model is shared with expected users. sharedModel, err := sharedModelState.Model() c.Assert(err, jc.ErrorIsNil) users, err := sharedModel.Users() c.Assert(err, jc.ErrorIsNil) var modelUserTags = make([]names.UserTag, len(users)) for i, u := range users { modelUserTags[i] = u.UserTag() } c.Assert(modelUserTags, jc.SameContents, []names.UserTag{ user.Tag().(names.UserTag), names.NewLocalUserTag("admin"), }) }
func (s *userManagerSuite) addUserWithSharedModel(c *gc.C, access params.ModelAccessPermission) { sharedModelState := s.Factory.MakeModel(c, nil) defer sharedModelState.Close() s.assertAddUser(c, access, []string{sharedModelState.ModelTag().String()}) // Check that the model has been shared. sharedModel, err := sharedModelState.Model() c.Assert(err, jc.ErrorIsNil) users, err := sharedModel.Users() c.Assert(err, jc.ErrorIsNil) var modelUserTags = make([]names.UserTag, len(users)) for i, u := range users { modelUserTags[i] = u.UserTag() if u.UserName() == "foobar" { c.Assert(u.ReadOnly(), gc.Equals, access == params.ModelReadAccess) } else if u.UserName() == "admin" { c.Assert(u.ReadOnly(), gc.Equals, false) } } c.Assert(modelUserTags, jc.SameContents, []names.UserTag{ names.NewLocalUserTag("foobar"), names.NewLocalUserTag("admin"), }) }
func (s *userManagerSuite) TestRemoveUser(c *gc.C) { args := usermanager.ModifyUsers{ Changes: []usermanager.ModifyUser{{ Username: "******", DisplayName: "Foo Bar", Password: "******", }}} removeArg := params.Entity{ Tag: "foobar", } removeArgs := params.Entities{Entities: []params.Entity{removeArg}} _, err := s.usermanager.AddUser(args) c.Assert(err, gc.IsNil) user, err := s.State.User(names.NewLocalUserTag("foobar")) c.Assert(user.IsDeactivated(), gc.Equals, false) // The user should be active result, err := s.usermanager.RemoveUser(removeArgs) c.Assert(err, gc.IsNil) c.Assert(result, gc.DeepEquals, params.ErrorResults{Results: []params.ErrorResult{params.ErrorResult{Error: nil}}}) user, err = s.State.User(names.NewLocalUserTag("foobar")) c.Assert(err, gc.IsNil) // Removal makes the user in active c.Assert(user.IsDeactivated(), gc.Equals, true) c.Assert(user.PasswordValid(args.Changes[0].Password), gc.Equals, false) }
func (s *userSuite) TestNewLocalUserTag(c *gc.C) { user := names.NewLocalUserTag("bob") c.Assert(user.Canonical(), gc.Equals, "bob@local") c.Assert(user.Name(), gc.Equals, "bob") c.Assert(user.Domain(), gc.Equals, "local") c.Assert(user.IsLocal(), gc.Equals, true) c.Assert(user.String(), gc.Equals, "user-bob@local") c.Assert(func() { names.NewLocalUserTag("bob@local") }, gc.PanicMatches, `invalid user name "bob@local"`) c.Assert(func() { names.NewLocalUserTag("") }, gc.PanicMatches, `invalid user name ""`) c.Assert(func() { names.NewLocalUserTag("!@#") }, gc.PanicMatches, `invalid user name "!@#"`) }
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) }
func (s *InitializeSuite) TestEnvironConfigWithoutAgentVersion(c *gc.C) { // admin-secret blocks Initialize. good := testing.EnvironConfig(c) attrs := good.AllAttrs() delete(attrs, "agent-version") bad, err := config.New(config.NoDefaults, attrs) c.Assert(err, jc.ErrorIsNil) owner := names.NewLocalUserTag("initialize-admin") _, err = state.Initialize(owner, statetesting.NewMongoInfo(), bad, statetesting.NewDialOpts(), state.Policy(nil)) c.Assert(err, gc.ErrorMatches, "agent-version must always be set in state") st := statetesting.Initialize(c, owner, good, nil) // yay side effects st.Close() s.openState(c, st.EnvironTag()) err = s.State.UpdateEnvironConfig(map[string]interface{}{}, []string{"agent-version"}, nil) c.Assert(err, gc.ErrorMatches, "agent-version must always be set in state") // EnvironConfig remains inviolate. cfg, err := s.State.EnvironConfig() c.Assert(err, jc.ErrorIsNil) c.Assert(cfg.AllAttrs(), gc.DeepEquals, good.AllAttrs()) }
func (s *userManagerSuite) assertAddUser(c *gc.C, access params.ModelAccessPermission, sharedModelTags []string) { sharedModelState := s.Factory.MakeModel(c, nil) defer sharedModelState.Close() args := params.AddUsers{ Users: []params.AddUser{{ Username: "******", DisplayName: "Foo Bar", Password: "******", SharedModelTags: sharedModelTags, ModelAccess: access, }}} result, err := s.usermanager.AddUser(args) // Check that the call is successful c.Assert(err, jc.ErrorIsNil) c.Assert(result.Results, gc.HasLen, 1) foobarTag := names.NewLocalUserTag("foobar") c.Assert(result.Results[0], gc.DeepEquals, params.AddUserResult{ Tag: foobarTag.String()}) // Check that the call results in a new user being created user, err := s.State.User(foobarTag) c.Assert(err, jc.ErrorIsNil) c.Assert(user, gc.NotNil) c.Assert(user.Name(), gc.Equals, "foobar") c.Assert(user.DisplayName(), gc.Equals, "Foo Bar") }
func (s *EnvUserSuite) TestAddEnvironmentNoCreatedByUserFails(c *gc.C) { user := s.Factory.MakeUser(c, &factory.UserParams{Name: "validusername"}) _, err := s.State.AddEnvironmentUser(state.EnvUserSpec{ User: user.UserTag(), CreatedBy: names.NewLocalUserTag("createdby")}) c.Assert(err, gc.ErrorMatches, `createdBy user "createdby" does not exist locally: user "createdby" not found`) }
func (s *ModelUserSuite) TestAddModelNoUserFails(c *gc.C) { createdBy := s.Factory.MakeUser(c, &factory.UserParams{Name: "createdby"}) _, err := s.State.AddModelUser(state.ModelUserSpec{ User: names.NewLocalUserTag("validusername"), CreatedBy: createdBy.UserTag()}) c.Assert(err, gc.ErrorMatches, `user "validusername" does not exist locally: user "validusername" not found`) }
func (s *metricsAdderSuite) TestNewMetricsAdderAPIRefusesNonAgent(c *gc.C) { tests := []struct { tag names.Tag environManager bool expectedError string }{ // TODO(cmars): unit agent should get permission denied when callers are // moved to machine agent. {names.NewUnitTag("mysql/0"), false, ""}, {names.NewLocalUserTag("admin"), true, "permission denied"}, {names.NewMachineTag("0"), false, ""}, {names.NewMachineTag("0"), true, ""}, } for i, test := range tests { c.Logf("test %d", i) anAuthoriser := s.authorizer anAuthoriser.EnvironManager = test.environManager anAuthoriser.Tag = test.tag endPoint, err := metricsadder.NewMetricsAdderAPI(s.State, nil, anAuthoriser) if test.expectedError == "" { c.Assert(err, jc.ErrorIsNil) c.Assert(endPoint, gc.NotNil) } else { c.Assert(err, gc.ErrorMatches, test.expectedError) c.Assert(endPoint, gc.IsNil) } } }
func (s *userManagerSuite) TestAddUserWithSecretKey(c *gc.C) { args := params.AddUsers{ Users: []params.AddUser{{ Username: "******", DisplayName: "Foo Bar", Password: "", // assign secret key }}} result, err := s.usermanager.AddUser(args) // Check that the call is succesful c.Assert(err, jc.ErrorIsNil) c.Assert(result.Results, gc.HasLen, 1) foobarTag := names.NewLocalUserTag("foobar") // Check that the call results in a new user being created user, err := s.State.User(foobarTag) c.Assert(err, jc.ErrorIsNil) c.Assert(user, gc.NotNil) c.Assert(user.Name(), gc.Equals, "foobar") c.Assert(user.DisplayName(), gc.Equals, "Foo Bar") c.Assert(user.SecretKey(), gc.NotNil) c.Assert(user.PasswordValid(""), jc.IsFalse) // Check that the secret key returned by the API matches what // is in state. c.Assert(result.Results[0], gc.DeepEquals, params.AddUserResult{ Tag: foobarTag.String(), SecretKey: user.SecretKey(), }) }
func (s *CloudInitSuite) TestFinishInstanceConfigNonDefault(c *gc.C) { userTag := names.NewLocalUserTag("not-touched") attrs := dummySampleConfig().Merge(testing.Attrs{ "authorized-keys": "we-are-the-keys", "ssl-hostname-verification": false, }) cfg, err := config.New(config.NoDefaults, attrs) c.Assert(err, jc.ErrorIsNil) icfg := &instancecfg.InstanceConfig{ MongoInfo: &mongo.MongoInfo{Tag: userTag}, APIInfo: &api.Info{Tag: userTag}, } err = instancecfg.FinishInstanceConfig(icfg, cfg) c.Assert(err, jc.ErrorIsNil) c.Assert(icfg, jc.DeepEquals, &instancecfg.InstanceConfig{ AuthorizedKeys: "we-are-the-keys", AgentEnvironment: map[string]string{ agent.ProviderType: "dummy", agent.ContainerType: "", }, MongoInfo: &mongo.MongoInfo{Tag: userTag}, APIInfo: &api.Info{Tag: userTag}, DisableSSLHostnameVerification: true, PreferIPv6: true, EnableOSRefreshUpdate: true, EnableOSUpgrade: true, }) }
func (s *userManagerSuite) TestUserInfoUserExists(c *gc.C) { foobar := "foobar" fooTag := names.NewLocalUserTag(foobar) user := s.Factory.MakeUser(c, &factory.UserParams{Name: 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 := usermanager.UserInfoResults{ Results: []usermanager.UserInfoResult{ { Result: &usermanager.UserInfo{ Username: "******", DisplayName: "Foo Bar", CreatedBy: s.adminName, DateCreated: user.DateCreated(), LastConnection: user.LastLogin(), }, }, }, } c.Assert(results, gc.DeepEquals, expected) }
// RemoveUser removes a user. func (api *UserManagerAPI) RemoveUser(args params.Entities) (params.ErrorResults, error) { result := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Entities)), } if len(args.Entities) == 0 { return result, nil } for i, arg := range args.Entities { if !names.IsValidUserName(arg.Tag) { result.Results[i].Error = common.ServerError(errors.Errorf("%q is not a valid username", arg.Tag)) continue } user, err := api.state.User(names.NewLocalUserTag(arg.Tag)) if err != nil { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } err = user.Deactivate() if err != nil { result.Results[i].Error = common.ServerError(fmt.Errorf("Failed to remove user: %s", err)) continue } } return result, nil }
func (s *userManagerSuite) TestUserInfo(c *gc.C) { userFoo := s.Factory.MakeUser(c, &factory.UserParams{Name: "foobar", DisplayName: "Foo Bar"}) userBar := s.Factory.MakeUser(c, &factory.UserParams{Name: "barfoo", DisplayName: "Bar Foo", Disabled: true}) args := params.UserInfoRequest{ Entities: []params.Entity{ { Tag: userFoo.Tag().String(), }, { Tag: userBar.Tag().String(), }, { Tag: names.NewLocalUserTag("ellie").String(), }, { Tag: names.NewUserTag("not@remote").String(), }, { Tag: "not-a-tag", }, }} results, err := s.usermanager.UserInfo(args) c.Assert(err, jc.ErrorIsNil) expected := params.UserInfoResults{ Results: []params.UserInfoResult{ { Result: ¶ms.UserInfo{ Username: "******", DisplayName: "Foo Bar", CreatedBy: s.adminName, DateCreated: userFoo.DateCreated(), LastConnection: userFoo.LastLogin(), }, }, { Result: ¶ms.UserInfo{ Username: "******", DisplayName: "Bar Foo", CreatedBy: s.adminName, DateCreated: userBar.DateCreated(), LastConnection: userBar.LastLogin(), Disabled: true, }, }, { Error: ¶ms.Error{ Message: "permission denied", Code: params.CodeUnauthorized, }, }, { Error: ¶ms.Error{ Message: "permission denied", Code: params.CodeUnauthorized, }, }, { Error: ¶ms.Error{ Message: `"not-a-tag" is not a valid tag`, }, }}, } c.Assert(results, jc.DeepEquals, expected) }
func (s *UserSuite) TestUserAdd(c *gc.C) { ctx, err := s.RunUserCommand(c, "add-user", "test") c.Assert(err, jc.ErrorIsNil) c.Assert(testing.Stderr(ctx), jc.HasPrefix, `user "test" added`) user, err := s.State.User(names.NewLocalUserTag("test")) c.Assert(err, jc.ErrorIsNil) c.Assert(user.IsDisabled(), jc.IsFalse) }
// UserTag returns the Tag for the User. func (u *User) UserTag() names.UserTag { name := u.doc.Name if name == "" { // TODO(waigani) This is a hack for upgrades to 1.23. Once we are no // longer tied to 1.23, we can confidently always use u.doc.Name. name = u.doc.DocID } return names.NewLocalUserTag(name) }
func (s *StateSuite) SetUpTest(c *gc.C) { s.MgoSuite.SetUpTest(c) s.BaseSuite.SetUpTest(c) s.Owner = names.NewLocalUserTag("test-admin") s.State = Initialize(c, s.Owner, s.InitialConfig, s.Policy) s.AddCleanup(func(*gc.C) { s.State.Close() }) s.Factory = factory.NewFactory(s.State) }
func (s *BootstrapSuite) TestInitialPassword(c *gc.C) { machineConf, cmd, err := s.initBootstrapCommand(c, nil, "--model-config", s.b64yamlControllerModelConfig, "--hosted-model-config", s.b64yamlHostedModelConfig, "--instance-id", string(s.instanceId), ) c.Assert(err, jc.ErrorIsNil) err = cmd.Run(nil) c.Assert(err, jc.ErrorIsNil) info := &mongo.MongoInfo{ Info: mongo.Info{ Addrs: []string{gitjujutesting.MgoServer.Addr()}, CACert: testing.CACert, }, } // Check we can log in to mongo as admin. // TODO(dfc) does passing nil for the admin user name make your skin crawl ? mine too. info.Tag, info.Password = nil, testPassword st, err := state.Open(testing.ModelTag, info, mongotest.DialOpts(), environs.NewStatePolicy()) c.Assert(err, jc.ErrorIsNil) defer st.Close() // We're running Mongo with --noauth; let's explicitly verify // that we can login as that user. Even with --noauth, an // explicit Login will still be verified. adminDB := st.MongoSession().DB("admin") err = adminDB.Login("admin", "invalid-password") c.Assert(err, gc.ErrorMatches, "(auth|(.*Authentication)) fail(s|ed)\\.?") err = adminDB.Login("admin", info.Password) c.Assert(err, jc.ErrorIsNil) // Check that the admin user has been given an appropriate // password u, err := st.User(names.NewLocalUserTag("admin")) c.Assert(err, jc.ErrorIsNil) c.Assert(u.PasswordValid(testPassword), jc.IsTrue) // Check that the machine configuration has been given a new // password and that we can connect to mongo as that machine // and that the in-mongo password also verifies correctly. machineConf1, err := agent.ReadConfig(agent.ConfigPath(machineConf.DataDir(), names.NewMachineTag("0"))) c.Assert(err, jc.ErrorIsNil) stateinfo, ok := machineConf1.MongoInfo() c.Assert(ok, jc.IsTrue) st, err = state.Open(testing.ModelTag, stateinfo, mongotest.DialOpts(), environs.NewStatePolicy()) c.Assert(err, jc.ErrorIsNil) defer st.Close() m, err := st.Machine("0") c.Assert(err, jc.ErrorIsNil) c.Assert(m.HasVote(), jc.IsTrue) }
func (s *commonSuite) TestAuthFuncForTagKind(c *gc.C) { // TODO(dimitern): This list of all supported tags and kinds needs // to live in juju/names. uuid, err := utils.NewUUID() c.Assert(err, jc.ErrorIsNil) allTags := []names.Tag{ nil, // invalid tag names.NewActionTag(uuid.String()), names.NewCharmTag("cs:precise/missing"), names.NewModelTag(uuid.String()), names.NewFilesystemTag("20/20"), names.NewLocalUserTag("user"), names.NewMachineTag("42"), names.NewNetworkTag("public"), names.NewRelationTag("wordpress:mysql mysql:db"), names.NewServiceTag("wordpress"), names.NewSpaceTag("apps"), names.NewStorageTag("foo/42"), names.NewUnitTag("wordpress/5"), names.NewUserTag("joe"), names.NewVolumeTag("80/20"), } for i, allowedTag := range allTags { c.Logf("test #%d: allowedTag: %v", i, allowedTag) var allowedKind string if allowedTag != nil { allowedKind = allowedTag.Kind() } getAuthFunc := common.AuthFuncForTagKind(allowedKind) authFunc, err := getAuthFunc() if allowedKind == "" { c.Check(err, gc.ErrorMatches, "tag kind cannot be empty") c.Check(authFunc, gc.IsNil) continue } else if !c.Check(err, jc.ErrorIsNil) { continue } for j, givenTag := range allTags { c.Logf("test #%d.%d: givenTag: %v", i, j, givenTag) var givenKind string if givenTag != nil { givenKind = givenTag.Kind() } if allowedKind == givenKind { c.Check(authFunc(givenTag), jc.IsTrue) } else { c.Check(authFunc(givenTag), jc.IsFalse) } } } }
func (s *modelManagerSuite) TestGrantMissingUserFails(c *gc.C) { s.setAPIUser(c, s.AdminUserTag(c)) st := s.Factory.MakeModel(c, nil) defer st.Close() user := names.NewLocalUserTag("foobar") err := s.grant(c, user, params.ModelReadAccess, st.ModelTag()) expectedErr := `could not grant model access: user "foobar" does not exist locally: user "foobar" not found` c.Assert(err, gc.ErrorMatches, expectedErr) }
func (s *cmdControllerSuite) createModelNormalUser(c *gc.C, modelname string, isServer bool) { s.run(c, "add-user", "test") modelManager := modelmanager.NewClient(s.APIState) _, err := modelManager.CreateModel(names.NewLocalUserTag("test").Id(), nil, map[string]interface{}{ "name": modelname, "authorized-keys": "ssh-key", "controller": isServer, }) c.Assert(err, jc.ErrorIsNil) }
func (s *usermanagerSuite) TestUserInfoNoResults(c *gc.C) { usermanager.PatchResponses(s, s.usermanager, func(interface{}) error { // do nothing, we get an empty result with no error return nil }, ) tag := names.NewLocalUserTag("foobar") _, err := s.usermanager.UserInfo(tag.String()) c.Assert(err, gc.ErrorMatches, "expected 1 result, got 0") }
func (s *backupsSuite) SetUpTest(c *gc.C) { s.JujuConnSuite.SetUpTest(c) s.resources = common.NewResources() s.resources.RegisterNamed("dataDir", common.StringResource("/var/lib/juju")) tag := names.NewLocalUserTag("spam") s.authorizer = &apiservertesting.FakeAuthorizer{Tag: tag} var err error s.api, err = backupsAPI.NewAPI(s.State, s.resources, s.authorizer) c.Assert(err, jc.ErrorIsNil) s.meta = backupstesting.NewMetadataStarted() }
func (s *bootstrapSuite) TestInitializeStateFailsSecondTime(c *gc.C) { dataDir := c.MkDir() configParams := agent.AgentConfigParams{ Paths: agent.Paths{DataDir: dataDir}, Tag: names.NewMachineTag("0"), UpgradedToVersion: jujuversion.Current, StateAddresses: []string{s.mgoInst.Addr()}, CACert: testing.CACert, Password: testing.DefaultMongoPassword, Model: testing.ModelTag, } cfg, err := agent.NewAgentConfig(configParams) c.Assert(err, jc.ErrorIsNil) cfg.SetStateServingInfo(params.StateServingInfo{ APIPort: 5555, StatePort: s.mgoInst.Port(), Cert: "foo", PrivateKey: "bar", SharedSecret: "baz", SystemIdentity: "qux", }) expectHW := instance.MustParseHardware("mem=2048M") mcfg := agentbootstrap.BootstrapMachineConfig{ BootstrapConstraints: constraints.MustParse("mem=1024M"), Jobs: []multiwatcher.MachineJob{multiwatcher.JobManageModel}, InstanceId: "i-bootstrap", Characteristics: expectHW, } envAttrs := dummy.SampleConfig().Delete("admin-secret").Merge(testing.Attrs{ "agent-version": jujuversion.Current.String(), }) envCfg, err := config.New(config.NoDefaults, envAttrs) c.Assert(err, jc.ErrorIsNil) hostedModelConfigAttrs := map[string]interface{}{ "name": "hosted", "uuid": utils.MustNewUUID().String(), } adminUser := names.NewLocalUserTag("agent-admin") st, _, err := agentbootstrap.InitializeState( adminUser, cfg, envCfg, hostedModelConfigAttrs, mcfg, mongo.DefaultDialOpts(), state.Policy(nil), ) c.Assert(err, jc.ErrorIsNil) st.Close() st, _, err = agentbootstrap.InitializeState(adminUser, cfg, envCfg, nil, mcfg, mongo.DefaultDialOpts(), environs.NewStatePolicy()) if err == nil { st.Close() } c.Assert(err, gc.ErrorMatches, "failed to initialize mongo admin user: cannot set admin password: not authorized .*") }
// NewStateForModelNamed returns an new model with the given modelName, which // has a unique UUID, and does not need to be closed when the test completes. func (s *ConnSuite) NewStateForModelNamed(c *gc.C, modelName string) *state.State { cfg := testing.CustomModelConfig(c, testing.Attrs{ "name": modelName, "uuid": utils.MustNewUUID().String(), }) otherOwner := names.NewLocalUserTag("test-admin") _, otherState, err := s.State.NewModel(cfg, otherOwner) c.Assert(err, jc.ErrorIsNil) s.AddCleanup(func(*gc.C) { otherState.Close() }) return otherState }
func (s *InitializeSuite) TestInitialize(c *gc.C) { cfg := testing.EnvironConfig(c) uuid, _ := cfg.UUID() initial := cfg.AllAttrs() st, err := state.Initialize(state.TestingMongoInfo(), cfg, state.TestingDialOpts(), nil) c.Assert(err, gc.IsNil) c.Assert(st, gc.NotNil) envTag := st.EnvironTag() c.Assert(envTag.Id(), gc.Equals, uuid) err = st.Close() c.Assert(err, gc.IsNil) s.openState(c) cfg, err = s.State.EnvironConfig() c.Assert(err, gc.IsNil) c.Assert(cfg.AllAttrs(), gc.DeepEquals, initial) // Check that the environment has been created. env, err := s.State.Environment() c.Assert(err, gc.IsNil) c.Assert(env.Tag(), gc.Equals, envTag) // Check that the owner has been created. owner := names.NewLocalUserTag("admin") c.Assert(env.Owner(), gc.Equals, owner) // Check that the owner can be retrieved by the tag. entity, err := s.State.FindEntity(env.Owner()) c.Assert(err, gc.IsNil) c.Assert(entity.Tag(), gc.Equals, owner) // Check that the owner has an EnvUser created for the bootstrapped environment. envUser, err := s.State.EnvironmentUser(env.Owner()) c.Assert(err, gc.IsNil) c.Assert(envUser.UserTag().Username(), gc.Equals, env.Owner().Username()) c.Assert(envUser.EnvironmentTag(), gc.Equals, env.Tag()) // Check that the environment can be found through the tag. entity, err = s.State.FindEntity(envTag) c.Assert(err, gc.IsNil) annotator := entity.(state.Annotator) annotations, err := annotator.Annotations() c.Assert(err, gc.IsNil) c.Assert(annotations, gc.HasLen, 0) cons, err := s.State.EnvironConstraints() c.Assert(err, gc.IsNil) c.Assert(&cons, jc.Satisfies, constraints.IsEmpty) addrs, err := s.State.APIHostPorts() c.Assert(err, gc.IsNil) c.Assert(addrs, gc.HasLen, 0) info, err := s.State.StateServerInfo() c.Assert(err, gc.IsNil) c.Assert(info, jc.DeepEquals, &state.StateServerInfo{EnvironmentTag: envTag}) }
func (s *usermanagerSuite) TestRemoveUser(c *gc.C) { err := s.usermanager.AddUser("foobar", "Foo Bar", "password") c.Assert(err, gc.IsNil) userTag := names.NewLocalUserTag("foobar") _, err = s.State.User(userTag) c.Assert(err, gc.IsNil) err = s.usermanager.RemoveUser("foobar") c.Assert(err, gc.IsNil) user, err := s.State.User(userTag) c.Assert(user.IsDeactivated(), gc.Equals, true) }
func (m *mockAddUserAPI) AddUser(username, displayname, password string) (names.UserTag, error) { if m.blocked { return names.UserTag{}, common.OperationBlockedError("the operation has been blocked") } m.username = username m.displayname = displayname m.password = password if m.failMessage == "" { return names.NewLocalUserTag(username), nil } return names.UserTag{}, errors.New(m.failMessage) }
func (s *factorySuite) TestMakeEnvUserInvalidCreatedBy(c *gc.C) { invalidFunc := func() { s.Factory.MakeEnvUser(c, &factory.EnvUserParams{ User: "******", CreatedBy: names.NewMachineTag("0"), }) } c.Assert(invalidFunc, gc.PanicMatches, `interface conversion: .*`) saved, err := s.State.EnvironmentUser(names.NewLocalUserTag("bob")) c.Assert(err, jc.Satisfies, errors.IsNotFound) c.Assert(saved, gc.IsNil) }