mirror of
https://github.com/Sea-Haven-Industries/open-swe.git
synced 2026-09-30 10:23:14 +00:00
* feat: open Slack-triggered PRs as the triggering user Route the Slack per-user GitHub token through the dashboard OAuth store (the backend the self-service link prompt populates) and block runs that lack a valid user token, prompting the user to (re-)link. Per-user OAuth now wins over bot-token-only mode for mapped Slack/dashboard users. Flip commit/PR authorship across all sources: the triggering user is the commit author (via repo-local git identity using their resolvable GitHub noreply email) and open-swe[bot] is the Co-authored-by collaborator. * fix: address PR review — shell-escape commit identity, fix token cache impersonation - Shell-escape the triggering user's name/email with shlex.quote before embedding them in the repo-setup `git config` command, so a name like O'Connor (or a crafted one) can't break or inject into the command. - Stop consulting the shared thread-metadata token cache in _resolve_dashboard_user_token. Slack thread ids are shared across the conversation, so a cached token from a prior triggering user could be returned for the current github_login. Always resolve by login from the dashboard OAuth store instead. * feat: dashboard self-service user mapping + UI cleanup - Add session-scoped GET/PUT /dashboard/api/my-mapping so users can set their own work email / Slack member ID (keyed by their GitHub login, source=self). - Slack account-link prompt now redirects to Profile Settings after auth. - Rename "My Settings" -> "Profile Settings" and "Cloud Agents" -> "Open SWE Agent"; remove the Integrations tab/section (folded out, low value for now) and redirect /integrations to Profile Settings. - Add a "User mapping" section to Profile Settings (work email used by Slack and Linear, optional Slack member ID). - Make dashboard auth cookies scheme-aware: Secure;SameSite=None over HTTPS, non-Secure;SameSite=Lax over http://localhost so local login works. * feat: self-service Slack account linking via Sign in with Slack (OIDC) Replace the spoofable manual work-email/Slack-ID form with a verified "Sign in with Slack" flow so a logged-in GitHub user can only ever link their own Slack identity. - New agent/dashboard/slack_oauth.py: OIDC authorize URL, code exchange, userInfo identity parse, optional workspace gate, configured check. - routes.py: session-gated GET /slack/login and /slack/callback that upsert the mapping from Slack-verified user_id + email (source=slack_oauth). Remove the spoofable PUT /my-mapping; expose slack_oauth_enabled on /me. - UI: drop the editable inputs; add a Connect Slack button + status to the User mapping section. Admin-managed mappings are unaffected and still resolve at trigger time.
117 lines
4.2 KiB
Python
117 lines
4.2 KiB
Python
"""Sign in with Slack (OpenID Connect) for self-service GitHub ⇄ Slack linking.
|
|
|
|
Reuses the existing Slack app — Sign in with Slack is a capability on the same
|
|
app that owns the bot token, so it only needs the ``openid email profile`` user
|
|
scopes, a redirect URL, and the app's client id/secret. The id_token/userInfo
|
|
claims give us a Slack-*verified* member id and email, so a logged-in GitHub
|
|
user can only ever link their own Slack identity (no self-asserted spoofing).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import os
|
|
from dataclasses import dataclass
|
|
from typing import Any
|
|
from urllib.parse import urlencode
|
|
|
|
import httpx
|
|
from fastapi import HTTPException
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
SLACK_CLIENT_ID = os.environ.get("SLACK_CLIENT_ID", "")
|
|
SLACK_CLIENT_SECRET = os.environ.get("SLACK_CLIENT_SECRET", "")
|
|
# Optional: restrict linking to a single workspace (the Slack team id, T...).
|
|
SLACK_TEAM_ID = os.environ.get("SLACK_TEAM_ID", "")
|
|
|
|
SLACK_STATE_COOKIE_NAME = "osw_slack_oauth_state"
|
|
SLACK_OIDC_SCOPES = "openid email profile"
|
|
|
|
_AUTHORIZE_URL = "https://slack.com/openid/connect/authorize"
|
|
_TOKEN_URL = "https://slack.com/api/openid.connect.token"
|
|
_USERINFO_URL = "https://slack.com/api/openid.connect.userInfo"
|
|
_USER_ID_CLAIM = "https://slack.com/user_id"
|
|
_TEAM_ID_CLAIM = "https://slack.com/team_id"
|
|
|
|
|
|
def slack_oauth_configured() -> bool:
|
|
return bool(SLACK_CLIENT_ID and SLACK_CLIENT_SECRET)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class SlackIdentity:
|
|
user_id: str
|
|
team_id: str
|
|
email: str | None
|
|
email_verified: bool
|
|
name: str | None
|
|
|
|
|
|
def build_authorize_url(*, redirect_uri: str, state: str) -> str:
|
|
params = {
|
|
"response_type": "code",
|
|
"scope": SLACK_OIDC_SCOPES,
|
|
"client_id": SLACK_CLIENT_ID,
|
|
"redirect_uri": redirect_uri,
|
|
"state": state,
|
|
}
|
|
if SLACK_TEAM_ID:
|
|
# Pre-selects the workspace so users can't accidentally sign in elsewhere.
|
|
params["team"] = SLACK_TEAM_ID
|
|
return f"{_AUTHORIZE_URL}?{urlencode(params)}"
|
|
|
|
|
|
def parse_slack_identity(data: dict[str, Any]) -> SlackIdentity:
|
|
"""Build a SlackIdentity from an openid.connect.userInfo response."""
|
|
if not data.get("ok", True):
|
|
raise HTTPException(400, f"slack userinfo failed: {data.get('error', 'unknown')}")
|
|
user_id = data.get(_USER_ID_CLAIM)
|
|
if not isinstance(user_id, str) or not user_id:
|
|
raise HTTPException(400, "slack userinfo missing user id")
|
|
team_id = data.get(_TEAM_ID_CLAIM)
|
|
email = data.get("email")
|
|
return SlackIdentity(
|
|
user_id=user_id,
|
|
team_id=team_id if isinstance(team_id, str) else "",
|
|
email=email if isinstance(email, str) and email else None,
|
|
email_verified=bool(data.get("email_verified")),
|
|
name=data.get("name") if isinstance(data.get("name"), str) else None,
|
|
)
|
|
|
|
|
|
def verify_team(identity: SlackIdentity) -> None:
|
|
"""Reject identities from a different workspace when one is configured."""
|
|
if SLACK_TEAM_ID and identity.team_id != SLACK_TEAM_ID:
|
|
raise HTTPException(403, "Slack account is not in the authorized workspace")
|
|
|
|
|
|
async def exchange_slack_code(code: str, redirect_uri: str) -> str:
|
|
"""Exchange an authorization code for a user access token."""
|
|
async with httpx.AsyncClient() as client:
|
|
resp = await client.post(
|
|
_TOKEN_URL,
|
|
data={
|
|
"client_id": SLACK_CLIENT_ID,
|
|
"client_secret": SLACK_CLIENT_SECRET,
|
|
"code": code,
|
|
"grant_type": "authorization_code",
|
|
"redirect_uri": redirect_uri,
|
|
},
|
|
)
|
|
resp.raise_for_status()
|
|
data = resp.json()
|
|
if not data.get("ok") or not data.get("access_token"):
|
|
raise HTTPException(400, f"slack oauth exchange failed: {data.get('error', 'unknown')}")
|
|
return data["access_token"]
|
|
|
|
|
|
async def fetch_slack_identity(access_token: str) -> SlackIdentity:
|
|
"""Resolve the signed-in Slack user's verified identity."""
|
|
async with httpx.AsyncClient() as client:
|
|
resp = await client.get(
|
|
_USERINFO_URL,
|
|
headers={"Authorization": f"Bearer {access_token}"},
|
|
)
|
|
resp.raise_for_status()
|
|
return parse_slack_identity(resp.json())
|