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
8 changes: 6 additions & 2 deletions adapters/slack/slackapi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ The package has four parts:

1. A Slack Web API client (`Client`) with typed methods, a generic `Call` escape hatch, and bounded rate-limit retry.
2. Two inbound transports that share one `Handler`: `Webhook` (signed HTTP requests) and `Client.Listen` (Socket Mode websocket).
3. Payload decoding for the Events API (`ParseEnvelope` and event types).
3. Payload decoding for the Events API (`ParseEnvelope` and event types) and `block_actions` interactions (`ParseBlockActions`).
4. Formats: Block Kit blocks, a Markdown splitter, mention helpers, and app manifest types.

The Slack adapter (package `slack`) uses this package for its Web API calls, rate-limit retry, history reads, and both inbound transports. The package doc marks the API as experimental. `RetryPolicy` and `RateLimited` keep the supported tier, because the Slack adapter exports them as type aliases. [doc.go:slackapi]
Expand Down Expand Up @@ -46,6 +46,7 @@ The Slack adapter (package `slack`) uses this package for its Web API calls, rat
| `Client.GetUploadURLExternal` | `files.getUploadURLExternal` | [files.go:Client.GetUploadURLExternal] |
| `Client.CompleteUploadExternal` | `files.completeUploadExternal` | [files.go:Client.CompleteUploadExternal] |
| `Client.OAuthV2Access` | `oauth.v2.access` | [oauth.go:Client.OAuthV2Access] |
| `Client.OpenIDConnectToken` | `openid.connect.token` | [openid.go:Client.OpenIDConnectToken] |
| `Client.AddReaction`, `Client.RemoveReaction` | `reactions.add`, `reactions.remove` | [reactions.go:Client.AddReaction,Client.RemoveReaction] |
| `Client.SetAssistantThreadStatus` | `assistant.threads.setStatus` | [status.go:Client.SetAssistantThreadStatus] |
| `Client.SetAgentSessionStatus` | `agents.sessions.setStatus` | [status.go:Client.SetAgentSessionStatus] |
Expand All @@ -60,6 +61,7 @@ Some of those types hold nested exported types:
- `FileSummary`: one uploaded file in `CompleteUploadExternalRequest`. [files.go:FileSummary]
- `FileShares` and `FileShare`: the shares of a file by channel ID, in `FileInfoResponse`. [files.go:FileShares,FileShare]
- `OAuthTeam`: the workspace or Enterprise Grid organization in `OAuthV2AccessResponse`. [oauth.go:OAuthTeam]
- `IDTokenClaims`: the decoded ID token claims in `OpenIDConnectTokenResponse`, with the Slack team ID and user ID. [openid.go:IDTokenClaims]

### Files

Expand All @@ -74,6 +76,7 @@ Some of those types hold nested exported types:
- `DeliveryType` has the values `DeliveryEventsAPI`, `DeliverySlashCommands`, and `DeliveryInteractive`. [delivery.go:DeliveryType]
- `Handler` handles a `Delivery` and returns the ack response. [delivery.go:Handler]
- `ErrBusy` and `ErrInvalidPayload` are sentinel handler errors. [delivery.go:ErrBusy,ErrInvalidPayload]
- `ParseBlockActions` decodes a `block_actions` interaction payload into `BlockActionsPayload` and its `Interaction*` and `BlockAction` types. It returns false for another interaction type. The typed payload covers a button click in a message, for an app that is installed in one workspace. For a click in a view, a select menu or another element, or an org-wide install on Enterprise Grid, the caller decodes the other fields, such as `view`, `selected_option`, or `enterprise`, from the raw payload. [interaction.go:ParseBlockActions,BlockActionsPayload,BlockAction]
- `Webhook` is the HTTP transport (`SigningSecret`, `Handler`, `Now`, `SignatureTolerance`). `Webhook.ServeHTTP` handles one request. [webhook.go:Webhook,Webhook.ServeHTTP]
- `VerifyRequest` checks the Slack v0 HMAC-SHA256 request signature. `DefaultSignatureTolerance` is 5 minutes. [signature.go:VerifyRequest,DefaultSignatureTolerance]
- `Client.Listen` is the Socket Mode transport. [socketmode.go:Client.Listen]
Expand Down Expand Up @@ -109,7 +112,8 @@ Some of those types hold nested exported types:

- `Client` is safe for concurrent use. [client.go:Client]
- `New` trims trailing slashes from `BaseURL`. It drops each `FileOrigins` entry that is not an absolute URL with a host, and logs a warning for it. [client.go:New]
- The client sends the `Authorization` header only when the token is not empty. `UploadToURL`, `PostResponseURL`, and `OAuthV2Access` never send the client token. [client.go:send,Options], [oauth.go:Client.OAuthV2Access]
- The client sends the `Authorization` header only when the token is not empty. `UploadToURL`, `PostResponseURL`, `OAuthV2Access`, and `OpenIDConnectToken` never send the client token. [client.go:send,Options], [oauth.go:Client.OAuthV2Access], [openid.go:Client.OpenIDConnectToken]
- `OpenIDConnectToken` checks the audience, the team ID, and the user ID of the ID token. It does not check the signature, the issuer, the expiry, or the nonce. The caller must check the issuer, the expiry, and the nonce (when the authorize request sent one) in `Claims`. [openid.go:Client.OpenIDConnectToken,parseIDToken]
- `Call` encodes a nil payload as `{}`, a `url.Values` payload as a form body, and any other payload as JSON. [client.go:Client.Call,encodeRequest]
- An `ok:false` response or a non-2xx status returns `*APIError`, except a throttling response: HTTP 429, or `ok:false` with `ratelimited` or `rate_limited`. Retry handles that response, and the retry rules below say when it returns `*RateLimited`. [client.go:Client.Call,send], [retry.go:slackThrottle,Client.doWithRetry]
- `WithToken` shares the base URL, file origins, HTTP client, retry policy, observer, and logger with the original client. [client.go:Client.WithToken]
Expand Down
6 changes: 6 additions & 0 deletions adapters/slack/slackapi/blocks.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,10 @@ type ButtonElement struct {
URL string
// ActionID is the optional action_id. It is omitted when empty.
ActionID string
// Value is the optional value that Slack sends back in the block_actions
// action when someone clicks the button. Slack allows at most 2000
// characters. It is omitted when empty.
Value string
// Style is the optional button style, "primary" or "danger". It is
// omitted when empty.
Style string
Expand All @@ -88,12 +92,14 @@ func (e ButtonElement) MarshalJSON() ([]byte, error) {
Text plainTextJSON `json:"text"`
URL string `json:"url,omitempty"`
ActionID string `json:"action_id,omitempty"`
Value string `json:"value,omitempty"`
Style string `json:"style,omitempty"`
}{
Type: "button",
Text: newPlainText(e.Text),
URL: e.URL,
ActionID: e.ActionID,
Value: e.Value,
Style: e.Style,
})
}
Expand Down
4 changes: 2 additions & 2 deletions adapters/slack/slackapi/blocks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,10 @@ func TestBlocksMarshalJSON(t *testing.T) {
{
name: "ActionsBlockWithBlockID",
block: slackapi.ActionsBlock{
Elements: []slackapi.ButtonElement{{Text: "Stop", ActionID: "stop", Style: "danger"}},
Elements: []slackapi.ButtonElement{{Text: "Stop", ActionID: "stop", Value: "chat-1", Style: "danger"}},
BlockID: "actions",
},
want: `{"type":"actions","elements":[{"type":"button","text":{"type":"plain_text","text":"Stop"},"action_id":"stop","style":"danger"}],"block_id":"actions"}`,
want: `{"type":"actions","elements":[{"type":"button","text":{"type":"plain_text","text":"Stop"},"action_id":"stop","value":"chat-1","style":"danger"}],"block_id":"actions"}`,
},
{
name: "ImageBlock",
Expand Down
3 changes: 3 additions & 0 deletions adapters/slack/slackapi/form_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,9 @@ func TestMethodsReturnAPIError(t *testing.T) {
{"oauth.v2.access", func(ctx context.Context, c *slackapi.Client) (any, error) {
return c.OAuthV2Access(ctx, slackapi.OAuthV2AccessRequest{})
}},
{"openid.connect.token", func(ctx context.Context, c *slackapi.Client) (any, error) {
return c.OpenIDConnectToken(ctx, slackapi.OpenIDConnectTokenRequest{})
}},
{"chat.postEphemeral", func(ctx context.Context, c *slackapi.Client) (any, error) {
return c.PostEphemeral(ctx, slackapi.PostEphemeralRequest{})
}},
Expand Down
123 changes: 123 additions & 0 deletions adapters/slack/slackapi/interaction.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package slackapi

import (
"encoding/json"
"fmt"
)

// InteractionTypeBlockActions is the type of the interaction payload that
// Slack sends when someone uses an interactive element, such as a button.
const InteractionTypeBlockActions = "block_actions"

// BlockActionsPayload is a block_actions interaction payload.
type BlockActionsPayload struct {
// Type is InteractionTypeBlockActions.
Type string `json:"type,omitempty"`
// Team is the workspace of the user. It is zero when Slack sends null,
// for an org-wide install on Enterprise Grid.
Team InteractionTeam `json:"team,omitzero"`
Comment thread
ethanndickson marked this conversation as resolved.
Resolved
// User is the user who used the element.
User InteractionUser `json:"user,omitzero"`
// APIAppID is the ID of the app.
APIAppID string `json:"api_app_id,omitempty"`
// Container is where the element is.
Container InteractionContainer `json:"container,omitzero"`
// TriggerID opens a modal within 3 seconds of the interaction.
TriggerID string `json:"trigger_id,omitempty"`
// Channel is the conversation of the element.
Channel InteractionChannel `json:"channel,omitzero"`
// Message is the message that holds the element. It is nil when the
// element is not in a message, and for an ephemeral message. For the
// thread of the message, use Container.ThreadTS.
Message *Message `json:"message,omitempty"`
// ResponseURL is the URL that PostResponseURL can post a response to.
ResponseURL string `json:"response_url,omitempty"`
// Actions are the actions of the interaction, usually one.
Actions []BlockAction `json:"actions,omitempty"`
}

// InteractionTeam is the workspace in an interaction payload.
type InteractionTeam struct {
// ID is the workspace ID (T).
ID string `json:"id,omitempty"`
// Domain is the subdomain of the workspace.
Domain string `json:"domain,omitempty"`
}

// InteractionUser is the user in an interaction payload.
type InteractionUser struct {
// ID is the user ID.
ID string `json:"id,omitempty"`
// Username is the user name.
Username string `json:"username,omitempty"`
// Name is the name of the user.
Name string `json:"name,omitempty"`
// TeamID is the ID of the workspace of the user.
TeamID string `json:"team_id,omitempty"`
}

// InteractionContainer is the container of the element in an interaction
// payload.
type InteractionContainer struct {
// Type is the container type, for example "message".
Type string `json:"type,omitempty"`
// MessageTS is the ts of the message that holds the element.
MessageTS string `json:"message_ts,omitempty"`
// ChannelID is the ID of the conversation of the message.
ChannelID string `json:"channel_id,omitempty"`
Comment thread
ethanndickson marked this conversation as resolved.
Resolved
// ThreadTS is the thread_ts of the message that holds the element. It
// is empty when the message is not in a thread, or when Slack omits it.
ThreadTS string `json:"thread_ts,omitempty"`
// IsEphemeral is true when the message is an ephemeral message.
IsEphemeral bool `json:"is_ephemeral,omitzero"`
}

// InteractionChannel is the conversation in an interaction payload.
type InteractionChannel struct {
// ID is the conversation ID.
ID string `json:"id,omitempty"`
// Name is the name of the conversation.
Name string `json:"name,omitempty"`
}

// BlockAction is one action in a BlockActionsPayload, with the fields of a
// button action.
type BlockAction struct {
// Type is the element type, for example "button".
Type string `json:"type,omitempty"`
// ActionID is the action_id of the element.
ActionID string `json:"action_id,omitempty"`
// BlockID is the block_id of the block that holds the element.
BlockID string `json:"block_id,omitempty"`
// Value is the value of the element, for example ButtonElement.Value.
Value string `json:"value,omitempty"`
// ActionTS is the timestamp of the action.
ActionTS string `json:"action_ts,omitempty"`
}

// ParseBlockActions decodes the payload of a DeliveryInteractive delivery
// when its type is InteractionTypeBlockActions. It returns false for an
// interaction of another type, for example view_submission, and an error if
// the payload does not decode.
//
// The typed payload covers a button click in a message, for an app that is
// installed in one workspace. For a click in a view, a select menu or another
// element, or an org-wide install on Enterprise Grid, decode the other
// fields, for example view, selected_option, or enterprise, from the raw
// payload.
func ParseBlockActions(payload []byte) (*BlockActionsPayload, bool, error) {
var head struct {
Type string `json:"type"`
}
if err := json.Unmarshal(payload, &head); err != nil {
return nil, false, fmt.Errorf("slack: invalid interaction: %w", err)
}
if head.Type != InteractionTypeBlockActions {
return nil, false, nil
}
var p BlockActionsPayload
if err := json.Unmarshal(payload, &p); err != nil {
return nil, false, fmt.Errorf("slack: invalid block_actions interaction: %w", err)
}
return &p, true, nil
}
128 changes: 128 additions & 0 deletions adapters/slack/slackapi/interaction_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
package slackapi_test

import (
"testing"

"github.com/coder/chat/adapters/slack/slackapi"
)

func TestParseBlockActions(t *testing.T) {
t.Parallel()

t.Run("ButtonClick", func(t *testing.T) {
t.Parallel()
got, ok, err := slackapi.ParseBlockActions([]byte(`{
"type": "block_actions",
"team": {"id": "T0TEAM", "domain": "acme"},
"user": {"id": "U0USER", "username": "ada", "name": "ada.lovelace", "team_id": "T0TEAM"},
"api_app_id": "A0APP",
"token": "verification-token",
"container": {"type": "message", "message_ts": "1700000000.000200", "channel_id": "C0CHAN", "thread_ts": "1700000000.000100", "is_ephemeral": false},
"trigger_id": "123.456.abc",
"channel": {"id": "C0CHAN", "name": "general"},
"enterprise": null,
"message": {
"type": "message",
"user": "U0BOT",
"bot_id": "B0BOT",
"text": "Done.",
"ts": "1700000000.000200",
"thread_ts": "1700000000.000100",
"team": "T0TEAM",
"blocks": [{"type": "actions", "block_id": "open", "elements": []}]
},
"state": {"values": {}},
"response_url": "https://hooks.slack.com/actions/T0TEAM/1/abc",
"actions": [{
"action_id": "open_in_coder",
"block_id": "open",
"text": {"type": "plain_text", "text": "Open in Coder", "emoji": true},
"value": "chat-1",
"type": "button",
"action_ts": "1700000001.000300"
}]
}`))
if err != nil || !ok {
t.Fatalf("ParseBlockActions = %v, %v, want true, nil", ok, err)
}
methodsCheckEqual(t, "payload", got, &slackapi.BlockActionsPayload{
Type: slackapi.InteractionTypeBlockActions,
Team: slackapi.InteractionTeam{ID: "T0TEAM", Domain: "acme"},
User: slackapi.InteractionUser{ID: "U0USER", Username: "ada", Name: "ada.lovelace", TeamID: "T0TEAM"},
APIAppID: "A0APP",
Container: slackapi.InteractionContainer{
Type: "message",
MessageTS: "1700000000.000200",
ChannelID: "C0CHAN",
ThreadTS: "1700000000.000100",
},
TriggerID: "123.456.abc",
Channel: slackapi.InteractionChannel{ID: "C0CHAN", Name: "general"},
Message: &slackapi.Message{
Type: "message",
User: "U0BOT",
BotID: "B0BOT",
Text: "Done.",
TS: "1700000000.000200",
ThreadTS: "1700000000.000100",
Team: "T0TEAM",
},
ResponseURL: "https://hooks.slack.com/actions/T0TEAM/1/abc",
Actions: []slackapi.BlockAction{{
Type: "button",
ActionID: "open_in_coder",
BlockID: "open",
Value: "chat-1",
ActionTS: "1700000001.000300",
}},
})
})

t.Run("EphemeralMessage", func(t *testing.T) {
t.Parallel()
got, ok, err := slackapi.ParseBlockActions([]byte(`{
"type": "block_actions",
"user": {"id": "U0USER"},
"container": {"type": "message", "message_ts": "1700000000.000300", "channel_id": "C0CHAN", "thread_ts": "1700000000.000100", "is_ephemeral": true},
"channel": {"id": "C0CHAN"},
"actions": [{"action_id": "link", "block_id": "link", "type": "button", "action_ts": "1700000001.000400"}]
}`))
if err != nil || !ok {
t.Fatalf("ParseBlockActions = %v, %v, want true, nil", ok, err)
}
methodsCheckEqual(t, "payload", got, &slackapi.BlockActionsPayload{
Type: slackapi.InteractionTypeBlockActions,
User: slackapi.InteractionUser{ID: "U0USER"},
Container: slackapi.InteractionContainer{
Type: "message",
MessageTS: "1700000000.000300",
ChannelID: "C0CHAN",
ThreadTS: "1700000000.000100",
IsEphemeral: true,
},
Channel: slackapi.InteractionChannel{ID: "C0CHAN"},
Actions: []slackapi.BlockAction{{Type: "button", ActionID: "link", BlockID: "link", ActionTS: "1700000001.000400"}},
})
})

t.Run("OtherType", func(t *testing.T) {
t.Parallel()
got, ok, err := slackapi.ParseBlockActions([]byte(`{"type":"view_submission","channel":"C0CHAN","view":{"id":"V0VIEW"}}`))
if got != nil || ok || err != nil {
t.Fatalf("ParseBlockActions = %+v, %v, %v, want nil, false, nil", got, ok, err)
}
})

for name, payload := range map[string]string{
"InvalidJSON": `{`,
"InvalidBlockActions": `{"type":"block_actions","actions":"open"}`,
} {
t.Run(name, func(t *testing.T) {
t.Parallel()
got, ok, err := slackapi.ParseBlockActions([]byte(payload))
if got != nil || ok || err == nil {
t.Fatalf("ParseBlockActions = %+v, %v, %v, want nil, false, an error", got, ok, err)
}
})
}
}
2 changes: 2 additions & 0 deletions adapters/slack/slackapi/manifest.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,8 @@ type ManifestOAuthConfig struct {
type ManifestScopes struct {
// Bot is the list of bot token scopes, such as "chat:write".
Bot []string `json:"bot,omitempty"`
// User is the list of user token scopes, such as "openid".
User []string `json:"user,omitempty"`
}

// ManifestSettings is the settings section of a Manifest. The three flags
Expand Down
7 changes: 5 additions & 2 deletions adapters/slack/slackapi/manifest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const formatsManifestJSON = `{
},
"oauth_config": {
"redirect_urls": ["https://coder.example.com/api/v2/slack/callback"],
"scopes": {"bot": ["app_mentions:read", "chat:write", "users:read"]}
"scopes": {"bot": ["app_mentions:read", "chat:write", "users:read"], "user": ["openid"]}
},
"settings": {
"event_subscriptions": {
Expand Down Expand Up @@ -58,7 +58,10 @@ func formatsManifest() slackapi.Manifest {
},
OAuthConfig: &slackapi.ManifestOAuthConfig{
RedirectURLs: []string{"https://coder.example.com/api/v2/slack/callback"},
Scopes: &slackapi.ManifestScopes{Bot: []string{"app_mentions:read", "chat:write", "users:read"}},
Scopes: &slackapi.ManifestScopes{
Bot: []string{"app_mentions:read", "chat:write", "users:read"},
User: []string{"openid"},
},
},
Settings: &slackapi.ManifestSettings{
EventSubscriptions: &slackapi.ManifestEventSubscriptions{
Expand Down
Loading
Loading