Skip to content
Draft
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: 8 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,11 @@ updates:
default-days: 7
exclude:
- "slack*"
- package-ecosystem: "pip"
directory: "standardized-auth"
schedule:
interval: "daily"
cooldown:
default-days: 7
exclude:
- "slack*"
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ jobs:
- "ai/slackbot-mcp-client/slack-identity"
- "block-kit"
- "methods"
- "standardized-auth"
defaults:
run:
working-directory: ${{ matrix.showcase }}
Expand Down Expand Up @@ -53,6 +54,7 @@ jobs:
- "ai/slackbot-mcp-client/slack-identity"
- "block-kit"
- "methods"
- "standardized-auth"
defaults:
run:
working-directory: ${{ matrix.showcase }}
Expand Down Expand Up @@ -82,6 +84,7 @@ jobs:
- "ai/slackbot-mcp-client/rich-responses/mcp-apps"
- "ai/slackbot-mcp-client/slack-identity"
- "block-kit"
- "standardized-auth"
defaults:
run:
working-directory: ${{ matrix.showcase }}
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ This collections of examples highlights features of a Slack app in the language
- **[AI in Slack](./ai)**: Agent experiences and MCP features in an interactive conversation interface.
- **[Block Kit](./block-kit)**: The framework of visual components arranged to create app layouts.
- **[Methods](./methods)**: An interface for querying information from and enacting change in a Slack workspace.
- **[Standardized Auth](./standardized-auth)**: Connect user accounts with the Slack-owned Connect and Manage connection controls.
5 changes: 5 additions & 0 deletions standardized-auth/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
SLACK_CLIENT_ID=
SLACK_CLIENT_SECRET=
SLACK_SIGNING_SECRET=
BASE_URL=https://1234-56-78-90-0.ngrok-free.app
PORT=3000
5 changes: 5 additions & 0 deletions standardized-auth/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
__pycache__
.venv
.env*
!.env.example
data/
2 changes: 2 additions & 0 deletions standardized-auth/.slack/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
apps.dev.json
cache/
6 changes: 6 additions & 0 deletions standardized-auth/.slack/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"manifest": {
"source": "local"
},
"project_id": "00000000-0000-0000-0000-000000000000"
}
5 changes: 5 additions & 0 deletions standardized-auth/.slack/hooks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"hooks": {
"get-hooks": "python3 -m slack_cli_hooks.hooks.get_hooks"
}
}
31 changes: 31 additions & 0 deletions standardized-auth/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Standardized Auth

Connect your Acme account to Slack with the Slack-owned **Connect** and **Manage connection** controls. Rocket skates, anvils, and giant magnets not included.

Read the docs: https://docs.slack.dev/authentication/standardized-auth

## How it works

Acme keeps every connection in Bolt's installation store: a user is connected when the store holds their user token.

- **Connect** opens `/slack/install`. When the OAuth flow saves the user's token, the app reports the connection with `apps.user.connection.requestAuth` and refreshes App Home.
- **Disconnect** forgets the user's token, reports the user as disconnected, then revokes the token.
- **`user_connection_status_requested`** answers with `apps.user.connection.update` whenever Slack asks about a user it doesn't know yet.
- **`tokens_revoked`** forgets users who remove Acme from their Slack settings and reports them as disconnected.
- **App Home** shows an `auth_provider` block with the user's current connection.

## Setup

```sh
$ ngrok http 3000 # Replace 1234-56-78-90-0.ngrok-free.app in manifest.json
$ slack install --environment local # Create a new app
$ slack app settings # Gather the client ID, client secret, and signing secret
$ slack env init # Update defaults with them and your ngrok URL
$ slack manifest # Validate fields
$ slack run
$ open https://1234-56-78-90-0.ngrok-free.app/slack/install # Install the app
```

Then open the app's **Home** tab and click **Connect**.

Swap the `users:read` and `users.profile:read` scopes for the ones your connection needs.
16 changes: 16 additions & 0 deletions standardized-auth/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import os

from slack_sdk.oauth.installation_store import FileInstallationStore
from slack_sdk.oauth.state_store.stateless import StatelessOAuthStateStore

from src.app import build_app

if __name__ == "__main__":
app = build_app(
installation_store=FileInstallationStore(base_dir="./data/installations"),
state_store=StatelessOAuthStateStore(
expiration_seconds=300, signing_secret=os.environ["SLACK_SIGNING_SECRET"]
),
base_url=os.environ["BASE_URL"],
)
app.start(port=int(os.environ.get("PORT", "3000")))
45 changes: 45 additions & 0 deletions standardized-auth/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
{
"display_information": {
"name": "Acme",
"description": "Rocket skates, anvils, and giant magnets for every plan",
"background_color": "#4A154B"
},
"features": {
"app_home": {
"home_tab_enabled": true,
"messages_tab_enabled": false
},
"bot_user": {
"display_name": "Acme",
"always_online": true
},
"user_connections": {
"is_enabled": true,
"auth_hosts": ["1234-56-78-90-0.ngrok-free.app"]
}
},
"oauth_config": {
"redirect_urls": ["https://1234-56-78-90-0.ngrok-free.app/slack/oauth_redirect"],
"scopes": {
"bot": ["users:read"],
"user": ["users.profile:read"]
}
},
"settings": {
"event_subscriptions": {
"request_url": "https://1234-56-78-90-0.ngrok-free.app/slack/events",
"bot_events": [
"app_home_opened",
"tokens_revoked",
"user_connection_status_requested"
]
},
"interactivity": {
"is_enabled": true,
"request_url": "https://1234-56-78-90-0.ngrok-free.app/slack/events"
},
"org_deploy_enabled": true,
"socket_mode_enabled": false,
"token_rotation_enabled": false
}
}
6 changes: 6 additions & 0 deletions standardized-auth/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
mypy==2.4.0
pytest==9.1.1
ruff==0.16.10
slack_bolt==1.30.0
slack_cli_hooks==0.3.0
slack_sdk @ git+https://github.com/slackapi/python-slack-sdk.git@699e1d1fe91effa4cb03bd0e3e8e5d88f43258b4
Empty file.
29 changes: 29 additions & 0 deletions standardized-auth/src/accounts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from slack_bolt import BoltContext
from slack_sdk.oauth.installation_store import Installation, InstallationStore


class AcmeAccounts:
def __init__(self, installation_store: InstallationStore):
self.installation_store = installation_store

def find(self, context: BoltContext, user_id: str) -> Installation | None:
installation = self.installation_store.find_installation(
enterprise_id=context.enterprise_id,
team_id=context.team_id,
user_id=user_id,
is_enterprise_install=context.is_enterprise_install,
)
if installation is None or installation.user_token is None:
return None
return installation

def forget(self, context: BoltContext, user_id: str) -> str | None:
account = self.find(context, user_id)
if account is None:
return None
self.installation_store.delete_installation(
enterprise_id=account.enterprise_id,
team_id=account.team_id,
user_id=user_id,
)
return account.user_token
57 changes: 57 additions & 0 deletions standardized-auth/src/acme.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
from dataclasses import dataclass
from typing import Any

from slack_sdk.models.blocks import AuthProviderBlock, MarkdownTextObject, SectionBlock
from slack_sdk.models.views import View

ACME_VALUE = "acme"
CONNECT_ACTION_ID = f"auth_provider_connect_{ACME_VALUE}"
DISCONNECT_ACTION_ID = f"auth_provider_disconnect_{ACME_VALUE}"

WELCOME_GREETING = (
"*Welcome to Acme!* :rocket:\n"
"Connect your Acme account to start ordering. "
"Anvils ship same day, gravity permitting."
)
CONNECTED_GREETING = (
"*You're all set!* :tada:\n"
"Your Acme account is connected. "
"Please keep giant magnets away from your laptop."
)


@dataclass(frozen=True)
class Connection:
identity: str
context: str


def plain_text(text: str) -> dict[str, str]:
return {"type": "plain_text", "text": text}


def acme_provider(auth_url: str, connection: Connection | None) -> dict[str, Any]:
provider: dict[str, Any] = {
"value": ACME_VALUE,
"name": plain_text("Acme account"),
"description": plain_text(
"Order rocket skates, anvils, and giant magnets without leaving Slack."
),
"auth_url": auth_url,
"is_connected": connection is not None,
}
if connection is not None:
provider["connected_identity"] = plain_text(connection.identity)
provider["connected_context"] = plain_text(connection.context)
return provider


def home_view(provider: dict[str, Any]) -> View:
greeting = CONNECTED_GREETING if provider["is_connected"] else WELCOME_GREETING
return View(
type="home",
blocks=[
SectionBlock(text=MarkdownTextObject(text=greeting)),
AuthProviderBlock(**provider),
],
)
41 changes: 41 additions & 0 deletions standardized-auth/src/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
from slack_bolt import App, BoltResponse
from slack_bolt.oauth.callback_options import CallbackOptions, FailureArgs
from slack_bolt.oauth.oauth_settings import OAuthSettings
from slack_sdk.oauth.installation_store import InstallationStore
from slack_sdk.oauth.state_store import OAuthStateStore

