Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions cmd/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,9 @@ func NewCommand(clients *shared.ClientFactory) *cobra.Command {
"Use --no-auth to skip authentication entirely and send the request without",
"a token.",
"",
"The response body is always printed. The command exits with an error when the",
"HTTP status is outside 2xx or the JSON response has \"ok\": false.",
"",
"See all methods at: https://docs.slack.dev/reference/methods",
}, "\n"),
Example: style.ExampleCommandsf([]style.ExampleCommand{
Expand Down Expand Up @@ -259,9 +262,31 @@ func runAPICommand(cmd *cobra.Command, clients *shared.ClientFactory, args []str
WithMessage("API request failed with status %d", resp.StatusCode)
}

var result map[string]json.RawMessage
if json.Unmarshal(resp.Body, &result) == nil {
var ok *bool
if json.Unmarshal(result["ok"], &ok) == nil && ok != nil && !*ok {

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.

🚦 issue (blocking): slack api has exited 0 on an HTTP 200 ok: false since v4.1.0, so a set -e script that reads .error stops after upgrading. Could this be opt-in, like curl's --fail-with-body, or wait for the next major?

return apiResponseError(result["error"], method)
}
}

return nil
}

func apiResponseError(rawError json.RawMessage, method string) error {
rawError = bytes.TrimSpace(rawError)
var code string
if json.Unmarshal(rawError, &code) == nil && code != "" {
return slackerror.NewAPIError(code, "", nil, method)
}
if len(rawError) == 0 || bytes.Equal(rawError, []byte("null")) || bytes.Equal(rawError, []byte(`""`)) {
return slackerror.New("api_request_failed").
WithMessage("API request failed with \"ok\": false")
}
return slackerror.New("api_request_failed").
WithMessage("API request failed with error %s", rawError)
}

// parseParams converts key=value arguments into url.Values
func parseParams(params []string) (url.Values, error) {
values := url.Values{}
Expand Down
122 changes: 122 additions & 0 deletions cmd/api/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,128 @@ func Test_runAPICommand_NonOKStatus(t *testing.T) {
assert.Contains(t, output, `"ok":false`)
}

func Test_runAPICommand_OKField(t *testing.T) {

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: The table covers the tricky shapes (null ok, uppercase OK, arrays, non-JSON), so the check can't widen by accident.

tests := map[string]struct {
flags cmdFlags
body string
expectedError string
expectedOut []string
}{
"ok false with error returns the error": {
flags: cmdFlags{method: "POST"},
body: `{"ok":false,"error":"invalid_auth"}`,
expectedError: "Your user account authorization isn't valid (invalid_auth)",
expectedOut: []string{`{"ok":false,"error":"invalid_auth"}`},
},
"ok false without error returns an error": {
flags: cmdFlags{method: "POST"},
body: `{"ok":false}`,
expectedError: `API request failed with "ok": false`,
expectedOut: []string{`{"ok":false}`},
},
"ok false with --include keeps the headers": {
flags: cmdFlags{method: "POST", include: true},
body: `{"ok":false,"error":"not_authed"}`,
expectedError: "(not_authed)",
expectedOut: []string{"HTTP 200", "X-Custom: test-value", `{"ok":false,"error":"not_authed"}`},
},
"ok false with an unknown error returns the error code": {
flags: cmdFlags{method: "POST"},
body: `{"ok":false,"error":"some_new_error"}`,
expectedError: "(some_new_error)",
expectedOut: []string{`{"ok":false,"error":"some_new_error"}`},
},
"ok false with an empty error returns an error": {
flags: cmdFlags{method: "POST"},
body: `{"ok":false,"error":""}`,
expectedError: `API request failed with "ok": false`,
expectedOut: []string{`{"ok":false,"error":""}`},
},
"ok false with a non-string error returns the error": {
flags: cmdFlags{method: "POST"},
body: `{"ok":false,"error":{"code":"invalid_auth"}}`,
expectedError: `API request failed with error {"code":"invalid_auth"}`,
expectedOut: []string{`{"ok":false,"error":{"code":"invalid_auth"}}`},
},
"ok false with a \"null\" string error returns the error": {
flags: cmdFlags{method: "POST"},
body: `{"ok":false,"error":"null"}`,
expectedError: "(null)",
expectedOut: []string{`{"ok":false,"error":"null"}`},
},
"ok false with a null error returns an error": {
flags: cmdFlags{method: "POST"},
body: `{"ok":false,"error":null}`,
expectedError: `API request failed with "ok": false`,
expectedOut: []string{`{"ok":false,"error":null}`},
},
"ok null succeeds": {
flags: cmdFlags{method: "POST"},
body: `{"ok":null}`,
expectedOut: []string{`{"ok":null}`},
},
"uppercase OK key succeeds": {
flags: cmdFlags{method: "POST"},
body: `{"OK":false}`,
expectedOut: []string{`{"OK":false}`},
},
"ok true succeeds": {
flags: cmdFlags{method: "POST"},
body: `{"ok":true,"user_id":"U123"}`,
expectedOut: []string{`{"ok":true,"user_id":"U123"}`},
},
"JSON without ok succeeds": {
flags: cmdFlags{method: "POST"},
body: `{"error":"not_an_ok_field"}`,
expectedOut: []string{`{"error":"not_an_ok_field"}`},
},
"JSON array succeeds": {
flags: cmdFlags{method: "POST"},
body: `[{"ok":false}]`,
expectedOut: []string{`[{"ok":false}]`},
},
"non-JSON body succeeds": {
flags: cmdFlags{method: "POST"},
body: "ok=false",
expectedOut: []string{"ok=false"},
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Custom", "test-value")
fmt.Fprint(w, tc.body)
}))
defer server.Close()

ctx := slackcontext.MockContext(t.Context())
clientsMock := shared.NewClientsMock()
clientsMock.AddDefaultMocks()
clientsMock.Config.TokenFlag = "xoxb-test-token"
clientsMock.Config.APIHostResolved = server.URL
clients := shared.NewClientFactory(clientsMock.MockClientFactory())

cmd := NewCommand(clients)
testutil.MockCmdIO(clients.IO, cmd)

flags = tc.flags
cmd.SetArgs([]string{"auth.test"})
err := cmd.ExecuteContext(ctx)

if tc.expectedError != "" {
assert.Error(t, err)
assert.Contains(t, err.Error(), tc.expectedError)
} else {
assert.NoError(t, err)
}
output := clientsMock.GetStdoutOutput()
for _, expected := range tc.expectedOut {
assert.Contains(t, output, expected)
}
})
}
}

func Test_runAPICommand_InvalidParam(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
clientsMock := shared.NewClientsMock()
Expand Down
3 changes: 3 additions & 0 deletions docs/reference/commands/slack_api.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading