diff --git a/adapters/slack/slackapi/README.md b/adapters/slack/slackapi/README.md index 1ea41d9..1bf2897 100644 --- a/adapters/slack/slackapi/README.md +++ b/adapters/slack/slackapi/README.md @@ -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] @@ -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] | @@ -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 @@ -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] @@ -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] diff --git a/adapters/slack/slackapi/blocks.go b/adapters/slack/slackapi/blocks.go index 3770c89..5175b1d 100644 --- a/adapters/slack/slackapi/blocks.go +++ b/adapters/slack/slackapi/blocks.go @@ -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 @@ -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, }) } diff --git a/adapters/slack/slackapi/blocks_test.go b/adapters/slack/slackapi/blocks_test.go index 7bdef50..601d2a2 100644 --- a/adapters/slack/slackapi/blocks_test.go +++ b/adapters/slack/slackapi/blocks_test.go @@ -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", diff --git a/adapters/slack/slackapi/form_test.go b/adapters/slack/slackapi/form_test.go index b66cca9..f846dba 100644 --- a/adapters/slack/slackapi/form_test.go +++ b/adapters/slack/slackapi/form_test.go @@ -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{}) }}, diff --git a/adapters/slack/slackapi/interaction.go b/adapters/slack/slackapi/interaction.go new file mode 100644 index 0000000..b1561d4 --- /dev/null +++ b/adapters/slack/slackapi/interaction.go @@ -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"` + // 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"` + // 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 +} diff --git a/adapters/slack/slackapi/interaction_test.go b/adapters/slack/slackapi/interaction_test.go new file mode 100644 index 0000000..96f19e9 --- /dev/null +++ b/adapters/slack/slackapi/interaction_test.go @@ -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) + } + }) + } +} diff --git a/adapters/slack/slackapi/manifest.go b/adapters/slack/slackapi/manifest.go index 1e40208..4a18c56 100644 --- a/adapters/slack/slackapi/manifest.go +++ b/adapters/slack/slackapi/manifest.go @@ -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 diff --git a/adapters/slack/slackapi/manifest_test.go b/adapters/slack/slackapi/manifest_test.go index c77c4ff..d7869b4 100644 --- a/adapters/slack/slackapi/manifest_test.go +++ b/adapters/slack/slackapi/manifest_test.go @@ -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": { @@ -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{ diff --git a/adapters/slack/slackapi/openid.go b/adapters/slack/slackapi/openid.go new file mode 100644 index 0000000..3bd964e --- /dev/null +++ b/adapters/slack/slackapi/openid.go @@ -0,0 +1,127 @@ +package slackapi + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net/url" + "strings" +) + +// OpenIDConnectTokenRequest is the request of openid.connect.token. +type OpenIDConnectTokenRequest struct { + // ClientID is the OAuth client ID of the app. + ClientID string + // ClientSecret is the OAuth client secret of the app. + ClientSecret string + // Code is the code that Slack sent to the redirect URL of the app. + Code string + // RedirectURI is the redirect_uri of the authorize request. Slack requires + // it when the authorize request had one. Empty sends none. + RedirectURI string +} + +// OpenIDConnectTokenResponse is the response of openid.connect.token for a +// Sign in with Slack login. +type OpenIDConnectTokenResponse struct { + // AccessToken is the user token (xoxp-). + AccessToken string `json:"access_token"` + // TokenType is "Bearer". + TokenType string `json:"token_type"` + // IDToken is the ID token, a JWT, exactly as Slack sent it. + IDToken string `json:"id_token"` + // RefreshToken refreshes AccessToken when the app has token rotation on. + // It is empty otherwise. + RefreshToken string `json:"refresh_token"` + // ExpiresIn is the lifetime of AccessToken in seconds when the app has + // token rotation on. It is zero otherwise. + ExpiresIn int `json:"expires_in"` + // Claims is the decoded payload of IDToken. + Claims IDTokenClaims `json:"-"` +} + +// IDTokenClaims are the claims of a Sign in with Slack ID token that the +// openid scope gives. +type IDTokenClaims struct { + // Issuer is the issuer, "https://slack.com" for slack.com. + Issuer string `json:"iss"` + // Subject is the ID of the user who signed in. + Subject string `json:"sub"` + // Audience is the client ID of the app that the token is for. + Audience string `json:"aud"` + // ExpiresAt is the expiry time of the token in Unix seconds. + ExpiresAt int64 `json:"exp"` + // IssuedAt is the time that Slack issued the token in Unix seconds. + IssuedAt int64 `json:"iat"` + // AuthTime is the time that the user signed in in Unix seconds. + AuthTime int64 `json:"auth_time"` + // Nonce is the nonce of the authorize request. It is empty when the + // authorize request had none. + Nonce string `json:"nonce"` + // TeamID is the ID of the workspace that the user signed in to. + TeamID string `json:"https://slack.com/team_id"` + // UserID is the ID of the user who signed in. + UserID string `json:"https://slack.com/user_id"` +} + +// OpenIDConnectToken calls openid.connect.token to exchange the code of a Sign +// in with Slack login for a user token and an ID token. It sends the client ID +// and the client secret in a form-encoded body, and never sends the token of +// c, so any Client can call it. It decodes the payload of the ID token into +// Claims, and returns an error when the ID token is missing or malformed, when +// its audience is not req.ClientID, or when it has no team ID or user ID. +// +// It does not check the signature of the ID token, because the token comes +// straight from Slack over TLS. OpenID Connect Core 1.0 section 3.1.3.7 allows +// this for the signature only. The same section requires checks of the issuer, +// the expiry, and the nonce when the authorize request sent one. +// OpenIDConnectToken does none of them, so the caller must check +// Claims.Issuer, Claims.ExpiresAt, and Claims.Nonce. +func (c *Client) OpenIDConnectToken(ctx context.Context, req OpenIDConnectTokenRequest) (*OpenIDConnectTokenResponse, error) { + values := url.Values{} + setFormString(values, "client_id", req.ClientID) + setFormString(values, "client_secret", req.ClientSecret) + setFormString(values, "code", req.Code) + setFormString(values, "redirect_uri", req.RedirectURI) + var resp OpenIDConnectTokenResponse + if err := c.WithToken("").Call(ctx, "openid.connect.token", values, &resp); err != nil { + return nil, err + } + claims, err := parseIDToken(resp.IDToken, req.ClientID) + if err != nil { + return nil, fmt.Errorf("slack: openid.connect.token: %w", err) + } + resp.Claims = claims + return &resp, nil +} + +// parseIDToken decodes the payload of the ID token and checks its audience, +// team ID, and user ID. It does not check the signature. +func parseIDToken(token, clientID string) (IDTokenClaims, error) { + var claims IDTokenClaims + if token == "" { + return claims, errors.New("id_token is missing") + } + parts := strings.Split(token, ".") + if len(parts) != 3 { + return claims, errors.New("id_token is not a JWT") + } + payload, err := base64.RawURLEncoding.DecodeString(parts[1]) + if err != nil { + return claims, fmt.Errorf("invalid id_token payload: %w", err) + } + if err := json.Unmarshal(payload, &claims); err != nil { + return claims, fmt.Errorf("invalid id_token claims: %w", err) + } + switch { + case claims.Audience != clientID: + return claims, fmt.Errorf("id_token audience %q is not the client ID %q", claims.Audience, clientID) + case claims.TeamID == "": + return claims, errors.New("id_token has no team ID") + case claims.UserID == "": + return claims, errors.New("id_token has no user ID") + } + return claims, nil +} diff --git a/adapters/slack/slackapi/openid_test.go b/adapters/slack/slackapi/openid_test.go new file mode 100644 index 0000000..438a844 --- /dev/null +++ b/adapters/slack/slackapi/openid_test.go @@ -0,0 +1,131 @@ +package slackapi_test + +import ( + "encoding/base64" + "encoding/json" + "net/url" + "strings" + "testing" + + "github.com/coder/chat/adapters/slack/slackapi" + "github.com/coder/chat/adapters/slack/slackapi/slackapitest" +) + +// openIDToken returns a JWT with claims as its payload and a fake signature. +func openIDToken(claims string) string { + return "eyJhbGciOiJSUzI1NiJ9." + base64.RawURLEncoding.EncodeToString([]byte(claims)) + ".signature" +} + +func TestOpenIDConnectToken(t *testing.T) { + t.Parallel() + + request := slackapi.OpenIDConnectTokenRequest{ + ClientID: "123.456", + ClientSecret: "client-secret", + Code: "login-code", + RedirectURI: "https://coder.example.com/callback", + } + + t.Run("Request", func(t *testing.T) { + t.Parallel() + // The run of "~" in the nonce encodes to "-", which only base64url + // has, as in a real ID token. + idToken := openIDToken(`{ + "iss": "https://slack.com", + "sub": "U0USER", + "aud": "123.456", + "exp": 1700000300, + "iat": 1700000000, + "auth_time": 1699999990, + "nonce": "login-nonce~~~~~", + "at_hash": "abc", + "https://slack.com/team_id": "T0TEAM", + "https://slack.com/user_id": "U0USER" + }`) + srv := slackapitest.NewServer(t) + srv.Respond("openid.connect.token", json.RawMessage(`{ + "ok": true, + "access_token": "xoxp-user", + "token_type": "Bearer", + "id_token": "`+idToken+`", + "refresh_token": "xoxe-1-refresh", + "expires_in": 43200 + }`)) + + resp, err := methodsNewClient(srv).OpenIDConnectToken(t.Context(), request) + if err != nil { + t.Fatalf("OpenIDConnectToken: %v", err) + } + calls := srv.Calls("openid.connect.token") + if len(calls) != 1 { + t.Fatalf("openid.connect.token calls = %d, want 1", len(calls)) + } + if got := calls[0].Header.Get("Authorization"); got != "" { + t.Errorf("Authorization = %q, want none", got) + } + methodsCheckEqual(t, "form", calls[0].Form, url.Values{ + "client_id": {"123.456"}, + "client_secret": {"client-secret"}, + "code": {"login-code"}, + "redirect_uri": {"https://coder.example.com/callback"}, + }) + methodsCheckEqual(t, "response", resp, &slackapi.OpenIDConnectTokenResponse{ + AccessToken: "xoxp-user", + TokenType: "Bearer", + IDToken: idToken, + RefreshToken: "xoxe-1-refresh", + ExpiresIn: 43200, + Claims: slackapi.IDTokenClaims{ + Issuer: "https://slack.com", + Subject: "U0USER", + Audience: "123.456", + ExpiresAt: 1700000300, + IssuedAt: 1700000000, + AuthTime: 1699999990, + Nonce: "login-nonce~~~~~", + TeamID: "T0TEAM", + UserID: "U0USER", + }, + }) + }) + + t.Run("InvalidIDToken", func(t *testing.T) { + t.Parallel() + tests := []struct { + name string + idToken string + want string + }{ + {"Missing", "", "id_token is missing"}, + {"NotThreeParts", "header.payload", "id_token is not a JWT"}, + {"BadBase64", "header.!!!.signature", "invalid id_token payload"}, + {"BadJSON", openIDToken(`not json`), "invalid id_token claims"}, + { + "OtherAudience", + openIDToken(`{"aud":"999.999","https://slack.com/team_id":"T0TEAM","https://slack.com/user_id":"U0USER"}`), + `id_token audience "999.999" is not the client ID "123.456"`, + }, + {"NoTeamID", openIDToken(`{"aud":"123.456","https://slack.com/user_id":"U0USER"}`), "id_token has no team ID"}, + {"NoUserID", openIDToken(`{"aud":"123.456","https://slack.com/team_id":"T0TEAM"}`), "id_token has no user ID"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + body, err := json.Marshal(map[string]any{"ok": true, "access_token": "xoxp-user", "id_token": tt.idToken}) + if err != nil { + t.Fatalf("json.Marshal: %v", err) + } + srv := slackapitest.NewServer(t) + srv.Respond("openid.connect.token", json.RawMessage(body)) + + resp, err := methodsNewClient(srv).OpenIDConnectToken(t.Context(), request) + if resp != nil { + t.Errorf("response = %+v, want nil", resp) + } + if want := "slack: openid.connect.token: " + tt.want; err == nil || !strings.HasPrefix(err.Error(), want) { + t.Fatalf("error = %v, want prefix %q", err, want) + } + }) + } + }) +} diff --git a/docs/reference.md b/docs/reference.md index 8ca88f5..4c395de 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -734,6 +734,7 @@ The client methods and how each one sends its request: | `Call` | any Web API method (the escape hatch) | form for a `url.Values` payload, else JSON | | `PostResponseURL` | the `response_url` of a command or an interaction | JSON, no token | | `OAuthV2Access` | `oauth.v2.access` | form with the client ID and the client secret, no token | +| `OpenIDConnectToken` | `openid.connect.token` | form with the client ID and the client secret, no token; returns the ID token claims with the Slack team ID and user ID. It 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) | | `CreateApp`, `DeleteApp` | `apps.manifest.create`, `apps.manifest.delete` | form, with an app configuration token; `CreateApp` sends the `Manifest` as a JSON string | Requests are POSTs with the bearer token unless the table says otherwise. @@ -783,6 +784,13 @@ Inbound deliveries: `DeliverySlashCommands`, or `DeliveryInteractive`), the JSON `Payload`, and `RetryAttempt` and `RetryReason` for a redelivery. It is the same for both transports. A slash command payload is a JSON object of strings over both. + `ParseBlockActions(payload)` decodes a `DeliveryInteractive` payload of type + `block_actions` (a button click), and returns false for other interaction + types. 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, such as `view`, `selected_option`, or `enterprise`, from the raw + payload. - A `Handler` handles a `Delivery` and gives the acknowledgement. A nil error acknowledges the delivery, and a non-nil response is the acknowledgement body, encoded as JSON. An error does not acknowledge it: