Skip to content

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

Go

fix(github): populate connected account name on install [MUL-3078] (#3811)

Multica Eve905ebbdde1a0
diff --git a/.env.example b/.env.example
index c756c7e332..c528bd141c 100644
--- a/.env.example
+++ b/.env.example
@@ -199,6 +199,16 @@ CORS_ALLOWED_ORIGINS=
# GITHUB_APP_SLUG is the tail of https://github.com/apps/<slug>.
GITHUB_APP_SLUG=
GITHUB_WEBHOOK_SECRET=
+# Optional: GitHub App identity for App-authenticated REST calls. When set,
+# the setup callback enriches the installation row with the real account
+# login (org / user name) immediately after install. When unset, the row
+# is created with the "unknown" placeholder and the next `installation`
+# webhook from GitHub overwrites it — set both to skip that interim flash.
+# GITHUB_APP_ID is the numeric "App ID" shown on the App's settings page.
+# GITHUB_APP_PRIVATE_KEY is the full PEM block (including BEGIN/END lines)
+# generated under "Private keys" on that same page; preserve newlines.
+GITHUB_APP_ID=
+GITHUB_APP_PRIVATE_KEY=
# Lark / Feishu bot integration (Settings → Integrations "Bind to Lark")
# Off until MULTICA_LARK_SECRET_KEY is set — a base64-encoded 32-byte key
diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdx
index c9c7e3d5fd..334aaa24cf 100644
--- a/apps/docs/content/docs/environment-variables.ja.mdx
+++ b/apps/docs/content/docs/environment-variables.ja.mdx
@@ -198,18 +198,24 @@ S3 の前段に CloudFront を置く場合、3 つの変数が適用されます
## GitHub 連携
-[GitHub PR ↔ イシュー連携](/github-integration)には 2 つの変数が必要です。設定で Connect GitHub を有効にし、受信 webhook を受け付けるには両方を設定してください。
+[GitHub PR ↔ イシュー連携](/github-integration)には 2 つの必須変数が必要です。設定で Connect GitHub を有効にし、受信 webhook を受け付けるには両方を設定してください。さらに 2 つの任意変数を設定すると、インストール時点で連携先のアカウント名を取得できます。
| 変数 | デフォルト | 説明 |
|---|---|---|
| `GITHUB_APP_SLUG` | 空 | GitHub App の slug(`https://github.com/apps/<slug>` の末尾部分)。設定 → GitHub のインストールボタン URL を構成します |
| `GITHUB_WEBHOOK_SECRET` | 空 | GitHub App に設定した Webhook secret。すべての `pull_request` / `installation` delivery の HMAC-SHA256 検証に使われ、setup コールバックの state token の HMAC キーとしても使われます |
+| `GITHUB_APP_ID` | 空 | 任意。App 設定ページに表示される数値の App ID。`GITHUB_APP_PRIVATE_KEY` と併せて設定すると、setup コールバックがインストール時点で GitHub から連携先のアカウント名を取得できます |
+| `GITHUB_APP_PRIVATE_KEY` | 空 | 任意。App の RSA 秘密鍵の完全な PEM ブロック(`-----BEGIN/END-----` 行を含み、改行を保ったまま)。GitHub の App 認証 REST 呼び出しに必要な短命 JWT の発行に使われます |
-**どちらかが設定されていない場合の動作:**
+**いずれかの必須変数が設定されていない場合の動作:**
- 設定 → GitHub の `Connect GitHub` が**無効**になり、admin に「not configured」というヒントを表示します。
- `/api/webhooks/github` エンドポイントは **`503 github webhooks not configured`** を返します — Multica はすべての署名を有効として扱うのではなく、secret なしではイベント処理を拒否します。
+**任意の `GITHUB_APP_ID` / `GITHUB_APP_PRIVATE_KEY` が設定されていない場合の動作:**
+
+- インストール直後、接続カードには一時的に `Connected to unknown` と表示されます。GitHub から `installation.created` webhook が届くと(通常は数秒以内)、Multica は行を実際の組織名/ユーザー名に更新し、リアルタイムブロードキャストを発行するため、開いている Settings → GitHub タブは手動更新なしで反映されます。
+
**注:** `GITHUB_WEBHOOK_SECRET` はインストールフローの state token の署名キーとして再利用されるため、運用者は secret を 1 つだけ管理すればよいです。これは GitHub App の *Client* secret では**ありません** — Client secret は OAuth 関連であり、この連携では使われません。完全な手順は [GitHub 連携 → セルフホストのセットアップ](/github-integration#self-host-setup)を参照してください。
## 使用量分析
diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdx
index 02d6834e5d..7de0720977 100644
--- a/apps/docs/content/docs/environment-variables.ko.mdx
+++ b/apps/docs/content/docs/environment-variables.ko.mdx
@@ -198,18 +198,24 @@ S3 앞에 CloudFront를 두는 경우 세 가지 변수가 적용됩니다: `CLO
## GitHub 연동
-[GitHub PR ↔ 이슈 연동](/github-integration)에는 두 개의 변수가 필요합니다. 설정에서 Connect GitHub를 활성화하고 들어오는 webhook을 수락하려면 둘 다 설정하세요.
+[GitHub PR ↔ 이슈 연동](/github-integration)에는 두 개의 필수 변수가 필요합니다. 설정에서 Connect GitHub를 활성화하고 들어오는 webhook을 수락하려면 둘 다 설정하세요. 추가로 두 개의 선택 변수를 설정하면 설치 시점에 연결된 계정 이름을 즉시 가져올 수 있습니다.
| 변수 | 기본값 | 설명 |
|---|---|---|
| `GITHUB_APP_SLUG` | 비어 있음 | GitHub App의 slug (`https://github.com/apps/<slug>`의 끝부분). 설정 → GitHub 설치 버튼 URL을 구성합니다 |
| `GITHUB_WEBHOOK_SECRET` | 비어 있음 | GitHub App에 설정한 Webhook secret. 모든 `pull_request` / `installation` delivery의 HMAC-SHA256 검증에 사용되며, setup 콜백 state token의 HMAC 키로도 사용됩니다 |
+| `GITHUB_APP_ID` | 비어 있음 | 선택. App 설정 페이지에 표시되는 숫자 App ID. `GITHUB_APP_PRIVATE_KEY`와 함께 설정하면 setup 콜백이 설치 시점에 GitHub에서 연결된 계정 이름을 가져올 수 있습니다 |
+| `GITHUB_APP_PRIVATE_KEY` | 비어 있음 | 선택. App RSA 비공개 키의 전체 PEM 블록 (`-----BEGIN/END-----` 줄 포함, 줄바꿈 유지). GitHub의 App 인증 REST 호출에 필요한 단명 JWT를 발급하는 데 사용됩니다 |
-**둘 중 하나라도 설정하지 않았을 때의 동작:**
+**필수 변수 중 하나라도 설정하지 않았을 때의 동작:**
- 설정 → GitHub의 `Connect GitHub`가 **비활성화**되고 admin에게 "not configured" 힌트를 표시합니다.
- `/api/webhooks/github` 엔드포인트는 **`503 github webhooks not configured`**를 반환합니다 — Multica는 모든 서명을 유효한 것으로 취급하기보다, secret 없이는 이벤트 처리를 거부합니다.
+**선택 `GITHUB_APP_ID` / `GITHUB_APP_PRIVATE_KEY`가 설정되지 않았을 때의 동작:**
+
+- 설치 직후 연결 카드에 잠시 `Connected to unknown`이 표시됩니다. GitHub의 `installation.created` 웹훅이 도착하면(보통 몇 초 이내) Multica가 행을 실제 조직/사용자 이름으로 갱신하고 실시간 브로드캐스트를 보내, 열려 있는 Settings → GitHub 탭이 수동 새로고침 없이 업데이트됩니다.
+
**참고:** `GITHUB_WEBHOOK_SECRET`은 설치 흐름 state token의 서명 키로 재사용되므로, 운영자는 secret 하나만 관리하면 됩니다. 이것은 GitHub App의 *Client* secret이 **아닙니다** — Client secret은 OAuth 관련이며 이 연동에서는 사용되지 않습니다. 전체 안내는 [GitHub 연동 → 자체 호스팅 설정](/github-integration#self-host-setup)을 참고하세요.
## 사용량 분석
diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdx
index 6f22985aa7..10ec0f1b52 100644
--- a/apps/docs/content/docs/environment-variables.mdx
+++ b/apps/docs/content/docs/environment-variables.mdx
@@ -200,18 +200,24 @@ For a full explanation of how each parameter affects daemon behavior, see [Daemo
## GitHub integration
-The [GitHub PR ↔ issue integration](/github-integration) needs two variables. Set both to enable Connect GitHub in Settings and accept incoming webhooks.
+The [GitHub PR ↔ issue integration](/github-integration) needs two variables. Set both to enable Connect GitHub in Settings and accept incoming webhooks. Two additional variables are optional but populate the connected account name on install.
| Variable | Default | Description |
|---|---|---|
| `GITHUB_APP_SLUG` | empty | The slug of your GitHub App (the tail of `https://github.com/apps/<slug>`). Drives the Settings → GitHub install button URL |
| `GITHUB_WEBHOOK_SECRET` | empty | The Webhook secret you set on the GitHub App. Used for HMAC-SHA256 verification of every `pull_request` / `installation` delivery, and as the HMAC key for the setup-callback state token |
+| `GITHUB_APP_ID` | empty | Optional. Numeric App ID from the App's settings page. Combined with `GITHUB_APP_PRIVATE_KEY`, lets the setup callback fetch the connected account name from GitHub immediately on install |
+| `GITHUB_APP_PRIVATE_KEY` | empty | Optional. Full PEM block of the App's RSA private key (including `-----BEGIN/END-----` lines, newlines preserved). Used to mint the short-lived JWT GitHub requires for App-authenticated REST calls |
-**Behavior when either is unset:**
+**Behavior when either of the required variables is unset:**
- `Connect GitHub` in Settings → GitHub is **disabled** and shows a "not configured" hint to admins.
- The `/api/webhooks/github` endpoint returns **`503 github webhooks not configured`** — Multica refuses to process events with no secret rather than treating every signature as valid.
+**Behavior when the optional `GITHUB_APP_ID` / `GITHUB_APP_PRIVATE_KEY` are unset:**
+
+- The connection card briefly shows `Connected to unknown` after install. Multica refreshes the row to the real org/user name as soon as GitHub delivers the `installation.created` webhook (typically within a few seconds), and broadcasts a realtime update so any open Settings → GitHub tab reflects the change without a manual refresh.
+
**Note:** `GITHUB_WEBHOOK_SECRET` is reused as the signing key for the install-flow state token, so operators only need to manage one secret. It is **not** the GitHub App's *Client* secret — Client secrets are OAuth-related and not used by this integration. See [GitHub integration → Self-host setup](/github-integration#self-host-setup) for the full walkthrough.
## Usage analytics
diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdx
index d3f8c2c37e..842772f415 100644
--- a/apps/docs/content/docs/environment-variables.zh.mdx
+++ b/apps/docs/content/docs/environment-variables.zh.mdx
@@ -203,18 +203,24 @@ API 返回的 `download_url` 在未配置 CloudFront 签名时会指向 `GET /ap
## GitHub 集成
-[GitHub PR ↔ issue 集成](/github-integration) 依赖两个环境变量。两个都配上才会启用 Settings 里的 Connect GitHub 并接受 webhook。
+[GitHub PR ↔ issue 集成](/github-integration) 依赖两个必填环境变量。两个都配上才会启用 Settings 里的 Connect GitHub 并接受 webhook。另外两个可选变量用于在安装时直接拿到关联账号名。
| 环境变量 | 默认值 | 说明 |
|---|---|---|
| `GITHUB_APP_SLUG` | 空 | 你的 GitHub App slug(`https://github.com/apps/<slug>` 的尾部)。Settings → GitHub 里安装按钮的跳转 URL 用它拼 |
| `GITHUB_WEBHOOK_SECRET` | 空 | 你在 GitHub App 上设置的 Webhook secret。每条 `pull_request` / `installation` delivery 都用它做 HMAC-SHA256 校验;同一个值也用作 setup 回调里 state token 的签名密钥 |
+| `GITHUB_APP_ID` | 空 | 可选。App 设置页上的数字 App ID。配合 `GITHUB_APP_PRIVATE_KEY` 使用,让 setup 回调在安装那一刻直接从 GitHub 取到关联账号名 |
+| `GITHUB_APP_PRIVATE_KEY` | 空 | 可选。App RSA 私钥的完整 PEM 块(包含 `-----BEGIN/END-----` 两行,保留换行)。用于签发 GitHub App 鉴权 REST 调用所需的短效 JWT |
-**任一变量未设时:**
+**任一必填变量未设时:**
- Settings → GitHub 里 `Connect GitHub` 按钮 **disable**,对 admin 显示「not configured」提示
- `/api/webhooks/github` 直接返回 **`503 github webhooks not configured`**——secret 没配置时 Multica 拒绝处理任何 webhook 事件,而不是把所有签名当 valid
+**可选 `GITHUB_APP_ID` / `GITHUB_APP_PRIVATE_KEY` 未设时:**
+
+- 安装完成后,连接卡片会先短暂显示 `已连接到 unknown`。等 GitHub 的 `installation.created` webhook 到达(通常几秒内),Multica 会把 row 刷成真实的组织/用户名,并通过 realtime 推送让正在打开的 Settings → GitHub 页面无需手动刷新即可更新。
+
**注意:** `GITHUB_WEBHOOK_SECRET` 同时被复用为 install 流程里 state token 的签名密钥,所以运维只需要维护一个 secret。它**不是** GitHub App 的 *Client* secret——Client secret 是 OAuth 用的,和本集成无关。完整配置流程见 [GitHub 集成 → Self-Host 配置](/github-integration#self-host-配置)。
## 用量统计
diff --git a/apps/docs/content/docs/github-integration.ja.mdx b/apps/docs/content/docs/github-integration.ja.mdx
index 419ed20029..63783835cf 100644
--- a/apps/docs/content/docs/github-integration.ja.mdx
+++ b/apps/docs/content/docs/github-integration.ja.mdx
@@ -114,13 +114,20 @@ API サーバーで:
```dotenv
GITHUB_APP_SLUG=multica-acme
GITHUB_WEBHOOK_SECRET=<the webhook secret you generated>
+
+# 任意(推奨)— インストール時点で接続済みアカウント名を取得できるため、
+# 最初の webhook が届くまで待たなくて済みます:
+GITHUB_APP_ID=<App 設定ページに表示される数値の App ID>
+GITHUB_APP_PRIVATE_KEY=<BEGIN/END 行を含む完全な PEM ブロック>
```
-両方の変数が必須です。どちらかが欠けていると:
+`GITHUB_APP_SLUG` と `GITHUB_WEBHOOK_SECRET` は必須です。どちらかが欠けていると:
- Settings の `Connect GitHub` が**無効**になり、「not configured」のヒントが表示されます。
- `/api/webhooks/github` エンドポイントが **`503 github webhooks not configured`** を返します — Multica は secret なしでイベントを処理することを拒否し、すべての署名を黙って有効として扱うことはありません。
+`GITHUB_APP_ID` と `GITHUB_APP_PRIVATE_KEY` は**任意**です。これらを設定すると、setup コールバックが GitHub の App 認証された `/app/installations/{id}` エンドポイントを呼び出して、インストール時点で実際の組織名やユーザー名を取得できます。設定しない場合、接続カードには一時的に `Connected to unknown` と表示され、GitHub から `installation.created` webhook が届くと(通常は数秒以内に)Multica が行を更新し、リアルタイムブロードキャストを発行するため、開いている Settings タブは手動更新なしで反映されます。秘密鍵は App 設定ページの **Private keys → Generate a private key** で生成し、PEM ブロック全体(`-----BEGIN/END RSA PRIVATE KEY-----` の行を含む)を改行を保ったまま env 変数に貼り付けてください。
+
`FRONTEND_ORIGIN` も設定されている必要があります(どのプロダクションのセルフホストでもすでに設定されています)。インストール後、setup コールバックがユーザーを `<FRONTEND_ORIGIN>/settings?tab=github` に戻します。
env 変数を設定した後は API を再起動してください。
diff --git a/apps/docs/content/docs/github-integration.ko.mdx b/apps/docs/content/docs/github-integration.ko.mdx
index 384f625dfb..2803ac959d 100644
--- a/apps/docs/content/docs/github-integration.ko.mdx
+++ b/apps/docs/content/docs/github-integration.ko.mdx
@@ -114,13 +114,20 @@ API 서버에서:
```dotenv
GITHUB_APP_SLUG=multica-acme
GITHUB_WEBHOOK_SECRET=<the webhook secret you generated>
+
+# 선택(권장) — 설치 직후 연결된 계정 이름을 바로 확보합니다.
+# 설정하지 않으면 첫 webhook이 도착할 때까지 대기해야 합니다:
+GITHUB_APP_ID=<App 설정 페이지에 표시되는 숫자 App ID>
+GITHUB_APP_PRIVATE_KEY=<BEGIN/END 줄을 포함한 전체 PEM 블록>
```
-두 변수 모두 필수입니다. 둘 중 하나라도 누락되면:
+`GITHUB_APP_SLUG`와 `GITHUB_WEBHOOK_SECRET`은 필수입니다. 둘 중 하나라도 누락되면:
- Settings의 `Connect GitHub`이 **비활성화**되고 "not configured" 힌트가 표시됩니다.
- `/api/webhooks/github` 엔드포인트가 **`503 github webhooks not configured`**를 반환합니다 — Multica는 secret 없이 이벤트를 처리하기를 거부하며, 모든 서명을 조용히 유효한 것으로 취급하지 않습니다.
+`GITHUB_APP_ID`와 `GITHUB_APP_PRIVATE_KEY`는 **선택 사항**입니다. 설정하면 setup 콜백이 GitHub의 App 인증 `/app/installations/{id}` 엔드포인트를 호출해 설치 직후에 실제 조직명/사용자명을 가져옵니다. 설정하지 않으면 연결 카드에 잠시 `Connected to unknown`이 표시되며, GitHub의 `installation.created` 웹훅이 도착하면(보통 몇 초 이내) Multica가 행을 갱신하고 실시간 브로드캐스트를 보내므로 열려 있는 Settings 탭이 수동 새로고침 없이 업데이트됩니다. 비공개 키는 App 설정 페이지의 **Private keys → Generate a private key**에서 생성한 뒤, PEM 블록 전체(`-----BEGIN/END RSA PRIVATE KEY-----` 줄 포함)를 줄바꿈을 유지한 채 env 값에 붙여넣으세요.
+
`FRONTEND_ORIGIN`도 설정되어 있어야 합니다(어떤 프로덕션 자체 호스팅이든 이미 설정되어 있습니다). 설치 후 setup 콜백이 사용자를 `<FRONTEND_ORIGIN>/settings?tab=github`으로 다시 돌려보냅니다.
env 변수를 설정한 후 API를 재시작하세요.
diff --git a/apps/docs/content/docs/github-integration.mdx b/apps/docs/content/docs/github-integration.mdx
index 59ffad7171..43e3392bc6 100644
--- a/apps/docs/content/docs/github-integration.mdx
+++ b/apps/docs/content/docs/github-integration.mdx
@@ -114,13 +114,20 @@ On the API server:
```dotenv
GITHUB_APP_SLUG=multica-acme
GITHUB_WEBHOOK_SECRET=<the webhook secret you generated>
+
+# Optional but recommended — populates the connected account name on
+# install instead of waiting for the first webhook to refresh it:
+GITHUB_APP_ID=<numeric App ID from the App's settings page>
+GITHUB_APP_PRIVATE_KEY=<full PEM block, including BEGIN/END lines>
```
-Both variables are required. If either is missing:
+`GITHUB_APP_SLUG` and `GITHUB_WEBHOOK_SECRET` are required. If either is missing:
- `Connect GitHub` in Settings is **disabled** and shows a "not configured" hint.
- The `/api/webhooks/github` endpoint returns **`503 github webhooks not configured`** — Multica refuses to process events with no secret, rather than silently treating every signature as valid.
+`GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY` are **optional**. They let the setup callback call GitHub's App-authenticated `/app/installations/{id}` endpoint to fetch the real organization or user name during install. Without them, the connection card briefly shows `Connected to unknown` until GitHub delivers the `installation.created` webhook (typically within a few seconds), at which point Multica refreshes the row and broadcasts a realtime update so any open Settings tab updates without a manual refresh. Generate the private key under **Private keys → Generate a private key** on the App's settings page; paste the full PEM block (including the `-----BEGIN/END RSA PRIVATE KEY-----` lines) into the env var, preserving newlines.
+
`FRONTEND_ORIGIN` must also be set (it already is for any production self-host); the setup callback bounces the user back to `<FRONTEND_ORIGIN>/settings?tab=github` after install.
Restart the API after setting the env vars.
diff --git a/apps/docs/content/docs/github-integration.zh.mdx b/apps/docs/content/docs/github-integration.zh.mdx
index 7007ade91c..5d563cdf4b 100644
--- a/apps/docs/content/docs/github-integration.zh.mdx
+++ b/apps/docs/content/docs/github-integration.zh.mdx
@@ -114,13 +114,19 @@ API server 上:
```dotenv
GITHUB_APP_SLUG=multica-acme
GITHUB_WEBHOOK_SECRET=<你刚生成的 webhook secret>
+
+# 可选但建议配置——安装完成时直接拿到关联账号名,而不是等第一次 webhook 才刷新:
+GITHUB_APP_ID=<App 设置页上的数字 App ID>
+GITHUB_APP_PRIVATE_KEY=<完整 PEM 块,包含 BEGIN/END 行>
```
-两个都必填。任何一个缺失:
+`GITHUB_APP_SLUG` 和 `GITHUB_WEBHOOK_SECRET` 必填。任何一个缺失:
- Settings 里 `Connect GitHub` 按钮会被 **disable**,并显示「not configured」提示
- `/api/webhooks/github` 直接返回 **`503 github webhooks not configured`**——Multica 在 secret 没配置时拒绝处理事件,不会出现「没 secret 也接受 webhook」的安全坑
+`GITHUB_APP_ID` 和 `GITHUB_APP_PRIVATE_KEY` **可选**。配上之后,setup 回调可以用 App JWT 鉴权调用 GitHub `/app/installations/{id}`,安装完成那一刻就拿到真实的组织名/用户名。不配的话,连接卡片会先显示 `已连接到 unknown`,等 GitHub 的 `installation.created` webhook 到达(通常几秒内),Multica 会刷新 row 并通过 realtime 推送让 Settings 页面无需手动刷新即可更新。私钥从 App 设置页 **Private keys → Generate a private key** 生成,把整段 PEM(含 `-----BEGIN/END RSA PRIVATE KEY-----` 两行)粘到 env 里,保留换行。
+
`FRONTEND_ORIGIN` 也必须设置(任何生产 self-host 都已经设了)——setup 回调结束后用它把用户跳回 `<FRONTEND_ORIGIN>/settings?tab=github`。
设完 env 重启 API。
diff --git a/server/internal/handler/github.go b/server/internal/handler/github.go
index 679a050178..42933217cb 100644
--- a/server/internal/handler/github.go
+++ b/server/internal/handler/github.go
@@ -20,6 +20,7 @@ import (
"time"
"github.com/go-chi/chi/v5"
+ "github.com/golang-jwt/jwt/v5"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/middleware"
@@ -27,6 +28,11 @@ import (
"github.com/multica-ai/multica/server/pkg/protocol"
)
+// githubAPIBase is the base URL for GitHub's REST API. Mutable so tests can
+// point fetchInstallationAccount at an httptest server without touching the
+// real GitHub.
+var githubAPIBase = "https://api.github.com"
+
// ── Response shapes ─────────────────────────────────────────────────────────
// GitHubInstallationResponse is the JSON shape returned by the installation
@@ -355,20 +361,40 @@ func (h *Handler) GitHubSetupCallback(w http.ResponseWriter, r *http.Request) {
}
// fetchInstallationAccount tries to enrich the installation row with the
-// account name + avatar via GitHub's public API. We deliberately do NOT
-// require GitHub App JWT auth here — the install endpoint is publicly
-// readable for installations on public accounts, and on failure we fall
-// back to placeholders that the next webhook will overwrite.
+// account name + avatar from GitHub.
+//
+// GitHub's `GET /app/installations/{id}` endpoint requires GitHub App
+// authentication (a JWT signed with the App's RSA private key). When the
+// operator has configured GITHUB_APP_ID and GITHUB_APP_PRIVATE_KEY, we
+// sign a short-lived JWT and use it; on any failure (env not set, key
+// malformed, GitHub returns non-200) we fall back to the "unknown"
+// placeholder. The next `installation` webhook delivery from GitHub will
+// upsert the row with the real account info — see handleInstallationEvent.
+//
+// The HTTP call is synchronous (no independent timeout — that's a pre-
+// existing wart of the install path), but we deliberately do NOT let a
+// failure abort the setup callback: a network blip here just leaves the
+// "unknown" placeholder in place, and the frontend re-queries on the
+// realtime broadcast emitted by the webhook handler, so the UI converges
+// without a manual refresh.
func fetchInstallationAccount(ctx context.Context, installationID int64) (login, accountType string, avatar *string) {
login = "unknown"
accountType = "User"
avatar = nil
- url := fmt.Sprintf("https://api.github.com/app/installations/%d", installationID)
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
+ endpoint := fmt.Sprintf("%s/app/installations/%d", strings.TrimRight(githubAPIBase, "/"), installationID)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return
}
req.Header.Set("Accept", "application/vnd.github+json")
+ if token, err := signGitHubAppJWT(time.Now()); err != nil {
+ // Misconfigured private key is operator-actionable — log so the
+ // install path doesn't silently fall back to "unknown" forever
+ // without leaving a breadcrumb.
+ slog.Warn("github: sign App JWT failed", "err", err)
+ } else if token != "" {
+ req.Header.Set("Authorization", "Bearer "+token)
+ }
resp, err := http.DefaultClient.Do(req)
if err != nil {
return
@@ -400,6 +426,43 @@ func fetchInstallationAccount(ctx context.Context, installationID int64) (login,
return
}
+// signGitHubAppJWT mints the short-lived RS256 JWT GitHub requires for
+// App-authenticated REST calls (see fetchInstallationAccount). Returns
+// ("", nil) when the operator hasn't configured the App identity — that's
+// a soft "App auth not available" signal, not an error, so callers can
+// fall through to their unauthenticated path. A malformed
+// GITHUB_APP_PRIVATE_KEY surfaces as an error so the operator notices.
+//
+// `now` is injected for deterministic tests; production callers pass
+// time.Now().
+func signGitHubAppJWT(now time.Time) (string, error) {
+ appID := strings.TrimSpace(os.Getenv("GITHUB_APP_ID"))
+ pemKey := strings.TrimSpace(os.Getenv("GITHUB_APP_PRIVATE_KEY"))
+ if appID == "" || pemKey == "" {
+ return "", nil
+ }
+ key, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(pemKey))
+ if err != nil {
+ return "", fmt.Errorf("parse GITHUB_APP_PRIVATE_KEY: %w", err)
+ }
+ // GitHub allows JWTs valid for up to 10 minutes. We back-date `iat`
+ // by 60 seconds to absorb modest clock skew between us and GitHub
+ // (otherwise an "iat in the future" verdict from GitHub fails the
+ // request) and cap `exp` at 9 minutes ahead to stay inside the cap
+ // even with the same skew applied.
+ claims := jwt.MapClaims{
+ "iat": now.Add(-60 * time.Second).Unix(),
+ "exp": now.Add(9 * time.Minute).Unix(),
+ "iss": appID,
+ }
+ token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
+ signed, err := token.SignedString(key)
+ if err != nil {
+ return "", fmt.Errorf("sign App JWT: %w", err)
+ }
+ return signed, nil
+}
+
// ── Listing / disconnect ────────────────────────────────────────────────────
// ListGitHubInstallations returns the workspace's connected GitHub
@@ -607,7 +670,7 @@ func (h *Handler) handleInstallationEvent(ctx context.Context, body []byte) {
return
}
avatar := p.Installation.Account.AvatarURL
- _, err = h.Queries.CreateGitHubInstallation(ctx, db.CreateGitHubInstallationParams{
+ inst, err := h.Queries.CreateGitHubInstallation(ctx, db.CreateGitHubInstallationParams{
WorkspaceID: existing.WorkspaceID,
InstallationID: p.Installation.ID,
AccountLogin: p.Installation.Account.Login,
@@ -617,7 +680,17 @@ func (h *Handler) handleInstallationEvent(ctx context.Context, body []byte) {
})
if err != nil {
slog.Warn("github: refresh installation failed", "err", err)
+ return
}
+ // Broadcast so any open Settings → GitHub tab re-queries the
+ // installations list. Without this, a row created by the setup
+ // callback with the "unknown" placeholder (e.g. because GitHub
+ // App JWT auth wasn't configured, or this webhook arrived after
+ // the user already loaded the page) would stay visibly stale
+ // until the user manually refreshes.
+ h.publish(protocol.EventGitHubInstallationCreated, uuidToString(inst.WorkspaceID), "system", "", map[string]any{
+ "installation": githubInstallationToBroadcast(inst),
+ })
}
}
diff --git a/server/internal/handler/github_test.go b/server/internal/handler/github_test.go
index 54f4823825..2ee0bf0284 100644
--- a/server/internal/handler/github_test.go
+++ b/server/internal/handler/github_test.go
@@ -4,9 +4,13 @@ import (
"bytes"
"context"
"crypto/hmac"
+ "crypto/rand"
+ "crypto/rsa"
"crypto/sha256"
+ "crypto/x509"
"encoding/hex"
"encoding/json"
+ "encoding/pem"
"fmt"
"net/http"
"net/http/httptest"
@@ -16,8 +20,11 @@ import (
"time"
"github.com/go-chi/chi/v5"
+ "github.com/golang-jwt/jwt/v5"
+ "github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/middleware"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
)
func TestExtractIdentifiers(t *testing.T) {
@@ -2043,3 +2050,342 @@ func TestWebhook_MergedPR_ChildWithParent_NotifiesParent(t *testing.T) {
}
}
}
+
+
+// generateTestRSAKeyPEM mints an RSA-2048 key, returns its PKCS#1 PEM
+// encoding (the format GitHub hands operators when they create the App)
+// and the parsed *rsa.PrivateKey for verification.
+func generateTestRSAKeyPEM(t *testing.T) (pemBytes []byte, key *rsa.PrivateKey) {
+ t.Helper()
+ k, err := rsa.GenerateKey(rand.Reader, 2048)
+ if err != nil {
+ t.Fatalf("generate RSA key: %v", err)
+ }
+ der := x509.MarshalPKCS1PrivateKey(k)
+ return pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: der}), k
+}
+
+// TestSignGitHubAppJWT_NotConfigured pins the contract that missing env
+// vars produce ("", nil) — a soft "App auth not available" signal that
+// fetchInstallationAccount uses to fall through to its unauthenticated
+// path. Returning an error here would force every install on a vanilla
+// self-host to log a noisy warning even though the deployment is
+// intentionally not running App-authenticated calls.
+func TestSignGitHubAppJWT_NotConfigured(t *testing.T) {
+ t.Setenv("GITHUB_APP_ID", "")
+ t.Setenv("GITHUB_APP_PRIVATE_KEY", "")
+ tok, err := signGitHubAppJWT(time.Now())
+ if err != nil {
+ t.Fatalf("expected nil error when env not set, got %v", err)
+ }
+ if tok != "" {
+ t.Errorf("expected empty token when env not set, got %q", tok)
+ }
+
+ // Half-configured (one var set, the other empty) is treated the same
+ // as fully unset — we never want a partial config to claim the App
+ // is wired up.
+ t.Setenv("GITHUB_APP_ID", "12345")
+ t.Setenv("GITHUB_APP_PRIVATE_KEY", "")
+ tok, err = signGitHubAppJWT(time.Now())
+ if err != nil || tok != "" {
+ t.Errorf("partial config should return empty token, got tok=%q err=%v", tok, err)
+ }
+}
+
+// TestSignGitHubAppJWT_InvalidPEM proves that a malformed private key is
+// surfaced as an error, not silently swallowed. The setup-callback path
+// catches and logs this so the operator gets a breadcrumb instead of an
+// install that quietly never enriches the row.
+func TestSignGitHubAppJWT_InvalidPEM(t *testing.T) {
+ t.Setenv("GITHUB_APP_ID", "12345")
+ t.Setenv("GITHUB_APP_PRIVATE_KEY", "not a real PEM block")
+ if _, err := signGitHubAppJWT(time.Now()); err == nil {
+ t.Error("expected error for malformed private key, got nil")
+ }
+}
+
+// TestSignGitHubAppJWT_ClaimsAndSignature signs a token with a known key
+// and verifies (a) the claims GitHub requires (`iss`, `iat`, `exp`) carry
+// the values we set, (b) iat is back-dated for clock skew, (c) exp stays
+// inside GitHub's 10-minute cap, and (d) the signature verifies against
+// the matching public key.
+func TestSignGitHubAppJWT_ClaimsAndSignature(t *testing.T) {
+ pemBytes, key := generateTestRSAKeyPEM(t)
+ t.Setenv("GITHUB_APP_ID", "424242")
+ t.Setenv("GITHUB_APP_PRIVATE_KEY", string(pemBytes))
+
+ now := time.Date(2026, 6, 5, 12, 0, 0, 0, time.UTC)
+ tok, err := signGitHubAppJWT(now)
+ if err != nil {
+ t.Fatalf("sign: %v", err)
+ }
+ if tok == "" {
+ t.Fatal("expected non-empty token when fully configured")
+ }
+
+ // Inject the same `now` into the parser's clock so default exp/nbf
+ // validation is anchored to the test-time, not real wall clock —
+ // otherwise the test becomes a time bomb that fails for real once
+ // the real time crosses the token's exp (now + 9m).
+ parsed, err := jwt.Parse(
+ tok,
+ func(token *jwt.Token) (any, error) {
+ if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
+ return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
+ }
+ return &key.PublicKey, nil
+ },
+ jwt.WithTimeFunc(func() time.Time { return now }),
+ )
+ if err != nil || !parsed.Valid {
+ t.Fatalf("verify token: err=%v valid=%v", err, parsed != nil && parsed.Valid)
+ }
+ claims, ok := parsed.Claims.(jwt.MapClaims)
+ if !ok {
+ t.Fatalf("claims type: %T", parsed.Claims)
+ }
+ if got, _ := claims["iss"].(string); got != "424242" {
+ t.Errorf("iss = %q, want 424242", got)
+ }
+ iat := int64(claims["iat"].(float64))
+ exp := int64(claims["exp"].(float64))
+ if iat != now.Add(-60*time.Second).Unix() {
+ t.Errorf("iat = %d, want %d (now - 60s for clock skew)", iat, now.Add(-60*time.Second).Unix())
+ }
+ if exp != now.Add(9*time.Minute).Unix() {
+ t.Errorf("exp = %d, want %d (now + 9m, inside GitHub's 10m cap)", exp, now.Add(9*time.Minute).Unix())
+ }
+ if exp-iat > int64(10*time.Minute/time.Second) {
+ t.Errorf("exp-iat = %d s, exceeds GitHub's 10m max", exp-iat)
+ }
+}
+
+// TestFetchInstallationAccount_AuthenticatedPopulatesRow simulates the
+// GitHub `/app/installations/{id}` endpoint with a JWT-gated mock and
+// verifies that fetchInstallationAccount, when fully configured,
+// (a) sends a Bearer JWT, (b) parses the JSON response, and (c) returns
+// the real account login instead of the "unknown" placeholder. This is
+// the assertion that nails down the bug fix for MUL-3078.
+func TestFetchInstallationAccount_AuthenticatedPopulatesRow(t *testing.T) {
+ pemBytes, key := generateTestRSAKeyPEM(t)
+ t.Setenv("GITHUB_APP_ID", "11111")
+ t.Setenv("GITHUB_APP_PRIVATE_KEY", string(pemBytes))
+
+ const wantInstallationID int64 = 7777777
+ var sawAuth string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ sawAuth = r.Header.Get("Authorization")
+ expectedPath := fmt.Sprintf("/app/installations/%d", wantInstallationID)
+ if r.URL.Path != expectedPath {
+ t.Errorf("unexpected path: got %q want %q", r.URL.Path, expectedPath)
+ }
+ // Verify JWT signature using the matching public key — this is
+ // what GitHub does on the real endpoint.
+ bearer := strings.TrimPrefix(sawAuth, "Bearer ")
+ if bearer == sawAuth {
+ http.Error(w, "missing Bearer prefix", http.StatusUnauthorized)
+ return
+ }
+ if _, err := jwt.Parse(bearer, func(token *jwt.Token) (any, error) {
+ return &key.PublicKey, nil
+ }); err != nil {
+ http.Error(w, "bad jwt: "+err.Error(), http.StatusUnauthorized)
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{
+ "account": map[string]any{
+ "login": "octocat",
+ "type": "Organization",
+ "avatar_url": "https://example.com/o.png",
+ },
+ })
+ }))
+ t.Cleanup(srv.Close)
+
+ oldBase := githubAPIBase
+ githubAPIBase = srv.URL
+ t.Cleanup(func() { githubAPIBase = oldBase })
+
+ login, accountType, avatar := fetchInstallationAccount(context.Background(), wantInstallationID)
+ if login != "octocat" {
+ t.Errorf("login = %q, want %q (the bug repro: stayed as 'unknown' before the fix)", login, "octocat")
+ }
+ if accountType != "Organization" {
+ t.Errorf("accountType = %q, want Organization", accountType)
+ }
+ if avatar == nil || *avatar != "https://example.com/o.png" {
+ t.Errorf("avatar = %v, want pointer to https://example.com/o.png", avatar)
+ }
+ if !strings.HasPrefix(sawAuth, "Bearer ") {
+ t.Errorf("expected Bearer auth header, got %q", sawAuth)
+ }
+}
+
+// TestFetchInstallationAccount_UnauthenticatedFallsBack documents the
+// degraded path: when the operator hasn't set GITHUB_APP_ID/PRIVATE_KEY,
+// the call is made unauthenticated, GitHub returns 401, and the function
+// returns the "unknown" placeholder. This is the input the webhook then
+// upserts over once GitHub delivers `installation.created`.
+func TestFetchInstallationAccount_UnauthenticatedFallsBack(t *testing.T) {
+ t.Setenv("GITHUB_APP_ID", "")
+ t.Setenv("GITHUB_APP_PRIVATE_KEY", "")
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("Authorization") == "" {
+ http.Error(w, "auth required", http.StatusUnauthorized)
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"account": map[string]any{"login": "should-not-see"}})
+ }))
+ t.Cleanup(srv.Close)
+ oldBase := githubAPIBase
+ githubAPIBase = srv.URL
+ t.Cleanup(func() { githubAPIBase = oldBase })
+
+ login, _, _ := fetchInstallationAccount(context.Background(), 999)
+ if login != "unknown" {
+ t.Errorf("login = %q, want unknown placeholder when auth not configured", login)
+ }
+}
+
+// TestFetchInstallationAccount_EmptyAccountKeepsPlaceholder pins that a 200
+// response with a missing `account.login` (e.g. GitHub returned a partial
+// payload) still yields the safe "unknown" placeholder rather than writing
+// an empty string — the frontend renders the literal value, so an empty
+// string would surface as "已连接到 " (the bug we're fixing, in a different
+// shape).
+func TestFetchInstallationAccount_EmptyAccountKeepsPlaceholder(t *testing.T) {
+ pemBytes, _ := generateTestRSAKeyPEM(t)
+ t.Setenv("GITHUB_APP_ID", "1")
+ t.Setenv("GITHUB_APP_PRIVATE_KEY", string(pemBytes))
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(w, http.StatusOK, map[string]any{"account": map[string]any{}})
+ }))
+ t.Cleanup(srv.Close)
+ oldBase := githubAPIBase
+ githubAPIBase = srv.URL
+ t.Cleanup(func() { githubAPIBase = oldBase })
+
+ login, accountType, avatar := fetchInstallationAccount(context.Background(), 12)
+ if login != "unknown" {
+ t.Errorf("expected 'unknown' placeholder for empty account.login, got %q", login)
+ }
+ if accountType != "User" {
+ t.Errorf("expected default 'User' accountType, got %q", accountType)
+ }
+ if avatar != nil {
+ t.Errorf("expected nil avatar, got %v", *avatar)
+ }
+}
+
+// TestWebhook_InstallationCreatedRefreshesUnknownLogin guards the fix for
+// MUL-3078: when the setup callback persists a row with the "unknown"
+// placeholder (because the operator hasn't configured App JWT auth, or
+// the API call failed), the subsequent `installation.created` webhook
+// must (a) overwrite account_login with the real value from the payload
+// and (b) broadcast a `github_installation:created` event so any open
+// Settings → GitHub tab re-queries without needing a manual refresh.
+func TestWebhook_InstallationCreatedRefreshesUnknownLogin(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("handler test fixture not initialized (no DB?)")
+ }
+ ctx := context.Background()
+ secret := "installation-refresh-secret"
+ t.Setenv("GITHUB_WEBHOOK_SECRET", secret)
+
+ const installationID int64 = 71717171
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM github_installation WHERE installation_id = $1`, installationID)
+ })
+
+ // Seed the row the way the setup callback does today when App JWT
+ // auth isn't available: account_login = "unknown".
+ if _, err := testHandler.Queries.CreateGitHubInstallation(ctx, db.CreateGitHubInstallationParams{
+ WorkspaceID: parseUUID(testWorkspaceID),
+ InstallationID: installationID,
+ AccountLogin: "unknown",
+ AccountType: "User",
+ }); err != nil {
+ t.Fatalf("seed installation row: %v", err)
+ }
+
+ // Subscribe to the bus BEFORE firing the webhook so we can assert the
+ // broadcast actually fired. Bus.Subscribe is per-event-type, which
+ // matches the realtime hub's downstream filter.
+ gotEvent := make(chan events.Event, 1)
+ testHandler.Bus.Subscribe(protocol.EventGitHubInstallationCreated, func(e events.Event) {
+ select {
+ case gotEvent <- e:
+ default:
+ }
+ })
+
+ body, _ := json.Marshal(map[string]any{
+ "action": "created",
+ "installation": map[string]any{
+ "id": installationID,
+ "account": map[string]any{
+ "login": "real-octocat",
+ "type": "Organization",
+ "avatar_url": "https://example.com/avatar.png",
+ },
+ },
+ })
+ mac := hmac.New(sha256.New, []byte(secret))
+ mac.Write(body)
+ sig := "sha256=" + hex.EncodeToString(mac.Sum(nil))
+
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest("POST", "/api/webhooks/github", bytes.NewReader(body))
+ req.Header.Set("X-GitHub-Event", "installation")
+ req.Header.Set("X-Hub-Signature-256", sig)
+ testHandler.HandleGitHubWebhook(rec, req)
+ if rec.Code != http.StatusAccepted {
+ t.Fatalf("webhook: expected 202, got %d (%s)", rec.Code, rec.Body.String())
+ }
+
+ // (a) The row's account_login must be the real login, not "unknown".
+ got, err := testHandler.Queries.GetGitHubInstallationByInstallationID(ctx, installationID)
+ if err != nil {
+ t.Fatalf("get installation: %v", err)
+ }
+ if got.AccountLogin != "real-octocat" {
+ t.Errorf("account_login = %q, want %q (refresh did not overwrite the unknown placeholder)",
+ got.AccountLogin, "real-octocat")
+ }
+ if got.AccountType != "Organization" {
+ t.Errorf("account_type = %q, want Organization", got.AccountType)
+ }
+
+ // (b) A broadcast must have been emitted on the installation:created
+ // channel so the frontend re-queries the list. The realtime listener
+ // drops events with empty workspace_id, so we verify both the type
+ // AND the workspace scope.
+ select {
+ case ev := <-gotEvent:
+ if ev.WorkspaceID != testWorkspaceID {
+ t.Errorf("broadcast WorkspaceID = %q, want %q", ev.WorkspaceID, testWorkspaceID)
+ }
+ // The payload must carry the redacted installation shape so
+ // non-admin clients on the workspace channel can't extract the
+ // numeric installation_id from the broadcast itself.
+ payload, ok := ev.Payload.(map[string]any)
+ if !ok {
+ t.Fatalf("broadcast payload type: %T", ev.Payload)
+ }
+ inst, ok := payload["installation"].(GitHubInstallationResponse)
+ if !ok {
+ t.Fatalf("installation payload type: %T", payload["installation"])
+ }
+ if inst.AccountLogin != "real-octocat" {
+ t.Errorf("broadcast account_login = %q, want real-octocat", inst.AccountLogin)
+ }
+ if inst.InstallationID != nil {
+ t.Errorf("broadcast must redact installation_id, got %v", *inst.InstallationID)
+ }
+ case <-time.After(2 * time.Second):
+ t.Errorf("expected github_installation:created broadcast after webhook refresh, got none in 2s")
+ }
+}