from src.accounts import AcmeAccounts
from src.acme import CONNECT_ACTION_ID, DISCONNECT_ACTION_ID
from src.listeners import AcmeListeners


def show_failure(args: FailureArgs) -> BoltResponse:
return args.default.failure(args)


def build_app(
installation_store: InstallationStore,
state_store: OAuthStateStore,
base_url: str,
) -> App:
listeners = AcmeListeners(
AcmeAccounts(installation_store), auth_url=f"{base_url}/slack/install"
)
app = App(
oauth_settings=OAuthSettings(
scopes=["users:read"],
user_scopes=["users.profile:read"],
install_page_rendering_enabled=False,
installation_store=installation_store,
state_store=state_store,
callback_options=CallbackOptions(
success=listeners.report_connected, failure=show_failure
),
),
)
app.event("app_home_opened")(listeners.publish_home)
app.event("user_connection_status_requested")(listeners.answer_status_request)
app.event("tokens_revoked")(listeners.forget_revoked_users)
app.action(CONNECT_ACTION_ID)(listeners.acknowledge_connect)
app.action(DISCONNECT_ACTION_ID)(listeners.acknowledge_disconnect)
return app
88 changes: 88 additions & 0 deletions standardized-auth/src/listeners.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
from slack_bolt import Ack, BoltContext, BoltResponse
from slack_bolt.oauth.callback_options import SuccessArgs
from slack_sdk import WebClient
from slack_sdk.oauth.installation_store import Installation

from src.accounts import AcmeAccounts
from src.acme import Connection, acme_provider, home_view


def connection_of(client: WebClient, account: Installation | None) -> Connection | None:
if account is None:
return None
identity = client.auth_test(token=account.user_token)
return Connection(identity=f"@{identity['user']}", context=identity["team"])


class AcmeListeners:
def __init__(self, accounts: AcmeAccounts, auth_url: str):
self.accounts = accounts
self.auth_url = auth_url

def report_connected(self, args: SuccessArgs) -> BoltResponse:
account = args.installation
client = WebClient(token=account.bot_token)
self.report(client, account.user_id, connection_of(client, account))
return args.default.success(args)

def publish_home(self, client: WebClient, context: BoltContext, event: dict):
account = self.accounts.find(context, event["user"])
provider = acme_provider(self.auth_url, connection_of(client, account))
client.views_publish(user_id=event["user"], view=home_view(provider))

def acknowledge_connect(self, ack: Ack):
ack()

def acknowledge_disconnect(
self, ack: Ack, body: dict, client: WebClient, context: BoltContext
):
ack()
self.disconnect(client, context, body["user"]["id"])

def answer_status_request(
self, client: WebClient, context: BoltContext, event: dict
):
account = self.accounts.find(context, event["user"])
status = "disconnected" if account is None else "connected"
client.apps_user_connection_update(user_id=event["user"], status=status)

def forget_revoked_users(
self, client: WebClient, context: BoltContext, event: dict
):
for user_id in event["tokens"].get("oauth", []):
self.accounts.forget(context, user_id)
self.report(client, user_id, None)

def handle_user_connection(
self, ack: Ack, body: dict, client: WebClient, context: BoltContext
):
ack()
user_id = body["user"]["id"]
if body["subtype"] == "connect":
self.open_connect_modal(client, context, user_id, body["trigger_id"])
elif body["subtype"] == "disconnect":
self.disconnect(client, context, user_id)

def open_connect_modal(
self, client: WebClient, context: BoltContext, user_id: str, trigger_id: str
):
account = self.accounts.find(context, user_id)
client.apps_user_connection_requestAuth(
trigger_id=trigger_id,
primary_provider=acme_provider(
self.auth_url, connection_of(client, account)
),
)

def disconnect(self, client: WebClient, context: BoltContext, user_id: str):
forgotten_token = self.accounts.forget(context, user_id)
self.report(client, user_id, None)
if forgotten_token is not None:
client.auth_revoke(token=forgotten_token)

def report(self, client: WebClient, user_id: str, connection: Connection | None):
provider = acme_provider(self.auth_url, connection)
client.apps_user_connection_requestAuth(
user_id=user_id, primary_provider=provider
)
client.views_publish(user_id=user_id, view=home_view(provider))
Empty file.
7 changes: 7 additions & 0 deletions standardized-auth/tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import pytest
from slack_sdk.oauth.installation_store import FileInstallationStore


@pytest.fixture
def store(tmp_path) -> FileInstallationStore:
return FileInstallationStore(base_dir=str(tmp_path / "installations"))
Loading
Loading