Skip to content
Merged
36 changes: 27 additions & 9 deletions cmd/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -314,10 +314,7 @@ func resolveToken(ctx context.Context, clients *shared.ClientFactory) (string, e
return "", err
}
if selected.App.AppID != "" {
token, err := installAndGetBotToken(ctx, clients, selected)
if err == nil && token != "" {
return token, nil
}
return installAndGetBotToken(ctx, clients, selected)
}
}
}
Expand All @@ -339,10 +336,7 @@ func resolveToken(ctx context.Context, clients *shared.ClientFactory) (string, e
return "", err
}
if selected.App.AppID != "" {
token, err := installAndGetBotToken(ctx, clients, selected)
if err == nil && token != "" {
return token, nil
}
return installAndGetBotToken(ctx, clients, selected)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧪 suggestion (non-blocking): Could a test cover an install error after picking an app from the prompt? If I put back the old swallow-the-error form here, every test still passes.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in commit fc2a7fe as Test_resolveToken_AppSelection_InstallError. It fails when I put the old swallow-the-error form back. Great catch!

}
}

Expand All @@ -364,6 +358,11 @@ func installAndGetBotToken(ctx context.Context, clients *shared.ClientFactory, s
}

manifest := slackManifest.AppManifest
if !selected.App.IsDev && manifest.IsFunctionRuntimeSlackHosted() {
return "", slackerror.New(slackerror.ErrAppHosted).
WithMessage("A deployed app that runs on Slack doesn't share its bot token with the CLI").
WithRemediation("Choose the local app with --app local, or pass a token with --token")
}
botScopes := []string{}
if manifest.OAuthConfig != nil && manifest.OAuthConfig.Scopes != nil {
botScopes = manifest.OAuthConfig.Scopes.Bot
Expand All @@ -373,10 +372,29 @@ func installAndGetBotToken(ctx context.Context, clients *shared.ClientFactory, s
outgoingDomains = *manifest.OutgoingDomains
}

result, _, err := clients.API().DeveloperAppInstall(ctx, clients.IO, selected.Auth.Token, selected.App, botScopes, outgoingDomains, "", false)
result, installState, err := clients.API().DeveloperAppInstall(ctx, clients.IO, selected.Auth.Token, selected.App, botScopes, outgoingDomains, "", false)
if err != nil {
return "", err
}
switch installState {
case "", types.InstallSuccess:
case types.InstallRequestPending:
return "", slackerror.New(slackerror.ErrAppApprovalRequestPending).
WithRemediation("Ask an admin to approve the app, or pass a token with --token")
case types.InstallRequestCancelled:
return "", slackerror.New(slackerror.ErrAppInstall).
WithMessage("The app needs admin approval and its approval request was cancelled").
WithRemediation("Request approval again with `slack install`, or pass a token with --token")
default:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧠 question (non-blocking): REQUEST_CANCELLED also lands here. Could it get its own case, or could the message name the state? Right now a cancelled request reads the same as one that was never sent, and no test covers it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in commit fc2a7fe: cancelled now has its own message, and the table test covers each approval state. Thanks! 🙇

return "", slackerror.New(slackerror.ErrAppInstall).
WithMessage("The app needs admin approval and no approval request was sent").
WithRemediation("Request approval with `slack install`, or pass a token with --token")
}
if result.APIAccessTokens.Bot == "" {
return "", slackerror.New(slackerror.ErrAppInstall).
WithMessage("The app was installed but no bot token was returned").
WithRemediation("Pass a token with --token")
}

return result.APIAccessTokens.Bot, nil
}
146 changes: 145 additions & 1 deletion cmd/api/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
"github.com/slackapi/slack-cli/internal/shared"
"github.com/slackapi/slack-cli/internal/shared/types"
"github.com/slackapi/slack-cli/internal/slackcontext"
"github.com/slackapi/slack-cli/internal/slackerror"
"github.com/slackapi/slack-cli/test/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
Expand Down Expand Up @@ -642,7 +643,104 @@ func Test_resolveToken_AppFlag_ByID(t *testing.T) {
assert.Equal(t, "xoxb-app-bot-token", token)
}

func Test_resolveToken_AppFlag_Local(t *testing.T) {
func Test_resolveToken_AppFlag_InstallErrors(t *testing.T) {
tests := map[string]struct {
settings *types.AppSettings
installResult internalapi.DeveloperAppInstallResult
installState types.InstallState
installErr error
installCalls int
expectedErr string
expectedMessage string
}{
"deployed slack hosted app errors before installing": {
settings: &types.AppSettings{FunctionRuntime: types.SlackHosted},
installCalls: 0,
expectedErr: slackerror.ErrAppHosted,
expectedMessage: "doesn't share its bot token",
},
"install error is returned": {
installErr: slackerror.New(slackerror.ErrInvalidAppID),
installCalls: 1,
expectedErr: slackerror.ErrInvalidAppID,
expectedMessage: "app_id",
},
"install with no bot token errors": {
installResult: internalapi.DeveloperAppInstallResult{AppID: "A111"},
installState: types.InstallSuccess,
installCalls: 1,
expectedErr: slackerror.ErrAppInstall,
expectedMessage: "no bot token was returned",
},
"install needing approval with a cancelled request errors": {
installState: types.InstallRequestCancelled,
installCalls: 1,
expectedErr: slackerror.ErrAppInstall,
expectedMessage: "approval request was cancelled",
},
"install needing approval with no request sent errors": {
installState: types.InstallRequestNotSent,
installCalls: 1,
expectedErr: slackerror.ErrAppInstall,
expectedMessage: "no approval request was sent",
},
"install needing approval with a pending request errors": {
installState: types.InstallRequestPending,
installCalls: 1,
expectedErr: slackerror.ErrAppApprovalRequestPending,
expectedMessage: "awaiting review",
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
clientsMock := shared.NewClientsMock()
clientsMock.Os.AddDefaultMocks()
clientsMock.IO.On("PrintDebug", mock.Anything, mock.Anything, mock.MatchedBy(func(args ...any) bool { return true }))
clientsMock.Config.AppFlag = "A111"

clientsMock.Auth.On("Auths", mock.Anything).Return([]types.SlackAuth{
{Token: "xoxp-tooling", TeamID: "T111", TeamDomain: "team-a"},
}, nil)
clientsMock.Auth.On("SetSelectedAuth", mock.Anything, mock.Anything, mock.Anything, mock.Anything)

appClientMock := &app.AppClientMock{}
appClientMock.On("GetDeployedAll", mock.Anything).Return([]types.App{
{AppID: "A111", TeamID: "T111", TeamDomain: "team-a"},
}, "", nil)
appClientMock.On("GetLocalAll", mock.Anything).Return([]types.App{}, nil)
appClientMock.On("GetDeployed", mock.Anything, "T111").Return(types.App{AppID: "A111", TeamID: "T111", TeamDomain: "team-a"}, nil)
appClientMock.On("GetLocal", mock.Anything, "T111").Return(types.App{}, nil)
clientsMock.AppClient.AppClientInterface = appClientMock

clientsMock.API.On("GetAppStatus", mock.Anything, "xoxp-tooling", []string{"A111"}, "T111").
Return(internalapi.GetAppStatusResult{Apps: []internalapi.AppStatusResultAppInfo{{AppID: "A111", Installed: true}}}, nil)
clientsMock.API.On("ValidateSession", mock.Anything, "xoxp-tooling").Return(internalapi.AuthSession{}, nil)

manifestMock := clientsMock.AppClient.Manifest.(*app.ManifestMockObject)
manifestMock.On("GetManifestLocal", mock.Anything, mock.Anything, mock.Anything).Return(types.SlackYaml{
AppManifest: types.AppManifest{
Settings: tc.settings,
OAuthConfig: &types.OAuthConfig{Scopes: &types.ManifestScopes{Bot: []string{"chat:write"}}},
},
}, nil)

clientsMock.API.On("DeveloperAppInstall", mock.Anything, mock.Anything, "xoxp-tooling", mock.Anything, []string{"chat:write"}, []string{}, "", false).
Return(tc.installResult, tc.installState, tc.installErr)

clients := shared.NewClientFactory(clientsMock.MockClientFactory())
clients.SDKConfig.WorkingDirectory = "/fake/project"

token, err := resolveToken(ctx, clients)
assert.Empty(t, token)
assert.True(t, slackerror.Is(err, tc.expectedErr), "expected %s, got %v", tc.expectedErr, err)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧪 suggestion (non-blocking): The cancelled and not-sent rows both expect ErrAppInstall, so swapping their messages still passes. Could each row also check its message, say an expectedMessage field with assert.Contains?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in commit 3964dda: each row now checks its message too, and swapping the cancelled and not-sent messages fails the test. Great catch!

assert.Contains(t, err.Error(), tc.expectedMessage)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💯 praise: Checking each row's message means swapping the cancelled and not-sent messages now fails the test.

clientsMock.API.AssertNumberOfCalls(t, "DeveloperAppInstall", tc.installCalls)
})
}
}

func Test_resolveToken_AppFlag_LocalSlackHostedRuntime(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
clientsMock := shared.NewClientsMock()
clientsMock.Os.AddDefaultMocks()
Expand Down Expand Up @@ -672,6 +770,7 @@ func Test_resolveToken_AppFlag_Local(t *testing.T) {
manifestMock := clientsMock.AppClient.Manifest.(*app.ManifestMockObject)
manifestMock.On("GetManifestLocal", mock.Anything, mock.Anything, mock.Anything).Return(types.SlackYaml{
AppManifest: types.AppManifest{
Settings: &types.AppSettings{FunctionRuntime: types.SlackHosted},
OAuthConfig: &types.OAuthConfig{Scopes: &types.ManifestScopes{Bot: []string{"commands"}}},
},
}, nil)
Expand Down Expand Up @@ -771,6 +870,51 @@ func Test_resolveToken_AppSelection(t *testing.T) {
assert.Equal(t, "xoxb-app-bot-token", token)
}

func Test_resolveToken_AppSelection_InstallError(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
clientsMock := shared.NewClientsMock()
clientsMock.Os.AddDefaultMocks()
clientsMock.IO.On("PrintDebug", mock.Anything, mock.Anything, mock.MatchedBy(func(args ...any) bool { return true }))

clientsMock.Auth.On("Auths", mock.Anything).Return([]types.SlackAuth{
{Token: "xoxp-tooling", TeamID: "T111", TeamDomain: "team-a"},
}, nil)
clientsMock.Auth.On("SetSelectedAuth", mock.Anything, mock.Anything, mock.Anything, mock.Anything)

appClientMock := &app.AppClientMock{}
appClientMock.On("GetDeployedAll", mock.Anything).Return([]types.App{
{AppID: "A111", TeamID: "T111", TeamDomain: "team-a"},
}, "", nil)
appClientMock.On("GetLocalAll", mock.Anything).Return([]types.App{}, nil)
appClientMock.On("GetDeployed", mock.Anything, "T111").Return(types.App{AppID: "A111", TeamID: "T111", TeamDomain: "team-a"}, nil)
appClientMock.On("GetLocal", mock.Anything, "T111").Return(types.App{}, nil)
clientsMock.AppClient.AppClientInterface = appClientMock

clientsMock.API.On("GetAppStatus", mock.Anything, "xoxp-tooling", []string{"A111"}, "T111").
Return(internalapi.GetAppStatusResult{Apps: []internalapi.AppStatusResultAppInfo{{AppID: "A111", Installed: true}}}, nil)
clientsMock.API.On("ValidateSession", mock.Anything, "xoxp-tooling").Return(internalapi.AuthSession{}, nil)

clientsMock.IO.On("SelectPrompt", mock.Anything, "Select an app", mock.Anything, mock.Anything).
Return(iostreams.SelectPromptResponse{Index: 0, Prompt: true}, nil)

manifestMock := clientsMock.AppClient.Manifest.(*app.ManifestMockObject)
manifestMock.On("GetManifestLocal", mock.Anything, mock.Anything, mock.Anything).Return(types.SlackYaml{
AppManifest: types.AppManifest{
OAuthConfig: &types.OAuthConfig{Scopes: &types.ManifestScopes{Bot: []string{"chat:write"}}},
},
}, nil)

clientsMock.API.On("DeveloperAppInstall", mock.Anything, mock.Anything, "xoxp-tooling", mock.Anything, []string{"chat:write"}, []string{}, "", false).
Return(internalapi.DeveloperAppInstallResult{}, types.InstallState(""), slackerror.New(slackerror.ErrInvalidAppID))

clients := shared.NewClientFactory(clientsMock.MockClientFactory())
clients.SDKConfig.WorkingDirectory = "/fake/project"

token, err := resolveToken(ctx, clients)
assert.Empty(t, token)
assert.True(t, slackerror.Is(err, slackerror.ErrInvalidAppID))
}

func Test_resolveToken_NoTokenFound(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
clientsMock := shared.NewClientsMock()
Expand Down
Loading