Files
bbc9b152e6 MM-68417, MM-68420: API support for PAT expiry and admin policy settings (#36706)
* MM-68417, MM-68420: API support for PAT expiry and admin policy settings

POST /users/{id}/tokens now accepts a client-supplied expires_at
(previously stripped per the TODO in api4/user.go), and the create app
method enforces two new ServiceSettings:

  - EnforcePersonalAccessTokenExpiry (bool, default false): when on,
    rejects creates with expires_at == 0
  - MaximumPersonalAccessTokenLifetimeDays (int, default 0 = unlimited):
    caps how far in the future expires_at may be

Rejections return distinct app error ids so clients can disambiguate:
expires_at_required, expires_at_in_past, expires_at_too_far.

GET /users/{id}/tokens already serializes expires_at via the model's
JSON tag added in MM-68419; clients derive token status (active /
expired / inactive) from is_active + expires_at without a separate
server-side field, keeping the response shape minimal.

The Client4 helper CreateUserAccessToken gained an optional variadic
expiresAt parameter (and the mmctl Client interface + mock match)
rather than introducing a parallel WithExpiry method.

Refs: MM-68417, MM-68420

* MM-68417: exempt bot accounts from PAT expiry enforcement

Mirrors the existing EnableUserAccessTokens bypass at session.go:453,
where bot tokens are allowed even when human PATs are disabled. Bots
are programmatic clients that typically need long-lived credentials,
and integrations that provision them would otherwise break the moment
an admin enables EnforcePersonalAccessTokenExpiry — turning a settings
toggle into a footgun. The expiry policy now applies only to human
users; bots can still be given a future expires_at by callers that
want it, but the server won't require one.

Locked in by a new TestCreateUserAccessToken/bot_tokens_are_exempt
subtest that enables enforcement plus a 30-day cap, creates a bot,
and asserts a non-expiring token is accepted.

Refs: MM-68417

* MM-68420: bound MaximumPersonalAccessTokenLifetimeDays in isValid

Negative values silently meant "unlimited" (the runtime check is `> 0`),
and very large values overflow int64 when computing
`now + days*86_400_000` at token-creation time, producing a wrap-around
that either rejects all reasonable expiries or accepts past timestamps
as valid.

Bound the setting in ServiceSettings.isValid to [0, MaxPersonalAccess
TokenLifetimeDays] where the cap is 36500 (100 years) — past any
realistic operational use and well clear of int64 overflow. Surfaces
as a config validation error rather than a silently-broken runtime
check. New TestServiceSettingsIsValid cases lock in zero, negative,
upper-bound, and above-upper-bound behavior.

Refs: MM-68420

* MM-68417: reject multiple expiresAt values in Client4 helper

CodeRabbit caught that the variadic CreateUserAccessToken silently used
expiresAt[0] when callers passed more than one value, masking a
mis-call instead of failing fast. Return an error in that case so the
misuse is visible at the call site rather than producing a token with
the wrong (or right-but-coincidental) expiry.

Refs: MM-68417

* MM-68417: make expiresAt a required parameter on Client4.CreateUserAccessToken

Drop the variadic in favor of a regular int64 parameter. The variadic
form silently dropped extra values and made a misuse undetectable at
the call site (per CodeRabbit review on PR 36706); the previous fix
guarded against >1 values at runtime, but a required parameter is
strictly better — the compiler now refuses the misuse and every caller
is forced to make a deliberate decision about expiry. Existing callers
that want the old behavior pass 0 (== never expires).

Refs: MM-68417

* MM-68417: add --expires-in flag to mmctl user token generate

Adds an --expires-in duration flag so operators can create expiring
PATs via the CLI. Accepts the standard Go duration syntax plus a
trailing 'd' for days (the common case for token lifetimes), e.g.
--expires-in 90d, --expires-in 12h, --expires-in 1h30m. Empty (the
default) means no expiry — matching prior behavior. Without this
flag the command was unusable once an admin enables
EnforcePersonalAccessTokenExpiry, since every create would fail with
app.user_access_token.expires_at_required.app_error.

Flag parsing now happens before the user-lookup API call so the
command fails fast on invalid input. Regenerated mmctl docs reflect
the new flag.

Refs: MM-68417

* MM-68417: cap --expires-in day count to prevent time.Duration overflow

parseExpiresIn returns time.Duration(days) * 24 * time.Hour, which is
int64 nanoseconds and overflows past ~106751 days (CodeRabbit caught
this). Cap at model.MaxPersonalAccessTokenLifetimeDays (36500) so the
CLI rejects values the server would reject anyway, well below the
int64-overflow point. Adds two test cases (at-cap and beyond-cap) to
TestParseExpiresIn.

Refs: MM-68417

* MM-68420: collapse PAT expiry settings into a single max-lifetime setting

Remove ServiceSettings.EnforcePersonalAccessTokenExpiry and fold the
policy onto MaximumPersonalAccessTokenLifetimeDays: 0 means no policy
(never-expiring tokens allowed, no cap), while a value > 0 requires every
new token to expire within that many days. The two-setting design let an
admin set a maximum but leave enforcement off, silently allowing
never-expiring tokens to sidestep the cap; the only combination the
boolean added (require expiry, no upper bound) has little practical
value. The removed field was introduced on this branch and never
released, so this is not a breaking change.

---------

Co-authored-by: Hanzo Dev <[email protected]>
2026-06-04 14:21:35 +02:00

671 lines
18 KiB
Go

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package commands
import (
"context"
"errors"
gomock "github.com/golang/mock/gomock"
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/v8/cmd/mmctl/printer"
"github.com/spf13/cobra"
)
func (s *MmctlUnitTestSuite) TestBotCreateCmd() {
s.Run("Should create a bot", func() {
printer.Clean()
botArg := "a-bot"
cmd := &cobra.Command{}
cmd.Flags().String("display-name", "some-name", "")
cmd.Flags().String("description", "some-text", "")
mockBot := model.Bot{Username: botArg, DisplayName: "some-name", Description: "some-text"}
s.client.
EXPECT().
CreateBot(context.TODO(), &mockBot).
Return(&mockBot, &model.Response{}, nil).
Times(1)
err := botCreateCmdF(s.client, cmd, []string{botArg})
s.Require().Nil(err)
s.Require().Len(printer.GetLines(), 1)
s.Require().Equal(&mockBot, printer.GetLines()[0])
})
s.Run("Should create a bot with an access token", func() {
printer.Clean()
botArg := "a-bot"
cmd := &cobra.Command{}
cmd.Flags().String("display-name", "some-name", "")
cmd.Flags().String("description", "some-text", "")
cmd.Flags().Bool("with-token", true, "")
mockBot := model.Bot{Username: botArg, DisplayName: "some-name", Description: "some-text"}
mockToken := model.UserAccessToken{Token: "token-id", Description: "autogenerated"}
s.client.
EXPECT().
CreateBot(context.TODO(), &mockBot).
Return(&mockBot, &model.Response{}, nil).
Times(1)
s.client.
EXPECT().
GetUserByUsername(context.TODO(), botArg, "").
Return(model.UserFromBot(&mockBot), &model.Response{}, nil).
Times(1)
s.client.
EXPECT().
CreateUserAccessToken(context.TODO(), mockBot.UserId, "autogenerated", int64(0)).
Return(&mockToken, &model.Response{}, nil).
Times(1)
err := botCreateCmdF(s.client, cmd, []string{botArg})
s.Require().Nil(err)
s.Require().Len(printer.GetLines(), 2)
s.Require().Equal(&mockBot, printer.GetLines()[0])
s.Require().Equal(&mockToken, printer.GetLines()[1])
})
s.Run("Should error when creating a bot", func() {
printer.Clean()
botArg := "a-bot"
mockBot := model.Bot{Username: botArg, DisplayName: "", Description: ""}
s.client.
EXPECT().
CreateBot(context.TODO(), &mockBot).
Return(nil, &model.Response{}, errors.New("some-error")).
Times(1)
err := botCreateCmdF(s.client, &cobra.Command{}, []string{botArg})
s.Require().NotNil(err)
s.Require().Len(printer.GetLines(), 0)
s.Require().Contains(err.Error(), "could not create bot")
})
}
func (s *MmctlUnitTestSuite) TestBotUpdateCmd() {
s.Run("Should update a bot", func() {
printer.Clean()
botArg := "a-bot"
cmd := &cobra.Command{}
cmd.Flags().String("username", "new-username", "")
cmd.Flags().String("display-name", "some-name", "")
cmd.Flags().String("description", "some-text", "")
cmd.Flags().Lookup("username").Changed = true
cmd.Flags().Lookup("display-name").Changed = true
cmd.Flags().Lookup("description").Changed = true
mockBot := model.Bot{Username: "new-username", DisplayName: "some-name", Description: "some-text"}
mockUser := model.User{Id: model.NewId()}
s.client.
EXPECT().
GetUserByUsername(context.TODO(), botArg, "").
Return(&mockUser, &model.Response{}, nil).
Times(1)
s.client.
EXPECT().
PatchBot(context.TODO(), mockUser.Id, gomock.Any()).
Return(&mockBot, &model.Response{}, nil).
Times(1)
err := botUpdateCmdF(s.client, cmd, []string{botArg})
s.Require().Nil(err)
s.Require().Len(printer.GetLines(), 1)
s.Require().Equal(&mockBot, printer.GetLines()[0])
})
s.Run("Should error when user not found bot", func() {
printer.Clean()
botArg := "a-bot"
cmd := &cobra.Command{}
cmd.Flags().String("username", "bot-username", "")
cmd.Flags().Lookup("username").Changed = true
s.client.
EXPECT().
GetUserByUsername(context.TODO(), botArg, "").
Return(nil, &model.Response{}, errors.New("mock error")).
Times(1)
s.client.
EXPECT().
GetUser(context.TODO(), botArg, "").
Return(nil, &model.Response{}, errors.New("mock error")).
Times(1)
err := botUpdateCmdF(s.client, cmd, []string{botArg})
s.Require().NotNil(err)
s.Require().Len(printer.GetLines(), 0)
s.Require().Contains(err.Error(), "unable to find user 'a-bot'")
})
s.Run("Should error when updating bot", func() {
printer.Clean()
botArg := "a-bot"
cmd := &cobra.Command{}
cmd.Flags().String("display-name", "some-name", "")
cmd.Flags().String("description", "some-text", "")
cmd.Flags().Lookup("display-name").Changed = true
cmd.Flags().Lookup("description").Changed = true
mockUser := model.User{Id: model.NewId()}
s.client.
EXPECT().
GetUserByUsername(context.TODO(), botArg, "").
Return(&mockUser, &model.Response{}, nil).
Times(1)
s.client.
EXPECT().
PatchBot(context.TODO(), mockUser.Id, gomock.Any()).
Return(nil, &model.Response{}, errors.New("mock error")).
Times(1)
err := botUpdateCmdF(s.client, cmd, []string{botArg})
s.Require().NotNil(err)
s.Require().Len(printer.GetLines(), 0)
s.Require().Contains(err.Error(), "could not update bot")
})
}
func (s *MmctlUnitTestSuite) TestBotListCmd() {
s.Run("Should list correctly all", func() {
printer.Clean()
botArg := "a-bot"
cmd := &cobra.Command{}
cmd.Flags().Bool("orphaned", false, "")
cmd.Flags().Bool("all", true, "")
mockBot := model.Bot{UserId: model.NewId(), Username: botArg, DisplayName: "some-name", Description: "some-text", OwnerId: model.NewId()}
mockUser := model.User{Id: mockBot.OwnerId}
s.client.
EXPECT().
GetBotsIncludeDeleted(context.TODO(), 0, 200, "").
Return([]*model.Bot{&mockBot}, &model.Response{}, nil).
Times(1)
s.client.
EXPECT().
GetUsersByIds(context.TODO(), []string{mockBot.OwnerId}).
Return([]*model.User{&mockUser}, &model.Response{}, nil).
Times(1)
err := botListCmdF(s.client, cmd, []string{botArg})
s.Require().Nil(err)
s.Require().Len(printer.GetLines(), 1)
s.Require().Equal(&mockBot, printer.GetLines()[0])
})
s.Run("Should list fail if one featching all bots requests fail", func() {
printer.Clean()
botArg := "a-bot"
cmd := &cobra.Command{}
cmd.Flags().Bool("orphaned", false, "")
cmd.Flags().Bool("all", true, "")
s.client.
EXPECT().
GetBotsIncludeDeleted(context.TODO(), 0, 200, "").
Return(nil, &model.Response{}, errors.New("mock error")).
Times(1)
err := botListCmdF(s.client, cmd, []string{botArg})
s.Require().NotNil(err)
s.Require().Len(printer.GetLines(), 0)
s.Require().Contains(err.Error(), "Failed to fetch bots")
})
s.Run("Should list correctly orphaned", func() {
printer.Clean()
botArg := "a-bot"
cmd := &cobra.Command{}
cmd.Flags().Bool("orphaned", true, "")
cmd.Flags().Bool("all", false, "")
mockBot := model.Bot{UserId: model.NewId(), Username: botArg, DisplayName: "some-name", Description: "some-text", OwnerId: model.NewId()}
mockUser := model.User{Id: mockBot.OwnerId}
s.client.
EXPECT().
GetBotsOrphaned(context.TODO(), 0, 200, "").
Return([]*model.Bot{&mockBot}, &model.Response{}, nil).
Times(1)
s.client.
EXPECT().
GetUsersByIds(context.TODO(), []string{mockBot.OwnerId}).
Return([]*model.User{&mockUser}, &model.Response{}, nil).
Times(1)
err := botListCmdF(s.client, cmd, []string{botArg})
s.Require().Nil(err)
s.Require().Len(printer.GetLines(), 1)
s.Require().Equal(&mockBot, printer.GetLines()[0])
})
s.Run("Should list fail if one featching bots orphaned requests fail", func() {
printer.Clean()
botArg := "a-bot"
cmd := &cobra.Command{}
cmd.Flags().Bool("orphaned", true, "")
cmd.Flags().Bool("all", false, "")
s.client.
EXPECT().
GetBotsOrphaned(context.TODO(), 0, 200, "").
Return(nil, &model.Response{}, errors.New("mock error")).
Times(1)
err := botListCmdF(s.client, cmd, []string{botArg})
s.Require().NotNil(err)
s.Require().Len(printer.GetLines(), 0)
s.Require().Contains(err.Error(), "Failed to fetch bots")
})
s.Run("Should list correctly bots", func() {
printer.Clean()
botArg := "a-bot"
cmd := &cobra.Command{}
cmd.Flags().Bool("orphaned", false, "")
cmd.Flags().Bool("all", false, "")
mockBot := model.Bot{UserId: model.NewId(), Username: botArg, DisplayName: "some-name", Description: "some-text", OwnerId: model.NewId()}
mockUser := model.User{Id: mockBot.OwnerId}
s.client.
EXPECT().
GetBots(context.TODO(), 0, 200, "").
Return([]*model.Bot{&mockBot}, &model.Response{}, nil).
Times(1)
s.client.
EXPECT().
GetUsersByIds(context.TODO(), []string{mockBot.OwnerId}).
Return([]*model.User{&mockUser}, &model.Response{}, nil).
Times(1)
err := botListCmdF(s.client, cmd, []string{botArg})
s.Require().Nil(err)
s.Require().Len(printer.GetLines(), 1)
s.Require().Equal(&mockBot, printer.GetLines()[0])
})
s.Run("Should list correctly bots with invalid ownerId", func() {
printer.Clean()
botArg := "a-bot"
cmd := &cobra.Command{}
cmd.Flags().Bool("orphaned", false, "")
cmd.Flags().Bool("all", false, "")
mockBot := model.Bot{UserId: model.NewId(), Username: botArg, DisplayName: "some-name", Description: "some-text", OwnerId: "Mr.Robot"}
s.client.
EXPECT().
GetBots(context.TODO(), 0, 200, "").
Return([]*model.Bot{&mockBot}, &model.Response{}, nil).
Times(1)
s.client.
EXPECT().
GetUsersByIds(context.TODO(), []string{mockBot.OwnerId}).
Return([]*model.User{}, &model.Response{}, nil).
Times(1)
err := botListCmdF(s.client, cmd, []string{botArg})
s.Require().Nil(err)
s.Require().Len(printer.GetLines(), 1)
s.Require().Equal(&mockBot, printer.GetLines()[0])
})
s.Run("Should list fail if one fetching bots requests fail", func() {
printer.Clean()
botArg := "a-bot"
cmd := &cobra.Command{}
cmd.Flags().Bool("orphaned", false, "")
cmd.Flags().Bool("all", false, "")
s.client.
EXPECT().
GetBots(context.TODO(), 0, 200, "").
Return(nil, &model.Response{}, errors.New("mock error")).
Times(1)
err := botListCmdF(s.client, cmd, []string{botArg})
s.Require().NotNil(err)
s.Require().Len(printer.GetLines(), 0)
s.Require().Contains(err.Error(), "Failed to fetch bots")
})
s.Run("Should list fail if fetching owners requests fail", func() {
printer.Clean()
botArg := "a-bot"
cmd := &cobra.Command{}
cmd.Flags().Bool("orphaned", false, "")
cmd.Flags().Bool("all", false, "")
mockBot := model.Bot{UserId: model.NewId(), Username: botArg, DisplayName: "some-name", Description: "some-text", OwnerId: model.NewId()}
s.client.
EXPECT().
GetBots(context.TODO(), 0, 200, "").
Return([]*model.Bot{&mockBot}, &model.Response{}, nil).
Times(1)
s.client.
EXPECT().
GetUsersByIds(context.TODO(), []string{mockBot.OwnerId}).
Return(nil, &model.Response{}, errors.New("mock error")).
Times(1)
err := botListCmdF(s.client, cmd, []string{botArg})
s.Require().NotNil(err)
s.Require().Len(printer.GetLines(), 0)
s.Require().Contains(err.Error(), "Failed to fetch bots")
})
}
func (s *MmctlUnitTestSuite) TestBotDisableCmd() {
s.Run("Should disable a bot", func() {
printer.Clean()
botArg := "a-bot"
mockBot := model.Bot{Username: botArg, DisplayName: "some-name", Description: "some-text"}
mockUser := model.User{Id: model.NewId()}
s.client.
EXPECT().
GetUserByUsername(context.TODO(), botArg, "").
Return(&mockUser, &model.Response{}, nil).
Times(1)
s.client.
EXPECT().
DisableBot(context.TODO(), mockUser.Id).
Return(&mockBot, &model.Response{}, nil).
Times(1)
err := botDisableCmdF(s.client, &cobra.Command{}, []string{botArg})
s.Require().Nil(err)
s.Require().Len(printer.GetLines(), 1)
s.Require().Equal(&mockBot, printer.GetLines()[0])
})
s.Run("Should error when user not found bot", func() {
printer.Clean()
botArg := "a-bot"
s.client.
EXPECT().
GetUserByUsername(context.TODO(), botArg, "").
Return(nil, &model.Response{}, errors.New("mock error")).
Times(1)
s.client.
EXPECT().
GetUser(context.TODO(), botArg, "").
Return(nil, &model.Response{}, errors.New("mock error")).
Times(1)
err := botDisableCmdF(s.client, &cobra.Command{}, []string{botArg})
s.Require().Error(err)
s.Require().Len(printer.GetErrorLines(), 1)
s.Require().Contains(printer.GetErrorLines()[0], "can't find user 'a-bot'")
})
s.Run("Should error when disabling bot", func() {
printer.Clean()
botArg := "a-bot"
cmd := &cobra.Command{}
cmd.Flags().String("display-name", "some-name", "")
cmd.Flags().String("description", "some-text", "")
cmd.Flags().Lookup("display-name").Changed = true
cmd.Flags().Lookup("description").Changed = true
mockUser := model.User{Id: model.NewId()}
s.client.
EXPECT().
GetUserByUsername(context.TODO(), botArg, "").
Return(&mockUser, &model.Response{}, nil).
Times(1)
s.client.
EXPECT().
DisableBot(context.TODO(), mockUser.Id).
Return(nil, &model.Response{}, errors.New("mock error")).
Times(1)
err := botDisableCmdF(s.client, cmd, []string{botArg})
s.Require().Error(err)
s.Require().Len(printer.GetErrorLines(), 1)
s.Require().Contains(printer.GetErrorLines()[0], "could not disable bot 'a-bot'")
})
}
func (s *MmctlUnitTestSuite) TestBotEnableCmd() {
s.Run("Should enable a bot", func() {
printer.Clean()
botArg := "a-bot"
mockBot := model.Bot{Username: botArg, DisplayName: "some-name", Description: "some-text"}
mockUser := model.User{Id: model.NewId()}
s.client.
EXPECT().
GetUserByUsername(context.TODO(), botArg, "").
Return(&mockUser, &model.Response{}, nil).
Times(1)
s.client.
EXPECT().
EnableBot(context.TODO(), mockUser.Id).
Return(&mockBot, &model.Response{}, nil).
Times(1)
err := botEnableCmdF(s.client, &cobra.Command{}, []string{botArg})
s.Require().Nil(err)
s.Require().Len(printer.GetLines(), 1)
s.Require().Equal(&mockBot, printer.GetLines()[0])
})
s.Run("Should error when user not found bot", func() {
printer.Clean()
botArg := "a-bot"
s.client.
EXPECT().
GetUserByUsername(context.TODO(), botArg, "").
Return(nil, &model.Response{}, errors.New("mock error")).
Times(1)
s.client.
EXPECT().
GetUser(context.TODO(), botArg, "").
Return(nil, &model.Response{}, errors.New("mock error")).
Times(1)
err := botEnableCmdF(s.client, &cobra.Command{}, []string{botArg})
s.Require().Error(err)
s.Require().Len(printer.GetErrorLines(), 1)
s.Require().Contains(printer.GetErrorLines()[0], "can't find user 'a-bot'")
})
s.Run("Should error when enabling bot", func() {
printer.Clean()
botArg := "a-bot"
cmd := &cobra.Command{}
cmd.Flags().String("display-name", "some-name", "")
cmd.Flags().String("description", "some-text", "")
cmd.Flags().Lookup("display-name").Changed = true
cmd.Flags().Lookup("description").Changed = true
mockUser := model.User{Id: model.NewId()}
s.client.
EXPECT().
GetUserByUsername(context.TODO(), botArg, "").
Return(&mockUser, &model.Response{}, nil).
Times(1)
s.client.
EXPECT().
EnableBot(context.TODO(), mockUser.Id).
Return(nil, &model.Response{}, errors.New("mock error")).
Times(1)
err := botEnableCmdF(s.client, cmd, []string{botArg})
s.Require().Error(err)
s.Require().Len(printer.GetErrorLines(), 1)
s.Require().Contains(printer.GetErrorLines()[0], "could not enable bot 'a-bot'")
})
}
func (s *MmctlUnitTestSuite) TestBotAssignCmd() {
s.Run("Should assign a bot", func() {
printer.Clean()
botArg := "a-bot"
userArg := "a-user"
mockBot := model.Bot{Username: botArg, DisplayName: "some-name", Description: "some-text"}
mockBotUser := model.User{Id: model.NewId()}
mockNewOwner := model.User{Id: model.NewId()}
s.client.
EXPECT().
GetUserByUsername(context.TODO(), botArg, "").
Return(&mockBotUser, &model.Response{}, nil).
Times(1)
s.client.
EXPECT().
GetUserByUsername(context.TODO(), userArg, "").
Return(&mockNewOwner, &model.Response{}, nil).
Times(1)
s.client.
EXPECT().
AssignBot(context.TODO(), mockBotUser.Id, mockNewOwner.Id).
Return(&mockBot, &model.Response{}, nil).
Times(1)
err := botAssignCmdF(s.client, &cobra.Command{}, []string{botArg, userArg})
s.Require().Nil(err)
s.Require().Len(printer.GetLines(), 1)
s.Require().Equal(&mockBot, printer.GetLines()[0])
})
s.Run("Should error when bot user not found", func() {
printer.Clean()
botArg := "a-bot"
userArg := "a-user"
s.client.
EXPECT().
GetUserByUsername(context.TODO(), botArg, "").
Return(nil, &model.Response{}, errors.New("mock error")).
Times(1)
s.client.
EXPECT().
GetUser(context.TODO(), botArg, "").
Return(nil, &model.Response{}, errors.New("mock error")).
Times(1)
err := botAssignCmdF(s.client, &cobra.Command{}, []string{botArg, userArg})
s.Require().NotNil(err)
s.Require().Len(printer.GetLines(), 0)
s.Require().Contains(err.Error(), "unable to find user 'a-bot'")
})
s.Run("Should error when new owner not found", func() {
printer.Clean()
botArg := "a-bot"
userArg := "a-user"
mockBotUser := model.User{Id: model.NewId()}
s.client.
EXPECT().
GetUserByUsername(context.TODO(), botArg, "").
Return(&mockBotUser, &model.Response{}, nil).
Times(1)
s.client.
EXPECT().
GetUserByUsername(context.TODO(), userArg, "").
Return(nil, &model.Response{}, errors.New("mock error")).
Times(1)
s.client.
EXPECT().
GetUser(context.TODO(), userArg, "").
Return(nil, &model.Response{}, errors.New("mock error")).
Times(1)
err := botAssignCmdF(s.client, &cobra.Command{}, []string{botArg, userArg})
s.Require().NotNil(err)
s.Require().Len(printer.GetLines(), 0)
s.Require().Contains(err.Error(), "unable to find user 'a-user'")
})
s.Run("Should error when assigning bot", func() {
printer.Clean()
botArg := "a-bot"
userArg := "a-user"
mockBotUser := model.User{Id: model.NewId()}
mockNewOwner := model.User{Id: model.NewId()}
s.client.
EXPECT().
GetUserByUsername(context.TODO(), botArg, "").
Return(&mockBotUser, &model.Response{}, nil).
Times(1)
s.client.
EXPECT().
GetUserByUsername(context.TODO(), userArg, "").
Return(&mockNewOwner, &model.Response{}, nil).
Times(1)
s.client.
EXPECT().
AssignBot(context.TODO(), mockBotUser.Id, mockNewOwner.Id).
Return(nil, &model.Response{}, errors.New("mock error")).
Times(1)
err := botAssignCmdF(s.client, &cobra.Command{}, []string{botArg, userArg})
s.Require().NotNil(err)
s.Require().Len(printer.GetLines(), 0)
s.Require().Contains(err.Error(), "can not assign bot 'a-bot' to user 'a-user'")
})
}