Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6056: verify GitHub installation control before workspace binding (#10705)

Bohan Jiang24ebdea7bed6
diff --git a/.env.example b/.env.example
index 664a632ddf..92f9b8fb99 100644
--- a/.env.example
+++ b/.env.example
@@ -575,14 +575,20 @@ CORS_ALLOWED_ORIGINS=
# `Authorization: Bearer <token>`.
# REALTIME_METRICS_TOKEN=
-# GitHub App integration (Settings → GitHub "Connect GitHub")
-# Both must be set for the Connect button to enable and for webhooks to be
-# accepted; leave empty to disable the integration. See docs/github-integration.
+# GitHub App integration (Settings → Code → GitHub)
+# Connect requires all six GitHub variables below, including the App ID/key.
+# Webhook acceptance requires only the webhook secret. See docs/github-integration.
# GITHUB_APP_SLUG is the tail of https://github.com/apps/<slug>.
GITHUB_APP_SLUG=
GITHUB_WEBHOOK_SECRET=
-# Optional for webhook-only deployments, but required for PR-card CI /
-# mergeability and Settings → Repositories → Choose from GitHub. These
+# App settings → Client ID / Client secrets (different from App ID/private key).
+# Enable "Request user authorization (OAuth) during installation" and set the
+# first Callback URL to https://<api-host>/api/github/setup before deploying.
+# New bindings are refused without GitHub user authorization.
+GITHUB_APP_CLIENT_ID=
+GITHUB_APP_CLIENT_SECRET=
+# Required for new connections (to verify organization-wide repository admin
+# rights), PR-card CI / mergeability, and Choose from GitHub. These
# credentials let the server authenticate as the App, mint short-lived
# installation tokens, and enrich the installation row with the real account
# login immediately.
diff --git a/apps/docs/content/docs/environment-variables.fr.mdx b/apps/docs/content/docs/environment-variables.fr.mdx
index a7e8e89abc..a96f20286e 100644
--- a/apps/docs/content/docs/environment-variables.fr.mdx
+++ b/apps/docs/content/docs/environment-variables.fr.mdx
@@ -185,8 +185,10 @@ Les limites de débit d'authentification nécessitent `REDIS_URL` ; sans cette v
|---|---|---|
| GitHub | `GITHUB_APP_SLUG` | Slug de la GitHub App |
| GitHub | `GITHUB_WEBHOOK_SECRET` | Secret de signature HMAC des webhooks et de l'état de connexion |
-| GitHub | `GITHUB_APP_ID` | Nécessaire pour le statut CI et la possibilité de fusion sur les cartes de PR, ainsi que pour le sélecteur de dépôts « Choisir depuis GitHub » |
-| GitHub | `GITHUB_APP_PRIVATE_KEY` | Clé privée PEM complète associée à l'App ID ; mêmes usages que ci-dessus |
+| GitHub | `GITHUB_APP_CLIENT_ID` | Client ID de l’App, requis pour vérifier que l’utilisateur peut accéder à l’installation |
+| GitHub | `GITHUB_APP_CLIENT_SECRET` | Client secret associé au Client ID, requis pour les nouvelles connexions |
+| GitHub | `GITHUB_APP_ID` | Requis pour vérifier le contrôle de l’installation lors des nouvelles connexions ; aussi utilisé par les cartes de PR et la liste des dépôts |
+| GitHub | `GITHUB_APP_PRIVATE_KEY` | Requis pour vérifier le contrôle de l’installation lors des nouvelles connexions ; aussi utilisé par les cartes de PR et la liste des dépôts |
| Lark | `MULTICA_LARK_SECRET_KEY` | Clé de chiffrement des identifiants de 32 octets, encodée en Base64 |
| Slack | `MULTICA_SLACK_SECRET_KEY` | Clé de chiffrement des jetons de 32 octets, encodée en Base64 |
| Telegram | `MULTICA_TELEGRAM_SECRET_KEY` | Clé de chiffrement du jeton du bot de 32 octets, encodée en Base64 |
diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdx
index 4e821a9749..620d53ec82 100644
--- a/apps/docs/content/docs/environment-variables.ja.mdx
+++ b/apps/docs/content/docs/environment-variables.ja.mdx
@@ -185,8 +185,10 @@ allowlist の正確な判定順序は[ログインとサインアップ](/auth-s
|---|---|---|
| GitHub | `GITHUB_APP_SLUG` | GitHub App の slug |
| GitHub | `GITHUB_WEBHOOK_SECRET` | Webhook HMAC と接続 state の署名シークレット |
-| GitHub | `GITHUB_APP_ID` | PR カードの CI ステータス・マージ可否と「GitHub から選択」リポジトリに必要です |
-| GitHub | `GITHUB_APP_PRIVATE_KEY` | App ID と対になる完全な PEM 秘密鍵。用途は同上 |
+| GitHub | `GITHUB_APP_CLIENT_ID` | App の Client ID。接続するユーザーが installation にアクセスできるか確認するために必須 |
+| GitHub | `GITHUB_APP_CLIENT_SECRET` | Client ID と対になる client secret。新規接続に必須 |
+| GitHub | `GITHUB_APP_ID` | 新規接続で installation の管理権限確認に必須。PR カードとリポジトリ一覧にも使用 |
+| GitHub | `GITHUB_APP_PRIVATE_KEY` | 新規接続で installation の管理権限確認に必須。PR カードとリポジトリ一覧にも使用 |
| Lark | `MULTICA_LARK_SECRET_KEY` | base64 エンコードされた 32 バイトの資格情報暗号化キー |
| Slack | `MULTICA_SLACK_SECRET_KEY` | base64 エンコードされた 32 バイトの token 暗号化キー |
| Telegram | `MULTICA_TELEGRAM_SECRET_KEY` | base64 エンコードされた 32 バイトの Bot token 暗号化キー |
diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdx
index f857b918d8..3ae7834b7a 100644
--- a/apps/docs/content/docs/environment-variables.ko.mdx
+++ b/apps/docs/content/docs/environment-variables.ko.mdx
@@ -185,8 +185,10 @@ reverse proxy 뒤에 배포한다면 실제 proxy 네트워크를 입력해야
|---|---|---|
| GitHub | `GITHUB_APP_SLUG` | GitHub App slug |
| GitHub | `GITHUB_WEBHOOK_SECRET` | Webhook HMAC 및 연결 state 서명 키 |
-| GitHub | `GITHUB_APP_ID` | PR 카드의 CI 상태, merge 가능 여부, "GitHub에서 선택" 저장소에 필요 |
-| GitHub | `GITHUB_APP_PRIVATE_KEY` | App ID와 짝을 이루는 전체 PEM private key. 용도는 위와 같음 |
+| GitHub | `GITHUB_APP_CLIENT_ID` | App Client ID. 연결하는 사용자의 installation 접근 권한을 확인하는 데 필수 |
+| GitHub | `GITHUB_APP_CLIENT_SECRET` | Client ID와 짝을 이루는 client secret. 새 연결에 필수 |
+| GitHub | `GITHUB_APP_ID` | 새 연결에서 installation 관리 권한을 확인하는 데 필수. PR 카드와 저장소 탐색에도 사용 |
+| GitHub | `GITHUB_APP_PRIVATE_KEY` | 새 연결에서 installation 관리 권한을 확인하는 데 필수. PR 카드와 저장소 탐색에도 사용 |
| Feishu | `MULTICA_LARK_SECRET_KEY` | base64로 인코딩한 32바이트 자격 증명 암호화 키 |
| Slack | `MULTICA_SLACK_SECRET_KEY` | base64로 인코딩한 32바이트 token 암호화 키 |
| Telegram | `MULTICA_TELEGRAM_SECRET_KEY` | base64로 인코딩한 32바이트 Bot token 암호화 키 |
diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdx
index 7f8fe84eff..661d72f500 100644
--- a/apps/docs/content/docs/environment-variables.mdx
+++ b/apps/docs/content/docs/environment-variables.mdx
@@ -185,8 +185,10 @@ The auth rate limits require `REDIS_URL`; without it, the startup log notes that
|---|---|---|
| GitHub | `GITHUB_APP_SLUG` | GitHub App slug |
| GitHub | `GITHUB_WEBHOOK_SECRET` | Webhook HMAC and connect-state signing secret |
-| GitHub | `GITHUB_APP_ID` | Needed for CI status and mergeability on PR cards and the "pick from GitHub" repository picker |
-| GitHub | `GITHUB_APP_PRIVATE_KEY` | Full PEM private key paired with the App ID; same uses as above |
+| GitHub | `GITHUB_APP_CLIENT_ID` | App Client ID. Required to verify the connecting user can access the installation |
+| GitHub | `GITHUB_APP_CLIENT_SECRET` | Client secret paired with the Client ID; required for new connections |
+| GitHub | `GITHUB_APP_ID` | Required for new connections to verify installation control; also used by PR cards and repository browsing |
+| GitHub | `GITHUB_APP_PRIVATE_KEY` | Required for new connections to verify installation control; also used by PR cards and repository browsing |
| Lark | `MULTICA_LARK_SECRET_KEY` | Base64-encoded 32-byte credential encryption key |
| Slack | `MULTICA_SLACK_SECRET_KEY` | Base64-encoded 32-byte token encryption key |
| Telegram | `MULTICA_TELEGRAM_SECRET_KEY` | Base64-encoded 32-byte Bot token encryption key |
diff --git a/apps/docs/content/docs/environment-variables.zh-Hant.mdx b/apps/docs/content/docs/environment-variables.zh-Hant.mdx
index ef94144fd2..bbe5f09a72 100644
--- a/apps/docs/content/docs/environment-variables.zh-Hant.mdx
+++ b/apps/docs/content/docs/environment-variables.zh-Hant.mdx
@@ -181,8 +181,10 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
|---|---|---|
| GitHub | `GITHUB_APP_SLUG` | GitHub App slug |
| GitHub | `GITHUB_WEBHOOK_SECRET` | Webhook HMAC 與連線 state 簽名金鑰 |
-| GitHub | `GITHUB_APP_ID` | PR 卡片的 CI 狀態、可合併性和"從 GitHub 選擇"倉庫都需要它 |
-| GitHub | `GITHUB_APP_PRIVATE_KEY` | 與 App ID 配套的完整 PEM 私鑰,用途同上 |
+| GitHub | `GITHUB_APP_CLIENT_ID` | App 的 Client ID。新連線必需,用於驗證操作者能否存取該 installation |
+| GitHub | `GITHUB_APP_CLIENT_SECRET` | 與 Client ID 配對的 client secret,新連線必需 |
+| GitHub | `GITHUB_APP_ID` | 新連線必需,用於驗證安裝管理權限;也用於 PR 卡片和倉庫瀏覽 |
+| GitHub | `GITHUB_APP_PRIVATE_KEY` | 新連線必需,用於驗證安裝管理權限;也用於 PR 卡片和倉庫瀏覽 |
| 飛書 | `MULTICA_LARK_SECRET_KEY` | base64 編碼的 32 位元組憑據加密金鑰 |
| Slack | `MULTICA_SLACK_SECRET_KEY` | base64 編碼的 32 位元組 token 加密金鑰 |
| Telegram | `MULTICA_TELEGRAM_SECRET_KEY` | base64 編碼的 32 位元組 Bot token 加密金鑰 |
diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdx
index 6525838efb..3f2758ebaa 100644
--- a/apps/docs/content/docs/environment-variables.zh.mdx
+++ b/apps/docs/content/docs/environment-variables.zh.mdx
@@ -185,8 +185,10 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
|---|---|---|
| GitHub | `GITHUB_APP_SLUG` | GitHub App slug |
| GitHub | `GITHUB_WEBHOOK_SECRET` | Webhook HMAC 与连接 state 签名密钥 |
-| GitHub | `GITHUB_APP_ID` | PR 卡片的 CI 状态、可合并性和"从 GitHub 选择"仓库都需要它 |
-| GitHub | `GITHUB_APP_PRIVATE_KEY` | 与 App ID 配套的完整 PEM 私钥,用途同上 |
+| GitHub | `GITHUB_APP_CLIENT_ID` | App 的 Client ID。新连接必需,用于校验操作者能否访问该 installation |
+| GitHub | `GITHUB_APP_CLIENT_SECRET` | 与 Client ID 配对的 client secret,新连接必需 |
+| GitHub | `GITHUB_APP_ID` | 新连接必需,用于验证安装管理权限;也用于 PR 卡片和仓库浏览 |
+| GitHub | `GITHUB_APP_PRIVATE_KEY` | 新连接必需,用于验证安装管理权限;也用于 PR 卡片和仓库浏览 |
| 飞书 | `MULTICA_LARK_SECRET_KEY` | base64 编码的 32 字节凭据加密密钥 |
| Slack | `MULTICA_SLACK_SECRET_KEY` | base64 编码的 32 字节 token 加密密钥 |
| Telegram | `MULTICA_TELEGRAM_SECRET_KEY` | base64 编码的 32 字节 Bot token 加密密钥 |
diff --git a/apps/docs/content/docs/github-integration.fr.mdx b/apps/docs/content/docs/github-integration.fr.mdx
index 1fe5783235..4a9c8a363a 100644
--- a/apps/docs/content/docs/github-integration.fr.mdx
+++ b/apps/docs/content/docs/github-integration.fr.mdx
@@ -17,6 +17,8 @@ Multica auto-hébergé peut aussi connecter en parallèle des instances Forgejo,
Un propriétaire ou un administrateur de l'espace de travail peut effectuer la connexion :
+Une nouvelle connexion exige aussi le contrôle de l’installation GitHub : une installation personnelle doit appartenir à l’utilisateur qui autorise l’App ; une installation d’organisation exige la permission admin sur chaque dépôt couvert. Un accès en lecture seule ou partiel ne suffit pas. Sélectionnez au moins un dépôt pour une installation d’organisation.
+
<Steps>
<Step>
Ouvrez **Paramètres → Code**.
@@ -139,8 +141,8 @@ Créez l'App dans **Developer settings → GitHub Apps** sur GitHub et renseigne
| Champ | Valeur |
|---|---|
| Homepage URL | L'adresse de votre frontend Multica, par ex. `https://multica.example.com` |
-| Callback URL | Laisser vide |
-| Setup URL | `https://<api-host>/api/github/setup`, avec **Redirect on update** activé |
+| Callback URL | `https://<api-host>/api/github/setup` |
+| Request user authorization (OAuth) during installation | Activer |
| Webhook URL | `https://<api-host>/api/webhooks/github` |
| Webhook secret | Une chaîne aléatoire que vous conservez durablement |
@@ -175,19 +177,21 @@ Récupérez le slug dans l'URL publique de l'App. Par exemple, le slug de `https
```dotenv
GITHUB_APP_SLUG=multica-acme
GITHUB_WEBHOOK_SECRET=<the webhook secret you entered when creating the App>
+GITHUB_APP_CLIENT_ID=<Client ID>
+GITHUB_APP_CLIENT_SECRET=<Client secret>
FRONTEND_ORIGIN=https://multica.example.com
```
-Si `GITHUB_APP_SLUG` ou `GITHUB_WEBHOOK_SECRET` manque, le bouton de connexion est désactivé et le point de terminaison du webhook refuse de traiter les événements.
+Les six variables GitHub de cette section sont requises pour les nouvelles connexions, y compris `GITHUB_APP_ID` et `GITHUB_APP_PRIVATE_KEY`. Si une variable manque, la connexion est désactivée ; la réception des webhooks exige seulement `GITHUB_WEBHOOK_SECRET`. Les connexions existantes continuent de fonctionner. Avant le déploiement, définissez la première Callback URL sur cet endpoint et activez OAuth lors de l’installation. GitHub n’utilise alors pas de Setup URL distincte.
-Pour que la carte de PR affiche le statut CI et la possibilité de fusion, définissez aussi les deux variables suivantes. Multica s'en sert pour s'authentifier en tant qu'App et récupérer les instantanés :
+Pour les nouvelles connexions, le statut CI et la possibilité de fusion des PR, définissez aussi les deux variables suivantes. Multica compare la liste complète des dépôts de l’installation, obtenue avec un jeton metadata en lecture seule, aux dépôts administrés par l’utilisateur :
```dotenv
GITHUB_APP_ID=<the GitHub App's numeric ID>
GITHUB_APP_PRIVATE_KEY=<full PEM private key, keeping the BEGIN/END lines and newlines>
```
-Générez la clé privée dans **Private keys → Generate a private key** de la GitHub App. Sans ces deux variables, les PR sont toujours reflétées et les tâches toujours associées automatiquement et changées de statut à la fusion ; la carte de PR n'affiche simplement ni CI ni état de fusion.
+Générez la clé privée dans **Private keys → Generate a private key** de la GitHub App. Sans ces deux variables, la connexion est désactivée. Les connexions existantes continuent de refléter les PR et de mettre à jour les tâches via les webhooks, mais les cartes de PR n’affichent ni CI ni état de fusion.
</Step>
<Step>
@@ -207,7 +211,7 @@ Redémarrez le serveur API, puis effectuez la connexion dans **Paramètres → C
## Dépannage
-- **Bouton de connexion désactivé** : vérifiez que `GITHUB_APP_SLUG` et `GITHUB_WEBHOOK_SECRET` parviennent bien au processus de l'API.
+- **Bouton de connexion désactivé** : vérifiez les six variables GitHub ci-dessus, la première Callback URL et **Request user authorization (OAuth) during installation**.
- **Le webhook renvoie 401** : vérifiez que la GitHub App et l'API utilisent le même secret de webhook, puis relancez la livraison depuis **Recent Deliveries** sur GitHub.
- **PR non associée** : vérifiez que le dépôt fait partie du périmètre autorisé de l'App, que l'association automatique est activée, que l'identifiant appartient à l'espace de travail courant et que personne n'a retiré la PR de la tâche.
- **Identifiant dans la description, mais PR non associée** : placez-le juste après un mot-clé de clôture (`Closes MUL-123`), ou dans le nom de branche ou le titre de la PR, ou associez la PR à la main.
diff --git a/apps/docs/content/docs/github-integration.ja.mdx b/apps/docs/content/docs/github-integration.ja.mdx
index a5b03bd3fa..75e3c0e5f8 100644
--- a/apps/docs/content/docs/github-integration.ja.mdx
+++ b/apps/docs/content/docs/github-integration.ja.mdx
@@ -17,6 +17,8 @@ GitHub 連携が読み取るのは、インストール時に許可されたリ
ワークスペースの owner または admin が接続できます。
+新規接続には GitHub 側の管理権限も必要です。個人の installation は認可するユーザー本人のものである必要があります。組織の installation では対象の全リポジトリで admin 権限が必要で、読み取り権限や一部だけの管理権限では接続できません。組織の installation には少なくとも1つのリポジトリを選択してください。
+
<Steps>
<Step>
**設定 → コード** を開きます。
@@ -137,8 +139,8 @@ GitHub の **Developer settings → GitHub Apps** で App を作成し、次の
| フィールド | 値 |
|---|---|
| Homepage URL | Multica のフロントエンド URL。例: `https://multica.example.com` |
-| Callback URL | 空欄 |
-| Setup URL | `https://<api-host>/api/github/setup`。**Redirect on update** を有効にする |
+| Callback URL | `https://<api-host>/api/github/setup` |
+| Request user authorization (OAuth) during installation | 有効にする |
| Webhook URL | `https://<api-host>/api/webhooks/github` |
| Webhook secret | 長期保管するランダムな文字列 |
@@ -173,19 +175,21 @@ App の公開 URL から slug を確認します。たとえば `https://github.
```dotenv
GITHUB_APP_SLUG=multica-acme
GITHUB_WEBHOOK_SECRET=<webhook secret entered when creating the App>
+GITHUB_APP_CLIENT_ID=<Client ID>
+GITHUB_APP_CLIENT_SECRET=<Client secret>
FRONTEND_ORIGIN=https://multica.example.com
```
-`GITHUB_APP_SLUG` と `GITHUB_WEBHOOK_SECRET` のいずれかがない場合、接続ボタンは無効になり、webhook エンドポイントもイベントを拒否します。
+新しい接続には、この節の6つの GitHub 変数すべてが必要です。`GITHUB_APP_ID` と `GITHUB_APP_PRIVATE_KEY` も必須です。いずれかがない場合は接続ボタンが無効になります。webhook の受信には `GITHUB_WEBHOOK_SECRET` のみが必要で、既存の接続は引き続き動作します。デプロイ前に最初の Callback URL をこのエンドポイントに設定し、インストール時の OAuth 認可を有効にしてください。このオプションを有効にすると、GitHub は別の Setup URL を使用しません。
-PR カードに CI の状態とマージ可能性を表示するには、次の 2 つの変数も必要です。Multica はこれを使って App として認証し、スナップショットを取得します。
+新規接続と PR カードの CI 状態・マージ可否のために、次の2つの変数も設定してください。Multica は metadata 読み取り専用トークンで installation の全リポジトリを取得し、接続ユーザーが管理するリポジトリと照合します。
```dotenv
GITHUB_APP_ID=<numeric GitHub App ID>
GITHUB_APP_PRIVATE_KEY=<complete PEM private key, including BEGIN/END lines and newlines>
```
-秘密鍵は GitHub App の **Private keys → Generate a private key** から生成します。この 2 つを設定しなくても、PR のミラー、タスクの自動紐づけ、マージ時のステータス変更は動作します。PR カードに CI やマージ状態が表示されないだけです。
+秘密鍵は GitHub App の **Private keys → Generate a private key** から生成します。この2つの変数がない場合、接続ボタンは無効になります。既存の接続は webhook で PR をミラーしタスクを更新しますが、PR カードに CI やマージ状態は表示されません。
</Step>
<Step>
@@ -205,7 +209,7 @@ API サービスを再起動し、**設定 → コード** から接続します
## よくある問題
-- **接続ボタンを使用できない**: `GITHUB_APP_SLUG` と `GITHUB_WEBHOOK_SECRET` が API プロセスに設定されていることを確認します。
+- **接続ボタンを使用できない**: 上記6つの GitHub 変数、最初の Callback URL、**Request user authorization (OAuth) during installation** を確認します。
- **Webhook が 401 を返す**: GitHub App と API が同じ Webhook secret を使っていることを確認し、GitHub の **Recent Deliveries** から再配信します。
- **PR が紐づかない**: リポジトリが App の許可範囲にあること、PR の自動紐づけが有効であること、番号が現在のワークスペースのものであること、誰かがタスクから外していないかを確認します。
- **本文に番号を書いても紐づかない**: `Closes MUL-123` を使うか、番号をブランチ名または PR タイトルに入れるか、手動で紐づけます。
diff --git a/apps/docs/content/docs/github-integration.ko.mdx b/apps/docs/content/docs/github-integration.ko.mdx
index b7f3d47707..bae43c3d9d 100644
--- a/apps/docs/content/docs/github-integration.ko.mdx
+++ b/apps/docs/content/docs/github-integration.ko.mdx
@@ -17,6 +17,8 @@ GitHub 연동은 설치할 때 승인한 저장소만 읽으며 코드, 댓글,
워크스페이스 owner 또는 admin이 연결할 수 있습니다.
+새 연결에는 GitHub의 설치 관리 권한도 필요합니다. 개인 installation은 승인하는 사용자 본인의 것이어야 합니다. 조직 installation은 포함된 모든 저장소에 admin 권한이 있어야 하며, 읽기 권한이나 일부 저장소의 관리 권한만으로는 연결할 수 없습니다. 조직 installation에 먼저 하나 이상의 저장소를 선택하세요.
+
<Steps>
<Step>
**설정 → 코드**를 엽니다.
@@ -137,8 +139,8 @@ GitHub의 **Developer settings → GitHub Apps**에서 App을 만들고 다음
| 필드 | 값 |
|---|---|
| Homepage URL | Multica 프런트엔드 주소. 예: `https://multica.example.com` |
-| Callback URL | 비워 둠 |
-| Setup URL | `https://<api-host>/api/github/setup`, **Redirect on update** 활성화 |
+| Callback URL | `https://<api-host>/api/github/setup` |
+| Request user authorization (OAuth) during installation | 활성화 |
| Webhook URL | `https://<api-host>/api/webhooks/github` |
| Webhook secret | 장기 보관할 임의 문자열 |
@@ -173,19 +175,21 @@ App의 공개 주소에서 slug를 확인합니다. 예를 들어 `https://githu
```dotenv
GITHUB_APP_SLUG=multica-acme
GITHUB_WEBHOOK_SECRET=<App을 만들 때 입력한 webhook secret>
+GITHUB_APP_CLIENT_ID=<Client ID>
+GITHUB_APP_CLIENT_SECRET=<Client secret>
FRONTEND_ORIGIN=https://multica.example.com
```
-`GITHUB_APP_SLUG`와 `GITHUB_WEBHOOK_SECRET` 중 하나라도 없으면 연결 버튼이 비활성화되고 webhook endpoint도 이벤트 처리를 거부합니다.
+새 연결에는 이 절의 GitHub 변수 여섯 개가 모두 필요하며 `GITHUB_APP_ID`와 `GITHUB_APP_PRIVATE_KEY`도 포함됩니다. 하나라도 없으면 연결 버튼이 비활성화됩니다. webhook 수신에는 `GITHUB_WEBHOOK_SECRET`만 필요하며 기존 연결은 계속 작동합니다. 배포 전에 첫 번째 Callback URL을 이 endpoint로 설정하고 설치 시 OAuth 승인을 활성화하세요. 이 옵션이 활성화되면 GitHub는 별도의 Setup URL을 사용하지 않습니다.
-PR 카드에 CI 상태와 merge 가능 여부를 표시하려면 다음 두 변수도 필요합니다. Multica는 이 값으로 App 신원을 인증하고 snapshot을 가져옵니다.
+새 연결과 PR 카드의 CI 상태 및 merge 가능 여부를 위해 다음 두 변수도 설정하세요. Multica는 metadata 읽기 전용 토큰으로 installation의 전체 저장소 목록을 가져와 연결 사용자가 관리하는 목록과 비교합니다.
```dotenv
GITHUB_APP_ID=<GitHub App 숫자 ID>
GITHUB_APP_PRIVATE_KEY=<BEGIN/END 줄과 줄바꿈을 유지한 전체 PEM private key>
```
-Private key는 GitHub App의 **Private keys → Generate a private key**에서 생성합니다. 이 두 변수가 없어도 PR은 계속 미러링되고 태스크 자동 연결과 merge 시 상태 변경도 작동합니다. PR 카드에 CI 또는 merge 상태가 표시되지 않을 뿐입니다.
+GitHub App의 **Private keys → Generate a private key**에서 키를 생성하세요. 두 변수가 없으면 연결 버튼이 비활성화됩니다. 기존 연결은 webhook으로 PR을 미러링하고 태스크를 업데이트하지만 PR 카드에 CI나 merge 상태가 표시되지 않습니다.
</Step>
<Step>
@@ -205,7 +209,7 @@ API 서비스를 다시 시작한 뒤 **설정 → 코드**에서 연결을 완
## 자주 묻는 문제
-- **연결 버튼을 사용할 수 없음**: `GITHUB_APP_SLUG`와 `GITHUB_WEBHOOK_SECRET`이 API 프로세스에 전달되었는지 확인합니다.
+- **연결 버튼을 사용할 수 없음**: 위의 GitHub 변수 여섯 개, 첫 번째 Callback URL, **Request user authorization (OAuth) during installation**을 확인합니다.
- **Webhook이 401을 반환함**: GitHub App과 API가 같은 Webhook secret을 사용하는지 확인하고 GitHub의 **Recent Deliveries**에서 다시 전달합니다.
- **PR이 연결되지 않음**: 저장소가 App 승인 범위에 있는지, 자동 연결이 켜져 있는지, 번호가 현재 워크스페이스에 속하는지, 누군가 태스크에서 PR을 제거하지 않았는지 확인합니다.
- **본문에 번호를 썼는데 연결되지 않음**: `Closes MUL-123`을 사용하거나, 번호를 브랜치 이름이나 PR 제목에 넣거나, 직접 연결합니다.
diff --git a/apps/docs/content/docs/github-integration.mdx b/apps/docs/content/docs/github-integration.mdx
index 9f9a731252..adb69dc657 100644
--- a/apps/docs/content/docs/github-integration.mdx
+++ b/apps/docs/content/docs/github-integration.mdx
@@ -17,6 +17,8 @@ Self-hosted Multica can also connect self-hosted Forgejo, Gitea, or GitLab insta
A workspace owner or admin can complete the connection:
+A new connection also requires GitHub installation control: a personal installation must belong to the authorizing GitHub user; an organization installation requires admin permission on every repository it covers. Read-only or partial access is insufficient. Select at least one repository for an organization installation before connecting.
+
<Steps>
<Step>
Open **Settings → Code**.
@@ -139,8 +141,8 @@ Create the App under GitHub's **Developer settings → GitHub Apps** and fill in
| Field | Value |
|---|---|
| Homepage URL | Your Multica frontend address, e.g. `https://multica.example.com` |
-| Callback URL | Leave blank |
-| Setup URL | `https://<api-host>/api/github/setup`, with **Redirect on update** enabled |
+| Callback URL | `https://<api-host>/api/github/setup` |
+| Request user authorization (OAuth) during installation | Enable |
| Webhook URL | `https://<api-host>/api/webhooks/github` |
| Webhook secret | A random string you keep long-term |
@@ -175,19 +177,21 @@ Take the slug from the App's public URL. For example, the slug of `https://githu
```dotenv
GITHUB_APP_SLUG=multica-acme
GITHUB_WEBHOOK_SECRET=<the webhook secret you entered when creating the App>
+GITHUB_APP_CLIENT_ID=<Client ID>
+GITHUB_APP_CLIENT_SECRET=<Client secret>
FRONTEND_ORIGIN=https://multica.example.com
```
-If either `GITHUB_APP_SLUG` or `GITHUB_WEBHOOK_SECRET` is missing, the connect button is disabled and the webhook endpoint refuses to process events.
+All six GitHub variables in this section are required for new connections, including `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY`. Missing any of them disables Connect; webhook acceptance requires only `GITHUB_WEBHOOK_SECRET`. Existing bindings continue working. Set the first Callback URL to this endpoint and enable installation OAuth before deploying. GitHub does not use a separate Setup URL when installation OAuth is enabled.
-For the PR card to show CI status and mergeability, also set the next two variables. Multica uses them to authenticate as the App and pull snapshots:
+For new connections, PR-card CI status and mergeability, also set the next two variables. Multica uses a metadata-only installation token to compare the complete installation repository list with the repositories the connecting user administers:
```dotenv
GITHUB_APP_ID=<the GitHub App's numeric ID>
GITHUB_APP_PRIVATE_KEY=<full PEM private key, keeping the BEGIN/END lines and newlines>
```
-Generate the private key under the GitHub App's **Private keys → Generate a private key**. Without these two variables, PRs still mirror and issues still auto-link and change status on merge; the PR card just shows no CI or merge state.
+Generate the private key under the GitHub App's **Private keys → Generate a private key**. Without these two variables, Connect is disabled. Existing bindings still mirror PRs and update issues from webhooks, but PR cards lack CI and mergeability status.
</Step>
<Step>
@@ -207,7 +211,7 @@ Restart the API server, then complete the connection in **Settings → Code**.
## Troubleshooting
-- **Connect button disabled**: check that `GITHUB_APP_SLUG` and `GITHUB_WEBHOOK_SECRET` reached the API process.
+- **Connect button disabled**: check all six GitHub variables above, the first Callback URL, and **Request user authorization (OAuth) during installation**.
- **Webhook returns 401**: confirm the GitHub App and the API use the same webhook secret, then redeliver from GitHub's **Recent Deliveries**.
- **PR not linked**: check that the repository is in the App's authorized scope, auto-linking is on, the identifier belongs to the current workspace, and nobody removed the PR from the issue.
- **Identifier in the body but not linked**: put it right after a closing keyword (`Closes MUL-123`), or in the branch name or PR title, or link the PR by hand.
diff --git a/apps/docs/content/docs/github-integration.zh-Hant.mdx b/apps/docs/content/docs/github-integration.zh-Hant.mdx
index c7f63c5717..b585ab2c84 100644
--- a/apps/docs/content/docs/github-integration.zh-Hant.mdx
+++ b/apps/docs/content/docs/github-integration.zh-Hant.mdx
@@ -17,6 +17,8 @@ GitHub 整合只讀取安裝時授權的倉庫,不會提交程式碼、評論
工作區 owner 或 admin 可以完成連線:
+新連線還要求 GitHub 側的安裝管理權限:個人安裝必須屬於授權使用者本人;組織安裝要求使用者對安裝涵蓋的每個倉庫都有 admin 權限。只有讀取權限或只能管理部分倉庫時無法連線。組織安裝需先選中至少一個倉庫。
+
<Steps>
<Step>
開啟 **設定 → 程式碼**。
@@ -139,8 +141,8 @@ Multica Cloud 無需執行本節。自託管需要先建立自己的 GitHub App
| 欄位 | 值 |
|---|---|
| Homepage URL | Multica 前端地址,例如 `https://multica.example.com` |
-| Callback URL | 留空 |
-| Setup URL | `https://<api-host>/api/github/setup`,並啟用 **Redirect on update** |
+| Callback URL | `https://<api-host>/api/github/setup` |
+| Request user authorization (OAuth) during installation | 啟用 |
| Webhook URL | `https://<api-host>/api/webhooks/github` |
| Webhook secret | 一段長期儲存的隨機字串 |
@@ -175,19 +177,21 @@ PR 快照透過 Pull requests、Checks 和 Commit statuses 的 REST API 獲取
```dotenv
GITHUB_APP_SLUG=multica-acme
GITHUB_WEBHOOK_SECRET=<建立 App 時填寫的 webhook secret>
+GITHUB_APP_CLIENT_ID=<Client ID>
+GITHUB_APP_CLIENT_SECRET=<Client secret>
FRONTEND_ORIGIN=https://multica.example.com
```
-`GITHUB_APP_SLUG` 和 `GITHUB_WEBHOOK_SECRET` 缺少任意一個時,連線按鈕會被禁用,webhook 介面也會拒絕處理事件。
+新連線需要本節的全部六個 GitHub 變數,包括 `GITHUB_APP_ID` 和 `GITHUB_APP_PRIVATE_KEY`。缺少任意一個都會停用連線按鈕;webhook 接入只要求 `GITHUB_WEBHOOK_SECRET`。既有綁定繼續運作。部署前,將第一個 Callback URL 設為此端點,並啟用安裝時 OAuth 授權。啟用此選項後,GitHub 不再使用獨立的 Setup URL。
-PR 卡片要顯示 CI 狀態與可合併性,還需要下面兩個變數,Multica 用它們以 App 身份鑑權並拉取快照:
+新連線以及 PR 卡片的 CI 狀態、可合併性還需要以下兩個變數。Multica 用唯讀 metadata token 取得安裝的完整倉庫清單,並與操作者可管理的倉庫清單核對:
```dotenv
GITHUB_APP_ID=<GitHub App 的數字 ID>
GITHUB_APP_PRIVATE_KEY=<完整 PEM 私鑰,保留 BEGIN/END 行和換行>
```
-私鑰在 GitHub App 的 **Private keys → Generate a private key** 中生成。不配置這兩個變數時,PR 照常映象,任務照常自動關聯並在合併時改狀態,只是 PR 卡片不顯示 CI 或合併狀態。
+私鑰在 GitHub App 的 **Private keys → Generate a private key** 中生成。不設定這兩個變數時,連線按鈕會被停用。既有綁定仍透過 webhook 映象 PR、更新任務,但 PR 卡片不顯示 CI 或合併狀態。
</Step>
<Step>
@@ -207,7 +211,7 @@ make migrate-up
## 常見問題
-- **連線按鈕不可用**:檢查 `GITHUB_APP_SLUG` 和 `GITHUB_WEBHOOK_SECRET` 是否已進入 API 程序。
+- **連線按鈕不可用**:檢查以上六個 GitHub 變數、第一個 Callback URL,以及 **Request user authorization (OAuth) during installation**。
- **Webhook 返回 401**:確認 GitHub App 與 API 使用同一個 Webhook secret,然後在 GitHub 的 **Recent Deliveries** 中重新投遞。
- **PR 沒有關聯**:檢查倉庫是否在 App 授權範圍內、自動關聯是否開啟、編號是否屬於當前工作區,以及是否有人把它從任務上移除過。
- **正文寫了編號但沒關聯**:改用 `Closes MUL-123`,或把編號放到分支名、PR 標題中,或者手動關聯。
diff --git a/apps/docs/content/docs/github-integration.zh.mdx b/apps/docs/content/docs/github-integration.zh.mdx
index 15880f189a..d900a95b99 100644
--- a/apps/docs/content/docs/github-integration.zh.mdx
+++ b/apps/docs/content/docs/github-integration.zh.mdx
@@ -17,6 +17,8 @@ GitHub 集成只读取安装时授权的仓库,不会提交代码、评论或
工作区 owner 或 admin 可以完成连接:
+新连接还要求 GitHub 侧的安装管理权限:个人安装必须属于授权用户本人;组织安装要求用户对安装覆盖的每个仓库都有 admin 权限。只有读权限或只能管理部分仓库时无法连接。组织安装需先选中至少一个仓库。
+
<Steps>
<Step>
打开 **设置 → 代码**。
@@ -139,8 +141,8 @@ Multica Cloud 无需执行本节。自托管需要先创建自己的 GitHub App
| 字段 | 值 |
|---|---|
| Homepage URL | Multica 前端地址,例如 `https://multica.example.com` |
-| Callback URL | 留空 |
-| Setup URL | `https://<api-host>/api/github/setup`,并启用 **Redirect on update** |
+| Callback URL | `https://<api-host>/api/github/setup` |
+| Request user authorization (OAuth) during installation | 启用 |
| Webhook URL | `https://<api-host>/api/webhooks/github` |
| Webhook secret | 一段长期保存的随机字符串 |
@@ -175,19 +177,21 @@ PR 快照通过 Pull requests、Checks 和 Commit statuses 的 REST API 获取
```dotenv
GITHUB_APP_SLUG=multica-acme
GITHUB_WEBHOOK_SECRET=<创建 App 时填写的 webhook secret>
+GITHUB_APP_CLIENT_ID=<Client ID>
+GITHUB_APP_CLIENT_SECRET=<Client secret>
FRONTEND_ORIGIN=https://multica.example.com
```
-`GITHUB_APP_SLUG` 和 `GITHUB_WEBHOOK_SECRET` 缺少任意一个时,连接按钮会被禁用,webhook 接口也会拒绝处理事件。
+新连接需要本节的全部六个 GitHub 变量,包括 `GITHUB_APP_ID` 和 `GITHUB_APP_PRIVATE_KEY`。缺少任意一个都会禁用连接按钮;webhook 接入只要求 `GITHUB_WEBHOOK_SECRET`。已有绑定继续工作。部署前,将第一个 Callback URL 设为此端点,并启用安装时 OAuth 授权。启用此选项后,GitHub 不再使用单独的 Setup URL。
-PR 卡片要显示 CI 状态与可合并性,还需要下面两个变量,Multica 用它们以 App 身份鉴权并拉取快照:
+新连接以及 PR 卡片的 CI 状态、可合并性还需要以下两个变量。Multica 用只读 metadata token 获取安装的完整仓库列表,并与操作者可管理的仓库列表核对:
```dotenv
GITHUB_APP_ID=<GitHub App 的数字 ID>
GITHUB_APP_PRIVATE_KEY=<完整 PEM 私钥,保留 BEGIN/END 行和换行>
```
-私钥在 GitHub App 的 **Private keys → Generate a private key** 中生成。不配置这两个变量时,PR 照常镜像,任务照常自动关联并在合并时改状态,只是 PR 卡片不显示 CI 或合并状态。
+私钥在 GitHub App 的 **Private keys → Generate a private key** 中生成。不配置这两个变量时,连接按钮会被禁用。已有绑定仍通过 webhook 镜像 PR、更新任务,但 PR 卡片不显示 CI 或合并状态。
</Step>
<Step>
@@ -207,7 +211,7 @@ make migrate-up
## 常见问题
-- **连接按钮不可用**:检查 `GITHUB_APP_SLUG` 和 `GITHUB_WEBHOOK_SECRET` 是否已进入 API 进程。
+- **连接按钮不可用**:检查以上六个 GitHub 变量、第一个 Callback URL,以及 **Request user authorization (OAuth) during installation**。
- **Webhook 返回 401**:确认 GitHub App 与 API 使用同一个 Webhook secret,然后在 GitHub 的 **Recent Deliveries** 中重新投递。
- **PR 没有关联**:检查仓库是否在 App 授权范围内、自动关联是否开启、编号是否属于当前工作区,以及是否有人把它从任务上移除过。
- **正文写了编号但没关联**:改用 `Closes MUL-123`,或把编号放到分支名、PR 标题中,或者手动关联。
diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.yml
index 627f909d9a..158d4301c0 100644
--- a/docker-compose.selfhost.yml
+++ b/docker-compose.selfhost.yml
@@ -119,6 +119,10 @@ services:
MULTICA_CLOUD_URL: ${MULTICA_CLOUD_URL:-}
GITHUB_APP_SLUG: ${GITHUB_APP_SLUG:-}
GITHUB_WEBHOOK_SECRET: ${GITHUB_WEBHOOK_SECRET:-}
+ # Required for new connections: verify the installing user's access.
+ GITHUB_APP_CLIENT_ID: ${GITHUB_APP_CLIENT_ID:-}
+ GITHUB_APP_CLIENT_SECRET: ${GITHUB_APP_CLIENT_SECRET:-}
+ # Required for new connections to prove organization repository control.
# App API credentials. The pull_request webhook is what mirrors a PR
# onto a card; these are what let the server authenticate as the App
# and pull the CI / mergeability snapshot that enriches it, plus
diff --git a/packages/views/settings/components/code-tab.tsx b/packages/views/settings/components/code-tab.tsx
index a3d8ff6e78..97cffb7c81 100644
--- a/packages/views/settings/components/code-tab.tsx
+++ b/packages/views/settings/components/code-tab.tsx
@@ -153,8 +153,12 @@ export function CodeTab() {
<>
{t(($) => $.github.not_configured)}{" "}
<code className="rounded-xs bg-muted px-1 py-0.5 text-micro">GITHUB_APP_SLUG</code>{" "}
+ <code className="rounded-xs bg-muted px-1 py-0.5 text-micro">GITHUB_WEBHOOK_SECRET</code>{" "}
+ <code className="rounded-xs bg-muted px-1 py-0.5 text-micro">GITHUB_APP_CLIENT_ID</code>{" "}
+ <code className="rounded-xs bg-muted px-1 py-0.5 text-micro">GITHUB_APP_CLIENT_SECRET</code>{" "}
+ <code className="rounded-xs bg-muted px-1 py-0.5 text-micro">GITHUB_APP_ID</code>{" "}
{t(($) => $.github.not_configured_and)}{" "}
- <code className="rounded-xs bg-muted px-1 py-0.5 text-micro">GITHUB_WEBHOOK_SECRET</code>
+ <code className="rounded-xs bg-muted px-1 py-0.5 text-micro">GITHUB_APP_PRIVATE_KEY</code>
{pausedNote}
</>
) : (
diff --git a/server/internal/handler/github.go b/server/internal/handler/github.go
index e70c97a58b..a4d2c5b464 100644
--- a/server/internal/handler/github.go
+++ b/server/internal/handler/github.go
@@ -369,14 +369,16 @@ func githubAppSlug() string { return strings.TrimSpace(os.Getenv("GITHUB_APP_SLU
// configure one value.
func githubWebhookSecret() string { return strings.TrimSpace(os.Getenv("GITHUB_WEBHOOK_SECRET")) }
-// isGitHubConfigured returns true only when BOTH the install slug and the
-// webhook secret are set. The Connect button uses this single flag, so the
-// frontend never offers a flow that the backend would reject.
-func isGitHubConfigured() bool { return githubAppSlug() != "" && githubWebhookSecret() != "" }
+// Connect requires user OAuth and App credentials to prove installation control.
+// Webhook ingestion and existing installations do not depend on this flag.
+func isGitHubConfigured() bool {
+ return githubAppSlug() != "" && githubWebhookSecret() != "" &&
+ githubAppClientID() != "" && githubAppClientSecret() != "" &&
+ isGitHubRepositoryBrowseConfigured()
+}
// isGitHubRepositoryBrowseConfigured is deliberately separate from the
-// install-flow flag. The App slug + webhook secret are enough to connect an
-// installation, but browsing its repositories also requires App JWT
+// install-flow flag. Browsing repositories requires App JWT
// credentials so the server can mint a short-lived installation token.
func isGitHubRepositoryBrowseConfigured() bool {
return strings.TrimSpace(os.Getenv("GITHUB_APP_ID")) != "" &&
@@ -399,7 +401,7 @@ func signGitHubState(workspaceID string, desktop bool) (string, error) {
if _, err := rand.Read(nonceBytes); err != nil {
return "", err
}
- nonce := hex.EncodeToString(nonceBytes)
+ nonce := strconv.FormatInt(time.Now().Unix(), 10) + "-" + hex.EncodeToString(nonceBytes)
// Keep the three-part format readable by installed clients and older servers.
if desktop {
nonce = "desktop-" + nonce
@@ -424,7 +426,7 @@ func verifyGitHubState(token string) (workspaceID, connectionID string, ok bool)
if len(parts) != 3 && len(parts) != 4 {
return "", "", false
}
- // Accept in-flight links from before the Code settings page was unified.
+ // Untimed links are rejected below; users must restart Connect after upgrade.
if len(parts) == 4 && parts[1] != "github" && parts[1] != "repositories" {
return "", "", false
}
@@ -434,6 +436,16 @@ func verifyGitHubState(token string) (workspaceID, connectionID string, ok bool)
if !hmac.Equal([]byte(hex.EncodeToString(mac.Sum(nil))), []byte(parts[len(parts)-1])) {
return "", "", false
}
+ connectionID = parts[len(parts)-2]
+ timestamp, _, found := strings.Cut(strings.TrimPrefix(connectionID, "desktop-"), "-")
+ issuedAt, err := strconv.ParseInt(timestamp, 10, 64)
+ if !found || err != nil {
+ return "", "", false
+ }
+ age := time.Since(time.Unix(issuedAt, 0))
+ if age > 15*time.Minute || age < -time.Minute {
+ return "", "", false
+ }
return parts[0], parts[len(parts)-2], true
}
@@ -469,8 +481,9 @@ func (h *Handler) GitHubConnect(w http.ResponseWriter, r *http.Request) {
// GitHubSetupCallback (GET /api/github/setup) handles the redirect GitHub
// sends after a user installs (or re-authorizes) the App. We expect
-// ?installation_id=<id>&state=<signed token>. We persist the installation
-// row (workspace ↔ installation_id mapping), then returns to Code settings.
+// ?installation_id=<id>&code=<user authorization code>&state=<signed token>.
+// The state authorizes the workspace; user OAuth proves installation access
+// before a new binding is persisted.
func (h *Handler) GitHubSetupCallback(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
installationIDStr := q.Get("installation_id")
@@ -495,7 +508,7 @@ func (h *Handler) GitHubSetupCallback(w http.ResponseWriter, r *http.Request) {
return
}
installationID, err := strconv.ParseInt(installationIDStr, 10, 64)
- if err != nil {
+ if err != nil || installationID <= 0 {
http.Redirect(w, r, settingsURL+"&github_error=bad_installation_id", http.StatusFound)
return
}
@@ -510,40 +523,63 @@ func (h *Handler) GitHubSetupCallback(w http.ResponseWriter, r *http.Request) {
return
}
settingsURL = strings.TrimRight(frontend, "/") + "/" + url.PathEscape(workspace.Slug) + "/settings?tab=code"
- // Resolve the installation against GitHub's API to capture display info.
- // If the App auth is not configured we still create the row with the
- // minimum we know; webhook events will refresh it as soon as one fires.
- login, accountType, avatar := fetchInstallationAccount(r.Context(), installationID)
-
- // Best-effort capture of the connecting user (may be nil if the public
- // callback was hit without a session — e.g. user wasn't logged in to
- // Multica when they finished the GitHub install). Either way we save
- // the row so the workspace owner sees the connection on next reload.
- connectedBy := pgtype.UUID{}
- if userID := requestUserID(r); userID != "" {
- if u, err := parseStrictUUID(userID); err == nil {
- connectedBy = u
- }
- }
-
- inst, err := h.Queries.CreateGitHubInstallation(r.Context(), db.CreateGitHubInstallationParams{
- WorkspaceID: wsUUID,
- InstallationID: installationID,
- AccountLogin: login,
- AccountType: accountType,
- AccountAvatarUrl: ptrToText(avatar),
- ConnectedByID: connectedBy,
- })
+ rows, err := h.Queries.ListGitHubInstallationsByWorkspace(r.Context(), wsUUID)
if err != nil {
- slog.Error("github: failed to persist installation", "err", err, "installation_id", installationID)
- http.Redirect(w, r, settingsURL+"&github_error=persist_failed", http.StatusFound)
+ http.Redirect(w, r, settingsURL+"&github_error=verification_failed", http.StatusFound)
return
}
- inst, err = h.consumePendingGitHubInstallation(r.Context(), inst)
- if err != nil {
- slog.Error("github: failed to apply pending installation metadata", "err", err, "installation_id", installationID)
- http.Redirect(w, r, settingsURL+"&github_error=persist_failed", http.StatusFound)
- return
+ var inst db.GithubInstallation
+ existing := false
+ for _, row := range rows {
+ if row.InstallationID == installationID {
+ inst, existing = row, true
+ break
+ }
+ }
+ // Repository-selection updates may carry no OAuth code. Reuse only a
+ // binding this workspace already has, without recreating or changing it.
+ if !existing {
+ if err := verifyGitHubInstallationOwnership(r.Context(), q.Get("code"), installationID); err != nil {
+ slog.Warn("github: refused unverified installation bind", "err", err,
+ "workspace_id", workspaceID, "installation_id", installationID)
+ http.Redirect(w, r, settingsURL+"&github_error="+githubOwnershipErrorCode(err), http.StatusFound)
+ return
+ }
+ // Resolve the installation against GitHub's API to capture display info.
+ // If the App auth is not configured we still create the row with the
+ // minimum we know; webhook events will refresh it as soon as one fires.
+ login, accountType, avatar := fetchInstallationAccount(r.Context(), installationID)
+
+ // Best-effort capture of the connecting user (may be nil if the public
+ // callback was hit without a session — e.g. user wasn't logged in to
+ // Multica when they finished the GitHub install). Either way we save
+ // the row so the workspace owner sees the connection on next reload.
+ connectedBy := pgtype.UUID{}
+ if userID := requestUserID(r); userID != "" {
+ if u, err := parseStrictUUID(userID); err == nil {
+ connectedBy = u
+ }
+ }
+
+ inst, err = h.Queries.CreateGitHubInstallation(r.Context(), db.CreateGitHubInstallationParams{
+ WorkspaceID: wsUUID,
+ InstallationID: installationID,
+ AccountLogin: login,
+ AccountType: accountType,
+ AccountAvatarUrl: ptrToText(avatar),
+ ConnectedByID: connectedBy,
+ })
+ if err != nil {
+ slog.Error("github: failed to persist installation", "err", err, "installation_id", installationID)
+ http.Redirect(w, r, settingsURL+"&github_error=persist_failed", http.StatusFound)
+ return
+ }
+ inst, err = h.consumePendingGitHubInstallation(r.Context(), inst)
+ if err != nil {
+ slog.Error("github: failed to apply pending installation metadata", "err", err, "installation_id", installationID)
+ http.Redirect(w, r, settingsURL+"&github_error=persist_failed", http.StatusFound)
+ return
+ }
}
h.publish(protocol.EventGitHubInstallationCreated, workspaceID, "system", "", map[string]any{
"installation": githubInstallationToBroadcast(inst),
@@ -796,20 +832,21 @@ func parseGitHubPageParam(
return value, true
}
-func fetchGitHubInstallationRepositories(
- ctx context.Context,
- installationID int64,
- page, perPage int,
-) (GitHubRepositoriesResponse, error) {
+type githubInstallationReadToken struct {
+ Token string `json:"token"`
+ RepositorySelection string `json:"repository_selection"`
+}
+
+// Restrict proof and repository browsing tokens to metadata access.
+func createGitHubInstallationReadToken(ctx context.Context, client *http.Client, installationID int64) (githubInstallationReadToken, error) {
appJWT, err := signGitHubAppJWT(time.Now())
if err != nil {
- return GitHubRepositoriesResponse{}, err
+ return githubInstallationReadToken{}, err
}
if appJWT == "" {
- return GitHubRepositoriesResponse{}, errors.New("github App JWT credentials unavailable")
+ return githubInstallationReadToken{}, errors.New("github App JWT credentials unavailable")
}
- client := &http.Client{Timeout: 15 * time.Second}
tokenEndpoint := fmt.Sprintf(
"%s/app/installations/%d/access_tokens",
strings.TrimRight(githubAPIBase, "/"),
@@ -822,28 +859,39 @@ func fetchGitHubInstallationRepositories(
strings.NewReader(`{"permissions":{"metadata":"read"}}`),
)
if err != nil {
- return GitHubRepositoriesResponse{}, err
+ return githubInstallationReadToken{}, err
}
setGitHubAPIHeaders(tokenReq, appJWT)
tokenReq.Header.Set("Content-Type", "application/json")
tokenResp, err := client.Do(tokenReq)
if err != nil {
- return GitHubRepositoriesResponse{}, fmt.Errorf("create installation token: %w", err)
+ return githubInstallationReadToken{}, fmt.Errorf("create installation token: %w", err)
}
defer tokenResp.Body.Close()
if tokenResp.StatusCode != http.StatusCreated {
_, _ = io.Copy(io.Discard, io.LimitReader(tokenResp.Body, githubAPIResponseLimit))
- return GitHubRepositoriesResponse{}, fmt.Errorf("create installation token: github status %d", tokenResp.StatusCode)
- }
- var tokenBody struct {
- Token string `json:"token"`
- RepositorySelection string `json:"repository_selection"`
+ return githubInstallationReadToken{}, fmt.Errorf("create installation token: github status %d", tokenResp.StatusCode)
}
+ var tokenBody githubInstallationReadToken
if err := json.NewDecoder(io.LimitReader(tokenResp.Body, githubAPIResponseLimit)).Decode(&tokenBody); err != nil {
- return GitHubRepositoriesResponse{}, fmt.Errorf("decode installation token: %w", err)
+ return githubInstallationReadToken{}, fmt.Errorf("decode installation token: %w", err)
}
if tokenBody.Token == "" {
- return GitHubRepositoriesResponse{}, errors.New("github returned an empty installation token")
+ return githubInstallationReadToken{}, errors.New("github returned an empty installation token")
+ }
+
+ return tokenBody, nil
+}
+
+func fetchGitHubInstallationRepositories(
+ ctx context.Context,
+ installationID int64,
+ page, perPage int,
+) (GitHubRepositoriesResponse, error) {
+ client := &http.Client{Timeout: 15 * time.Second}
+ tokenBody, err := createGitHubInstallationReadToken(ctx, client, installationID)
+ if err != nil {
+ return GitHubRepositoriesResponse{}, err
}
defer revokeGitHubInstallationToken(client, tokenBody.Token)
diff --git a/server/internal/handler/github_install_ownership.go b/server/internal/handler/github_install_ownership.go
new file mode 100644
index 0000000000..abfbc01f6a
--- /dev/null
+++ b/server/internal/handler/github_install_ownership.go
@@ -0,0 +1,310 @@
+package handler
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "os"
+ "strings"
+ "time"
+)
+
+// GitHub's user OAuth endpoints live on the web host, separate from its API.
+var githubOAuthBase = "https://github.com"
+
+func githubAppClientID() string { return strings.TrimSpace(os.Getenv("GITHUB_APP_CLIENT_ID")) }
+func githubAppClientSecret() string { return strings.TrimSpace(os.Getenv("GITHUB_APP_CLIENT_SECRET")) }
+
+var (
+ // errGitHubUserAuthorizationMissing means the setup redirect carried no
+ // user-authorization `code`. Almost always operator-actionable: the App
+ // needs "Request user authorization (OAuth) during installation" enabled.
+ errGitHubUserAuthorizationMissing = errors.New("github: setup callback carried no user authorization code")
+ errGitHubInstallationNotAuthorized = errors.New("github: installing user does not control the installation")
+)
+
+const (
+ githubUserInstallationsPageSize = 100
+ // githubUserInstallationsMaxPages caps the walk at 2000 installations so a
+ // hostile or pathological account cannot hold the callback open forever.
+ githubUserInstallationsMaxPages = 20
+)
+
+// The signed state authorizes only the workspace. A new installation binding
+// also requires GitHub to confirm the installing user's control; visibility
+// through a read-only repository collaboration is insufficient.
+func verifyGitHubInstallationOwnership(ctx context.Context, code string, installationID int64) error {
+ clientID, clientSecret := githubAppClientID(), githubAppClientSecret()
+ if clientID == "" || clientSecret == "" {
+ return errors.New("github: user authorization credentials are not configured")
+ }
+ if strings.TrimSpace(code) == "" {
+ return errGitHubUserAuthorizationMissing
+ }
+ ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
+ defer cancel()
+ client := &http.Client{Timeout: 15 * time.Second}
+ userToken, err := exchangeGitHubUserCode(ctx, client, clientID, clientSecret, code)
+ if err != nil {
+ return err
+ }
+ // The token never leaves this function and is never stored; revoking it
+ // mirrors how installation tokens are handled elsewhere in this file.
+ defer revokeGitHubUserToken(client, clientID, clientSecret, userToken)
+ return assertUserCanManageInstallation(ctx, client, userToken, installationID)
+}
+
+// githubOwnershipErrorCode maps a verification failure to the `github_error`
+// code carried back to Settings. The frontend renders one generic "connect
+// failed" toast for all of them; the distinction is for operators reading
+// logs and support tickets.
+func githubOwnershipErrorCode(err error) string {
+ switch {
+ case errors.Is(err, errGitHubInstallationNotAuthorized):
+ return "installation_not_authorized"
+ case errors.Is(err, errGitHubUserAuthorizationMissing):
+ return "missing_authorization"
+ default:
+ return "verification_failed"
+ }
+}
+
+// exchangeGitHubUserCode trades the setup redirect's `code` for a
+// user-to-server access token. GitHub answers 200 with an `error` field for a
+// bad or replayed code, so the body is checked as well as the status.
+func exchangeGitHubUserCode(
+ ctx context.Context,
+ client *http.Client,
+ clientID, clientSecret, code string,
+) (string, error) {
+ form := url.Values{}
+ form.Set("client_id", clientID)
+ form.Set("client_secret", clientSecret)
+ form.Set("code", code)
+ endpoint := strings.TrimRight(githubOAuthBase, "/") + "/login/oauth/access_token"
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode()))
+ if err != nil {
+ return "", err
+ }
+ req.Header.Set("Accept", "application/json")
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ resp, err := client.Do(req)
+ if err != nil {
+ return "", fmt.Errorf("exchange github user code: %w", err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, githubAPIResponseLimit))
+ return "", fmt.Errorf("exchange github user code: github status %d", resp.StatusCode)
+ }
+ var body struct {
+ AccessToken string `json:"access_token"`
+ Error string `json:"error"`
+ }
+ if err := json.NewDecoder(io.LimitReader(resp.Body, githubAPIResponseLimit)).Decode(&body); err != nil {
+ return "", fmt.Errorf("decode github user token: %w", err)
+ }
+ if body.Error != "" {
+ return "", errors.New("github refused the user authorization code")
+ }
+ if body.AccessToken == "" {
+ return "", errors.New("github returned an empty user access token")
+ }
+ return body.AccessToken, nil
+}
+
+// GitHub includes collaborator installations in this list, so finding an ID
+// must be followed by account ownership or full repository administration proof.
+func assertUserCanManageInstallation(
+ ctx context.Context,
+ client *http.Client,
+ userToken string,
+ installationID int64,
+) error {
+ for page := 1; page <= githubUserInstallationsMaxPages; page++ {
+ endpoint := fmt.Sprintf(
+ "%s/user/installations?per_page=%d&page=%d",
+ strings.TrimRight(githubAPIBase, "/"),
+ githubUserInstallationsPageSize,
+ page,
+ )
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
+ if err != nil {
+ return err
+ }
+ setGitHubAPIHeaders(req, userToken)
+ resp, err := client.Do(req)
+ if err != nil {
+ return fmt.Errorf("list user installations: %w", err)
+ }
+ if resp.StatusCode != http.StatusOK {
+ _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, githubAPIResponseLimit))
+ resp.Body.Close()
+ return fmt.Errorf("list user installations: github status %d", resp.StatusCode)
+ }
+ var body struct {
+ Installations []struct {
+ ID int64 `json:"id"`
+ Account struct {
+ ID int64 `json:"id"`
+ Type string `json:"type"`
+ } `json:"account"`
+ } `json:"installations"`
+ }
+ decodeErr := json.NewDecoder(io.LimitReader(resp.Body, githubAPIResponseLimit)).Decode(&body)
+ resp.Body.Close()
+ if decodeErr != nil {
+ return fmt.Errorf("decode user installations: %w", decodeErr)
+ }
+ for _, installation := range body.Installations {
+ if installation.ID == installationID {
+ switch installation.Account.Type {
+ case "User":
+ var user struct {
+ ID int64 `json:"id"`
+ }
+ if err := getGitHubOwnershipJSON(ctx, client, "/user", userToken, &user); err != nil {
+ return err
+ }
+ if user.ID > 0 && user.ID == installation.Account.ID {
+ return nil
+ }
+ case "Organization":
+ return assertUserAdministersInstallationRepositories(ctx, client, userToken, installationID)
+ }
+ return errGitHubInstallationNotAuthorized
+ }
+ }
+ if len(body.Installations) < githubUserInstallationsPageSize {
+ break
+ }
+ }
+ return errGitHubInstallationNotAuthorized
+}
+
+func getGitHubOwnershipJSON(ctx context.Context, client *http.Client, path, token string, out any) error {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(githubAPIBase, "/")+path, nil)
+ if err != nil {
+ return err
+ }
+ setGitHubAPIHeaders(req, token)
+ resp, err := client.Do(req)
+ if err != nil {
+ return fmt.Errorf("github ownership request: %w", err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return fmt.Errorf("github ownership request: status %d", resp.StatusCode)
+ }
+ if err := json.NewDecoder(io.LimitReader(resp.Body, githubAPIResponseLimit)).Decode(out); err != nil {
+ return fmt.Errorf("decode github ownership response: %w", err)
+ }
+ return nil
+}
+
+func assertUserAdministersInstallationRepositories(ctx context.Context, client *http.Client, userToken string, installationID int64) error {
+ userRepos, err := githubOwnershipRepositoryIDs(ctx, client,
+ fmt.Sprintf("/user/installations/%d/repositories", installationID), userToken, true)
+ if err != nil {
+ return err
+ }
+ token, err := createGitHubInstallationReadToken(ctx, client, installationID)
+ if err != nil {
+ return err
+ }
+ defer revokeGitHubInstallationToken(client, token.Token)
+ appRepos, err := githubOwnershipRepositoryIDs(ctx, client, "/installation/repositories", token.Token, false)
+ if err != nil {
+ return err
+ }
+ if len(userRepos) != len(appRepos) {
+ return errGitHubInstallationNotAuthorized
+ }
+ for id := range appRepos {
+ if _, ok := userRepos[id]; !ok {
+ return errGitHubInstallationNotAuthorized
+ }
+ }
+ return nil
+}
+
+// A complete, nonempty repository set is required. Reject partial pages,
+// missing permissions/counts, and changing pagination rather than proving
+// control over only the subset a collaborator can see.
+func githubOwnershipRepositoryIDs(ctx context.Context, client *http.Client, path, token string, requireAdmin bool) (map[int64]struct{}, error) {
+ ids := make(map[int64]struct{})
+ total := int64(-1)
+ for page := 1; page <= githubUserInstallationsMaxPages; page++ {
+ var body struct {
+ TotalCount *int64 `json:"total_count"`
+ Repositories []struct {
+ ID int64 `json:"id"`
+ Permissions struct {
+ Admin bool `json:"admin"`
+ } `json:"permissions"`
+ } `json:"repositories"`
+ }
+ endpoint := fmt.Sprintf("%s?per_page=%d&page=%d", path, githubUserInstallationsPageSize, page)
+ if err := getGitHubOwnershipJSON(ctx, client, endpoint, token, &body); err != nil {
+ return nil, err
+ }
+ if body.TotalCount == nil || *body.TotalCount <= 0 || (total >= 0 && total != *body.TotalCount) {
+ return nil, errGitHubInstallationNotAuthorized
+ }
+ total = *body.TotalCount
+ for _, repo := range body.Repositories {
+ if repo.ID <= 0 || (requireAdmin && !repo.Permissions.Admin) {
+ return nil, errGitHubInstallationNotAuthorized
+ }
+ if _, duplicate := ids[repo.ID]; duplicate {
+ return nil, errGitHubInstallationNotAuthorized
+ }
+ ids[repo.ID] = struct{}{}
+ }
+ if int64(len(ids)) == total {
+ return ids, nil
+ }
+ if int64(len(ids)) > total || len(body.Repositories) == 0 {
+ return nil, errGitHubInstallationNotAuthorized
+ }
+ }
+ return nil, errGitHubInstallationNotAuthorized
+}
+
+// revokeGitHubUserToken drops the short-lived user token as soon as the
+// ownership check is done, even if the caller cancelled. Revocation is best-effort.
+func revokeGitHubUserToken(client *http.Client, clientID, clientSecret, token string) {
+ if token == "" {
+ return
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ endpoint := fmt.Sprintf(
+ "%s/applications/%s/token",
+ strings.TrimRight(githubAPIBase, "/"),
+ url.PathEscape(clientID),
+ )
+ payload, err := json.Marshal(map[string]string{"access_token": token})
+ if err != nil {
+ return
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodDelete, endpoint, bytes.NewReader(payload))
+ if err != nil {
+ return
+ }
+ req.Header.Set("Accept", "application/vnd.github+json")
+ req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
+ req.Header.Set("Content-Type", "application/json")
+ req.SetBasicAuth(clientID, clientSecret)
+ resp, err := client.Do(req)
+ if err != nil {
+ return
+ }
+ defer resp.Body.Close()
+ _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, githubAPIResponseLimit))
+}
diff --git a/server/internal/handler/github_install_ownership_test.go b/server/internal/handler/github_install_ownership_test.go
new file mode 100644
index 0000000000..5422ad2cef
--- /dev/null
+++ b/server/internal/handler/github_install_ownership_test.go
@@ -0,0 +1,477 @@
+package handler
+
+import (
+ "context"
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+func TestGitHubSetupRejectsUnverifiedInstallation(t *testing.T) {
+ if testHandler == nil {
+ t.Fatal("handler fixture requires an isolated database")
+ }
+ t.Setenv("GITHUB_WEBHOOK_SECRET", "ownership-test-secret")
+ t.Setenv("GITHUB_APP_CLIENT_ID", "test-client")
+ t.Setenv("GITHUB_APP_CLIENT_SECRET", "test-client-secret")
+ t.Setenv("GITHUB_APP_ID", "")
+ t.Setenv("GITHUB_APP_PRIVATE_KEY", "")
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprint(w, `{"account":{"login":"unrelated-org","type":"Organization"}}`)
+ }))
+ t.Cleanup(srv.Close)
+ oldBase := githubAPIBase
+ githubAPIBase = srv.URL
+ t.Cleanup(func() { githubAPIBase = oldBase })
+ installationID := time.Now().UnixNano()
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM github_installation WHERE installation_id = $1`, installationID)
+ })
+ state, err := signState(testWorkspaceID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/github/setup?installation_id=%d&state=%s", installationID, url.QueryEscape(state)), nil)
+ rec := httptest.NewRecorder()
+ testHandler.GitHubSetupCallback(rec, req)
+ rows, err := testHandler.Queries.ListGitHubInstallationsByInstallationID(req.Context(), installationID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(rows) != 0 {
+ t.Fatalf("unverified installation was persisted: %d bindings", len(rows))
+ }
+ if rec.Code != http.StatusFound || !strings.Contains(rec.Header().Get("Location"), "github_error=missing_authorization") {
+ t.Fatalf("callback = %d %s", rec.Code, rec.Header().Get("Location"))
+ }
+}
+
+func stubGitHubOwnership(t *testing.T, serve http.HandlerFunc) {
+ t.Helper()
+ t.Setenv("GITHUB_APP_CLIENT_ID", "test-client")
+ t.Setenv("GITHUB_APP_CLIENT_SECRET", "test-client-secret")
+ srv := httptest.NewServer(serve)
+ t.Cleanup(srv.Close)
+ oldAPI, oldOAuth := githubAPIBase, githubOAuthBase
+ githubAPIBase, githubOAuthBase = srv.URL, srv.URL
+ t.Cleanup(func() { githubAPIBase, githubOAuthBase = oldAPI, oldOAuth })
+}
+
+func serveGitHubOwnership(t *testing.T, w http.ResponseWriter, r *http.Request, installationID int64) bool {
+ t.Helper()
+ switch r.URL.Path {
+ case "/login/oauth/access_token":
+ if r.Method != http.MethodPost || r.FormValue("code") != "valid-code" || r.FormValue("client_id") != "test-client" || r.FormValue("client_secret") != "test-client-secret" {
+ t.Error("incorrect OAuth exchange request")
+ }
+ fmt.Fprint(w, `{"access_token":"test-user-token"}`)
+ case "/user/installations":
+ if r.Header.Get("Authorization") != "Bearer test-user-token" {
+ t.Error("installation access must be checked with the user token")
+ }
+ fmt.Fprintf(w, `{"installations":[{"id":%d,"account":{"id":123,"type":"User"}}]}`, installationID)
+ case "/user":
+ if r.Header.Get("Authorization") != "Bearer test-user-token" {
+ t.Error("identity must use the user token")
+ }
+ fmt.Fprint(w, `{"id":123}`)
+ case "/applications/test-client/token":
+ id, secret, _ := r.BasicAuth()
+ var body struct {
+ AccessToken string `json:"access_token"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Error(err)
+ }
+ if r.Method != http.MethodDelete || id != "test-client" || secret != "test-client-secret" || body.AccessToken != "test-user-token" {
+ t.Error("incorrect token revocation request")
+ }
+ w.WriteHeader(http.StatusNoContent)
+ default:
+ return false
+ }
+ return true
+}
+
+func TestGitHubSetupOwnershipFailuresNeverBind(t *testing.T) {
+ t.Setenv("GITHUB_WEBHOOK_SECRET", "ownership-test-secret")
+ for _, mode := range []string{"foreign_installation", "exchange_rejected", "api_unavailable", "malformed_api", "missing_credentials"} {
+ t.Run(mode, func(t *testing.T) {
+ installationID := time.Now().UnixNano()
+ victimWS := dbfx.Workspace(t, "Victim", fmt.Sprintf("victim-%d", installationID))
+ victimID := dbfx.Insert(t, "github_installation", testutil.Cols{
+ "workspace_id": victimWS, "installation_id": installationID,
+ "account_login": "victim-org", "account_type": "Organization",
+ })
+ var revoked atomic.Int32
+ stubGitHubOwnership(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/applications/test-client/token" {
+ revoked.Add(1)
+ }
+ if mode == "exchange_rejected" && r.URL.Path == "/login/oauth/access_token" {
+ fmt.Fprint(w, `{"error":"bad_verification_code"}`)
+ return
+ }
+ if r.URL.Path == "/user/installations" {
+ switch mode {
+ case "api_unavailable":
+ http.Error(w, "unavailable", http.StatusServiceUnavailable)
+ return
+ case "malformed_api":
+ fmt.Fprint(w, `{`)
+ return
+ }
+ }
+ if !serveGitHubOwnership(t, w, r, installationID-1) {
+ t.Errorf("unverified callback fetched installation metadata: %s", r.URL.Path)
+ http.NotFound(w, r)
+ }
+ })
+ if mode == "missing_credentials" {
+ t.Setenv("GITHUB_APP_CLIENT_SECRET", "")
+ }
+ state, err := signState(testWorkspaceID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/github/setup?installation_id=%d&code=valid-code&state=%s", installationID, url.QueryEscape(state)), nil)
+ rec := httptest.NewRecorder()
+ testHandler.GitHubSetupCallback(rec, req)
+ wantError := "verification_failed"
+ if mode == "foreign_installation" {
+ wantError = "installation_not_authorized"
+ }
+ if rec.Code != http.StatusFound || !strings.Contains(rec.Header().Get("Location"), "github_error="+wantError) {
+ t.Fatalf("callback = %d %s", rec.Code, rec.Header().Get("Location"))
+ }
+ rows, err := testHandler.Queries.ListGitHubInstallationsByInstallationID(req.Context(), installationID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(rows) != 1 || uuidToString(rows[0].ID) != victimID || uuidToString(rows[0].WorkspaceID) != victimWS {
+ t.Fatalf("foreign installation bindings changed: %+v", rows)
+ }
+ wantRevocations := int32(1)
+ if mode == "exchange_rejected" || mode == "missing_credentials" {
+ wantRevocations = 0
+ }
+ if revoked.Load() != wantRevocations {
+ t.Fatalf("revocations = %d, want %d", revoked.Load(), wantRevocations)
+ }
+ })
+ }
+}
+
+func TestGitHubSetupExistingBindingNeedsNoCode(t *testing.T) {
+ t.Setenv("GITHUB_WEBHOOK_SECRET", "ownership-test-secret")
+ t.Setenv("GITHUB_APP_CLIENT_ID", "")
+ t.Setenv("GITHUB_APP_CLIENT_SECRET", "")
+ installationID := time.Now().UnixNano()
+ rowID := dbfx.Insert(t, "github_installation", testutil.Cols{
+ "workspace_id": testWorkspaceID, "installation_id": installationID,
+ "account_login": "existing-org", "account_type": "Organization", "connected_by_id": testUserID,
+ })
+ state, err := signState(testWorkspaceID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/github/setup?installation_id=%d&state=%s", installationID, url.QueryEscape(state)), nil)
+ rec := httptest.NewRecorder()
+ testHandler.GitHubSetupCallback(rec, req)
+ if rec.Code != http.StatusFound || !strings.Contains(rec.Header().Get("Location"), "github_connected=1") {
+ t.Fatalf("update = %d %s", rec.Code, rec.Header().Get("Location"))
+ }
+ row, err := testHandler.Queries.GetGitHubInstallationByID(req.Context(), parseUUID(rowID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if row.AccountLogin != "existing-org" || uuidToString(row.ConnectedByID) != testUserID {
+ t.Fatalf("update changed existing binding: %+v", row)
+ }
+}
+
+func TestGitHubSetupRejectsReadOnlyCollaborator(t *testing.T) {
+ t.Setenv("GITHUB_WEBHOOK_SECRET", "collaborator-test-secret")
+ pemBytes, _ := generateTestRSAKeyPEM(t)
+ t.Setenv("GITHUB_APP_ID", "11111")
+ t.Setenv("GITHUB_APP_PRIVATE_KEY", string(pemBytes))
+ installationID := time.Now().UnixNano()
+ stubGitHubOwnership(t, func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/user/installations":
+ fmt.Fprintf(w, `{"installations":[{"id":%d,"account":{"id":123,"type":"Organization"}}]}`, installationID)
+ case fmt.Sprintf("/user/installations/%d/repositories", installationID):
+ fmt.Fprint(w, `{"total_count":1,"repositories":[{"id":1,"permissions":{"admin":false,"pull":true}}]}`)
+ default:
+ if !serveGitHubOwnership(t, w, r, installationID) {
+ fmt.Fprint(w, `{"account":{"login":"victim-org","type":"Organization"}}`)
+ }
+ }
+ })
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM github_installation WHERE installation_id = $1`, installationID)
+ })
+ state, err := signState(testWorkspaceID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/github/setup?installation_id=%d&code=valid-code&state=%s", installationID, url.QueryEscape(state)), nil)
+ rec := httptest.NewRecorder()
+ testHandler.GitHubSetupCallback(rec, req)
+ rows, err := testHandler.Queries.ListGitHubInstallationsByInstallationID(req.Context(), installationID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(rows) != 0 {
+ t.Fatalf("read-only collaborator created %d installation bindings", len(rows))
+ }
+ if !strings.Contains(rec.Header().Get("Location"), "github_error=installation_not_authorized") {
+ t.Fatalf("callback = %d %s", rec.Code, rec.Header().Get("Location"))
+ }
+}
+
+func TestGitHubOwnershipPaginationAndRevocation(t *testing.T) {
+ var pages, revoked atomic.Int32
+ stubGitHubOwnership(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/applications/test-client/token" {
+ revoked.Add(1)
+ }
+ if r.URL.Path == "/user/installations" {
+ pages.Add(1)
+ if r.URL.Query().Get("per_page") != "100" {
+ t.Error("missing page size")
+ }
+ if r.URL.Query().Get("page") == "1" {
+ installations := make([]map[string]int64, 100)
+ for i := range installations {
+ installations[i] = map[string]int64{"id": int64(i + 1)}
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"installations": installations})
+ return
+ }
+ }
+ if !serveGitHubOwnership(t, w, r, 999) {
+ http.NotFound(w, r)
+ }
+ })
+ if err := verifyGitHubInstallationOwnership(context.Background(), "valid-code", 999); err != nil {
+ t.Fatal(err)
+ }
+ if pages.Load() != 2 || revoked.Load() != 1 {
+ t.Fatalf("pages=%d revocations=%d", pages.Load(), revoked.Load())
+ }
+}
+
+func TestGitHubSetupRequiresAdministrationOfAllInstallationRepositories(t *testing.T) {
+ for _, mode := range []string{"all_admin", "partial_access", "different_repositories", "missing_admin", "empty_installation", "admin_on_later_page", "read_on_later_page", "app_unavailable", "missing_app_credentials"} {
+ t.Run(mode, func(t *testing.T) {
+ t.Setenv("GITHUB_WEBHOOK_SECRET", "repository-admin-secret")
+ pemBytes, _ := generateTestRSAKeyPEM(t)
+ t.Setenv("GITHUB_APP_ID", "11111")
+ t.Setenv("GITHUB_APP_PRIVATE_KEY", string(pemBytes))
+ installationID := time.Now().UnixNano()
+ var userRevoked, appRevoked, userPages, appPages atomic.Int32
+ stubGitHubOwnership(t, func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/user/installations":
+ fmt.Fprintf(w, `{"installations":[{"id":%d,"account":{"id":123,"type":"Organization"}}]}`, installationID)
+ case fmt.Sprintf("/app/installations/%d/access_tokens", installationID):
+ var body struct {
+ Permissions map[string]string `json:"permissions"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Error(err)
+ }
+ if len(body.Permissions) != 1 || body.Permissions["metadata"] != "read" {
+ t.Errorf("proof token permissions: %+v", body.Permissions)
+ }
+ if r.Method != http.MethodPost || !strings.HasPrefix(r.Header.Get("Authorization"), "Bearer ey") {
+ t.Error("metadata token must use App JWT")
+ }
+ writeJSON(w, http.StatusCreated, map[string]any{"token": "app-proof-token"})
+ case "/installation/token":
+ if r.Method != http.MethodDelete || r.Header.Get("Authorization") != "Bearer app-proof-token" {
+ t.Error("incorrect App token revocation")
+ }
+ appRevoked.Add(1)
+ w.WriteHeader(http.StatusNoContent)
+ case fmt.Sprintf("/user/installations/%d/repositories", installationID), "/installation/repositories":
+ isUser := strings.HasPrefix(r.URL.Path, "/user/")
+ wantToken := "Bearer app-proof-token"
+ if isUser {
+ userPages.Add(1)
+ wantToken = "Bearer test-user-token"
+ } else {
+ appPages.Add(1)
+ }
+ if r.Header.Get("Authorization") != wantToken {
+ t.Errorf("incorrect repository-list token for %s", r.URL.Path)
+ }
+ if !isUser && mode == "app_unavailable" {
+ http.Error(w, "unavailable", http.StatusServiceUnavailable)
+ return
+ }
+ count := 1
+ if mode == "empty_installation" {
+ count = 0
+ }
+ if !isUser && mode == "partial_access" {
+ count = 2
+ }
+ if mode == "admin_on_later_page" || mode == "read_on_later_page" {
+ count = 101
+ }
+ start := 1
+ if r.URL.Query().Get("page") == "2" {
+ start = 101
+ }
+ repos := []map[string]any{}
+ for id := start; id <= count && id < start+100; id++ {
+ repoID := id
+ if !isUser && mode == "different_repositories" {
+ repoID = 2
+ }
+ item := map[string]any{"id": repoID}
+ if isUser && mode != "missing_admin" {
+ item["permissions"] = map[string]bool{"admin": mode != "read_on_later_page" || id != 101, "pull": true}
+ }
+ repos = append(repos, item)
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"total_count": count, "repositories": repos})
+ case "/applications/test-client/token":
+ userRevoked.Add(1)
+ serveGitHubOwnership(t, w, r, installationID)
+ default:
+ if !serveGitHubOwnership(t, w, r, installationID) {
+ writeJSON(w, http.StatusOK, map[string]any{"account": map[string]any{"login": "admin-org", "type": "Organization"}})
+ }
+ }
+ })
+ if mode == "missing_app_credentials" {
+ t.Setenv("GITHUB_APP_PRIVATE_KEY", "")
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM github_installation WHERE installation_id = $1`, installationID)
+ })
+ state, err := signState(testWorkspaceID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/github/setup?installation_id=%d&code=valid-code&state=%s", installationID, url.QueryEscape(state)), nil)
+ rec := httptest.NewRecorder()
+ testHandler.GitHubSetupCallback(rec, req)
+ rows, err := testHandler.Queries.ListGitHubInstallationsByInstallationID(req.Context(), installationID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ allowed := mode == "all_admin" || mode == "admin_on_later_page"
+ wantRows := 0
+ wantQuery := "github_error=installation_not_authorized"
+ if allowed {
+ wantRows = 1
+ wantQuery = "github_connected=1"
+ }
+ if mode == "app_unavailable" || mode == "missing_app_credentials" {
+ wantQuery = "github_error=verification_failed"
+ }
+ if len(rows) != wantRows || !strings.Contains(rec.Header().Get("Location"), wantQuery) {
+ t.Fatalf("bindings=%d callback=%d %s", len(rows), rec.Code, rec.Header().Get("Location"))
+ }
+ if userRevoked.Load() != 1 {
+ t.Fatalf("user token revocations = %d", userRevoked.Load())
+ }
+ wantAppRevoked := int32(1)
+ if mode == "missing_admin" || mode == "empty_installation" || mode == "read_on_later_page" || mode == "missing_app_credentials" {
+ wantAppRevoked = 0
+ }
+ if appRevoked.Load() != wantAppRevoked {
+ t.Fatalf("App token revocations=%d want=%d", appRevoked.Load(), wantAppRevoked)
+ }
+ if mode == "admin_on_later_page" && (userPages.Load() != 2 || appPages.Load() != 2) {
+ t.Fatalf("user pages=%d App pages=%d", userPages.Load(), appPages.Load())
+ }
+ })
+ }
+}
+
+func TestGitHubPersonalInstallationRequiresAccountOwner(t *testing.T) {
+ for _, mode := range []string{"owner", "collaborator", "missing_identity", "identity_unavailable"} {
+ t.Run(mode, func(t *testing.T) {
+ stubGitHubOwnership(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/user" {
+ switch mode {
+ case "collaborator":
+ fmt.Fprint(w, `{"id":456}`)
+ case "missing_identity":
+ fmt.Fprint(w, `{}`)
+ case "identity_unavailable":
+ http.Error(w, "unavailable", http.StatusServiceUnavailable)
+ default:
+ fmt.Fprint(w, `{"id":123}`)
+ }
+ return
+ }
+ if !serveGitHubOwnership(t, w, r, 999) {
+ t.Errorf("unexpected endpoint: %s", r.URL.Path)
+ http.NotFound(w, r)
+ }
+ })
+ err := verifyGitHubInstallationOwnership(context.Background(), "valid-code", 999)
+ if (err == nil) != (mode == "owner") {
+ t.Fatalf("owner verification: %v", err)
+ }
+ })
+ }
+}
+
+func TestGitHubStateExpiry(t *testing.T) {
+ t.Setenv("GITHUB_WEBHOOK_SECRET", "expiry-test-secret")
+ for _, tc := range []struct {
+ nonce string
+ want bool
+ }{
+ {fmt.Sprintf("%d-nonce", time.Now().Add(-14*time.Minute).Unix()), true},
+ {fmt.Sprintf("desktop-%d-nonce", time.Now().Add(-14*time.Minute).Unix()), true},
+ {fmt.Sprintf("%d-nonce", time.Now().Add(-16*time.Minute).Unix()), false},
+ {fmt.Sprintf("%d-nonce", time.Now().Add(2*time.Minute).Unix()), false},
+ {"old-nonce", false},
+ } {
+ payload := testWorkspaceID + "." + tc.nonce
+ mac := hmac.New(sha256.New, []byte("expiry-test-secret"))
+ mac.Write([]byte(payload))
+ if _, _, ok := verifyGitHubState(payload + "." + hex.EncodeToString(mac.Sum(nil))); ok != tc.want {
+ t.Errorf("nonce %q: ok=%v", tc.nonce, ok)
+ }
+ }
+}
+
+func TestGitHubConnectRequiresOAuthCredentials(t *testing.T) {
+ t.Setenv("GITHUB_APP_SLUG", "test-app")
+ t.Setenv("GITHUB_WEBHOOK_SECRET", "test-secret")
+ t.Setenv("GITHUB_APP_CLIENT_ID", "test-client")
+ t.Setenv("GITHUB_APP_CLIENT_SECRET", "test-client-secret")
+ t.Setenv("GITHUB_APP_ID", "11111")
+ t.Setenv("GITHUB_APP_PRIVATE_KEY", "configured-key")
+ if !isGitHubConfigured() {
+ t.Fatal("fully configured Connect disabled")
+ }
+ for _, key := range []string{"GITHUB_APP_CLIENT_ID", "GITHUB_APP_CLIENT_SECRET", "GITHUB_APP_ID", "GITHUB_APP_PRIVATE_KEY"} {
+ t.Run(key, func(t *testing.T) {
+ t.Setenv(key, "")
+ if isGitHubConfigured() {
+ t.Fatal("Connect enabled without OAuth credentials")
+ }
+ })
+ }
+}
diff --git a/server/internal/handler/github_test.go b/server/internal/handler/github_test.go
index b203ad6cc8..137e801843 100644
--- a/server/internal/handler/github_test.go
+++ b/server/internal/handler/github_test.go
@@ -310,14 +310,18 @@ func TestGitHubStateDesktopAndLegacyLinks(t *testing.T) {
mac := hmac.New(sha256.New, []byte("test-secret-123"))
mac.Write([]byte(payload))
token := payload + "." + hex.EncodeToString(mac.Sum(nil))
- if got, ok := verifyState(token); !ok || got != wsID {
- t.Fatalf("legacy %s rejected", target)
+ if _, ok := verifyState(token); ok {
+ t.Fatalf("untimed legacy %s state accepted", target)
}
}
}
func TestGitHubConnectUsesUnifiedState(t *testing.T) {
t.Setenv("GITHUB_APP_SLUG", "multica-test")
+ t.Setenv("GITHUB_APP_ID", "11111")
+ t.Setenv("GITHUB_APP_PRIVATE_KEY", "configured-key")
+ t.Setenv("GITHUB_APP_CLIENT_ID", "test-client")
+ t.Setenv("GITHUB_APP_CLIENT_SECRET", "test-client-secret")
t.Setenv("GITHUB_WEBHOOK_SECRET", "test-secret-123")
wsID := "11111111-2222-3333-4444-555555555555"
for _, platform := range []string{"web", "legacy-desktop", "desktop"} {
@@ -354,27 +358,28 @@ func TestGitHubSetupCallbackReturnsToInitiatingClient(t *testing.T) {
t.Setenv("FRONTEND_ORIGIN", "https://app.multica.test")
t.Setenv("GITHUB_APP_ID", "")
t.Setenv("GITHUB_APP_PRIVATE_KEY", "")
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ installationID := time.Now().UnixNano()
+ stubGitHubOwnership(t, func(w http.ResponseWriter, r *http.Request) {
+ if serveGitHubOwnership(t, w, r, installationID) {
+ return
+ }
writeJSON(w, http.StatusOK, map[string]any{"account": map[string]any{"login": "example-org", "type": "Organization"}})
- }))
- t.Cleanup(srv.Close)
- oldBase := githubAPIBase
- githubAPIBase = srv.URL
- t.Cleanup(func() { githubAPIBase = oldBase })
+ })
workspace, err := testHandler.Queries.GetWorkspace(context.Background(), parseUUID(testWorkspaceID))
if err != nil {
t.Fatal(err)
}
- installationID := time.Now().UnixNano()
t.Cleanup(func() {
testPool.Exec(context.Background(), `DELETE FROM github_installation WHERE installation_id = $1`, installationID)
})
for _, desktop := range []bool{false, true} {
+ // Each client must exercise a new OAuth-verified binding.
+ testPool.Exec(context.Background(), `DELETE FROM github_installation WHERE installation_id = $1`, installationID)
state, err := signGitHubState(testWorkspaceID, desktop)
if err != nil {
t.Fatal(err)
}
- req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/github/setup?installation_id=%d&state=%s", installationID, url.QueryEscape(state)), nil)
+ req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/github/setup?installation_id=%d&code=valid-code&state=%s", installationID, url.QueryEscape(state)), nil)
rec := httptest.NewRecorder()
testHandler.GitHubSetupCallback(rec, req)
if desktop {
@@ -2863,13 +2868,12 @@ func TestSetupCallback_ConsumesPendingInstallationCreated(t *testing.T) {
// Force fetchInstallationAccount to take its degraded path. This pins that
// the final real account name comes from the earlier webhook, not the
// setup callback's synchronous GitHub API lookup.
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ stubGitHubOwnership(t, func(w http.ResponseWriter, r *http.Request) {
+ if serveGitHubOwnership(t, w, r, installationID) {
+ return
+ }
http.Error(w, "auth required", http.StatusUnauthorized)
- }))
- t.Cleanup(srv.Close)
- oldBase := githubAPIBase
- githubAPIBase = srv.URL
- t.Cleanup(func() { githubAPIBase = oldBase })
+ })
body, _ := json.Marshal(map[string]any{
"action": "created",
@@ -2909,7 +2913,7 @@ func TestSetupCallback_ConsumesPendingInstallationCreated(t *testing.T) {
t.Fatalf("signState: %v", err)
}
setupReq := httptest.NewRequest("GET",
- fmt.Sprintf("/api/github/setup?installation_id=%d&state=%s", installationID, state),
+ fmt.Sprintf("/api/github/setup?installation_id=%d&code=valid-code&state=%s", installationID, state),
nil,
)
setupRec := httptest.NewRecorder()