Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
Revert "feat(vcs): update access tokens without rotating webhooks (#10401)" (#10416)
Bohan Jiang9d0bb72409a6
diff --git a/apps/docs/content/docs/vcs-integration.fr.mdx b/apps/docs/content/docs/vcs-integration.fr.mdxindex 501f931636..e7219f4933 100644--- a/apps/docs/content/docs/vcs-integration.fr.mdx+++ b/apps/docs/content/docs/vcs-integration.fr.mdx@@ -64,11 +64,9 @@ Copiez l'**URL du webhook** et le **Secret du webhook** affichés après la conn</Steps><Callout type="warn">-Le secret du webhook n'est affiché qu'une seule fois. Copiez-le avant de quitter la page.+Le secret du webhook n'est affiché qu'une seule fois. Copiez-le avant de quitter la page. Reconnecter la même instance régénère le jeton et le secret.</Callout>-Pour remplacer uniquement le jeton d'accès, ouvrez le menu de la connexion et choisissez **Mettre à jour le jeton d'accès**. Multica valide le nouveau jeton avant de l'enregistrer et met à jour le compte affiché s'il appartient à un autre utilisateur. Le secret du webhook et les pull requests liées sont conservés. Reconnecter la même instance régénère toujours le jeton et le secret du webhook.-### Instance avec une autorité de certification privéeSi **Connecter** indique que le certificat du fournisseur « is signed by a certificate authority this server does not trust », le certificat HTTPS de l'instance est émis par une autorité de certification (CA) interne, ou auto-signé, à laquelle le serveur Multica ne fait pas confiance. Un administrateur du serveur doit ajouter cette CA au magasin de confiance du backend : avec Helm, définissez `backend.extraCACerts.configMap` ; avec Docker Compose, montez la CA et définissez `SSL_CERT_DIR`. Les étapes sont décrites dans [Private CA certificates](https://github.com/multica-ai/multica/blob/main/SELF_HOSTING_ADVANCED.md#private-ca-certificates-optional). Le backend transmet aussi cette CA aux daemons, afin que leur git puisse cloner les dépôts de la même instance.diff --git a/apps/docs/content/docs/vcs-integration.ja.mdx b/apps/docs/content/docs/vcs-integration.ja.mdxindex ab1f301881..924e7b0348 100644--- a/apps/docs/content/docs/vcs-integration.ja.mdx+++ b/apps/docs/content/docs/vcs-integration.ja.mdx@@ -64,11 +64,9 @@ Multica で **設定 → コード**を開き、**セルフホスト Git** の</Steps><Callout type="warn">-Webhook secret は一度しか表示されません。ページを離れる前にコピーしてください。+Webhook secret は一度しか表示されません。ページを離れる前にコピーしてください。同じインスタンスへ再接続すると、トークンと secret がローテーションされます。</Callout>-アクセストークンだけを置き換えるには、接続メニューで **アクセストークンを更新** を選択します。Multica は保存前に新しいトークンを検証し、別のユーザーのトークンであれば表示アカウントを更新します。Webhook secret とリンク済みのプルリクエストは保持されます。同じインスタンスへの再接続では、引き続きトークンと Webhook secret の両方がローテーションされます。-### プライベート CA を使うインスタンス**接続**で、プロバイダーの証明書が "is signed by a certificate authority this server does not trust" と表示された場合、インスタンスの HTTPS 証明書は Multica サーバーが信頼していない社内 CA で発行されている(または自己署名である)ということです。サーバー管理者がその CA をバックエンドの信頼ストアに追加してください。Helm では `backend.extraCACerts.configMap` を設定し、Docker Compose では CA をマウントして `SSL_CERT_DIR` を設定します。手順は [Private CA certificates](https://github.com/multica-ai/multica/blob/main/SELF_HOSTING_ADVANCED.md#private-ca-certificates-optional) を参照してください。バックエンドはこの CA をデーモンにも渡すため、デーモンの git も同じインスタンスのリポジトリをクローンできます。diff --git a/apps/docs/content/docs/vcs-integration.ko.mdx b/apps/docs/content/docs/vcs-integration.ko.mdxindex 2f64717424..3d93851d85 100644--- a/apps/docs/content/docs/vcs-integration.ko.mdx+++ b/apps/docs/content/docs/vcs-integration.ko.mdx@@ -64,11 +64,9 @@ Multica에서 **설정 → 코드**를 열고 **셀프 호스팅 Git** 행에서</Steps><Callout type="warn">-Webhook secret은 한 번만 표시됩니다. 페이지를 떠나기 전에 복사하세요.+Webhook secret은 한 번만 표시됩니다. 페이지를 떠나기 전에 복사하세요. 같은 인스턴스에 다시 연결하면 token과 secret이 교체됩니다.</Callout>-액세스 토큰만 교체하려면 연결 메뉴에서 **액세스 토큰 업데이트**를 선택하세요. Multica는 저장 전에 새 토큰을 검증하며, 다른 사용자의 토큰이면 표시되는 계정을 업데이트합니다. Webhook secret과 연결된 풀 리퀘스트는 유지됩니다. 같은 인스턴스에 다시 연결하면 기존과 같이 토큰과 Webhook secret이 모두 교체됩니다.-### 사설 CA를 사용하는 인스턴스**연결** 시 제공자 인증서에 대해 "is signed by a certificate authority this server does not trust"라는 메시지가 나오면, 인스턴스의 HTTPS 인증서가 Multica 서버가 신뢰하지 않는 내부 CA로 발급되었거나 자체 서명된 것입니다. 서버 관리자가 해당 CA를 백엔드 신뢰 저장소에 추가해야 합니다. Helm에서는 `backend.extraCACerts.configMap`을 설정하고, Docker Compose에서는 CA를 마운트한 뒤 `SSL_CERT_DIR`을 설정합니다. 자세한 절차는 [Private CA certificates](https://github.com/multica-ai/multica/blob/main/SELF_HOSTING_ADVANCED.md#private-ca-certificates-optional)를 참고하세요. 백엔드는 이 CA를 데몬에도 전달하므로, 데몬의 git도 같은 인스턴스의 저장소를 클론할 수 있습니다.diff --git a/apps/docs/content/docs/vcs-integration.mdx b/apps/docs/content/docs/vcs-integration.mdxindex 15477a12a7..d5a9b630e5 100644--- a/apps/docs/content/docs/vcs-integration.mdx+++ b/apps/docs/content/docs/vcs-integration.mdx@@ -64,11 +64,9 @@ Copy the **webhook URL** and **webhook secret** shown after connecting.</Steps><Callout type="warn">-The webhook secret is shown only once. Copy it before leaving the page.+The webhook secret is shown only once. Copy it before leaving the page. Reconnecting the same instance rotates the token and secret.</Callout>-To replace only the access token, open the connection menu and choose **Update access token**. Multica validates the new token before saving it and updates the displayed account if it belongs to a different user. The webhook secret and linked pull requests are preserved. Reconnecting the same instance still rotates both the token and webhook secret.-### Instance with a private CAIf **Connect** reports that the provider's certificate "is signed by a certificate authority this server does not trust", the instance's HTTPS certificate comes from an internal CA (or is self-signed) that the Multica server does not trust. A server operator adds that CA to the backend's trust store: with Helm, set `backend.extraCACerts.configMap`; with Docker Compose, mount the CA and set `SSL_CERT_DIR`. See [Private CA certificates](https://github.com/multica-ai/multica/blob/main/SELF_HOSTING_ADVANCED.md#private-ca-certificates-optional) for the steps. The backend also passes that CA to daemons, so their git can clone repositories from the same instance.diff --git a/apps/docs/content/docs/vcs-integration.zh-Hant.mdx b/apps/docs/content/docs/vcs-integration.zh-Hant.mdxindex 15e43bcfb3..4028b8af49 100644--- a/apps/docs/content/docs/vcs-integration.zh-Hant.mdx+++ b/apps/docs/content/docs/vcs-integration.zh-Hant.mdx@@ -64,11 +64,9 @@ MULTICA_VCS_SECRET_KEY=<base64 32 位元組金鑰></Steps><Callout type="warn">-Webhook 金鑰只顯示一次,請在離開頁面前複製。+Webhook 金鑰只顯示一次,請在離開頁面前複製。重新連線同一例項會輪換令牌與金鑰。</Callout>-只需替換存取權杖時,在連線選單中選擇 **更新存取權杖**。Multica 會先驗證新權杖再儲存;如果權杖屬於另一位使用者,介面會顯示新帳號。Webhook 金鑰和已關聯的提取請求都會保留。重新連線同一執行個體仍會同時輪換權杖與 Webhook 金鑰。-### 例項使用私有 CA如果點選 **連線** 後提示提供方的憑證 "is signed by a certificate authority this server does not trust",說明例項的 HTTPS 憑證由內部 CA 簽發(或是自簽名憑證),而 Multica 服務端不信任這個 CA。需要由服務端管理員把該 CA 加入後端的信任庫:使用 Helm 時設定 `backend.extraCACerts.configMap`;使用 Docker Compose 時掛載 CA 並設定 `SSL_CERT_DIR`。具體步驟見 [Private CA certificates](https://github.com/multica-ai/multica/blob/main/SELF_HOSTING_ADVANCED.md#private-ca-certificates-optional)。後端還會把該 CA 下發給守護程序,使守護程序的 git 也能克隆同一例項上的倉庫。diff --git a/apps/docs/content/docs/vcs-integration.zh.mdx b/apps/docs/content/docs/vcs-integration.zh.mdxindex 033c5a4aa6..7e05f02635 100644--- a/apps/docs/content/docs/vcs-integration.zh.mdx+++ b/apps/docs/content/docs/vcs-integration.zh.mdx@@ -64,11 +64,9 @@ MULTICA_VCS_SECRET_KEY=<base64 32 字节密钥></Steps><Callout type="warn">-Webhook 密钥只显示一次,请在离开页面前复制。+Webhook 密钥只显示一次,请在离开页面前复制。重新连接同一实例会轮换令牌与密钥。</Callout>-只需替换访问令牌时,在连接菜单中选择 **更新访问令牌**。Multica 会先校验新令牌再保存;如果令牌属于另一个用户,界面会显示新账号。Webhook 密钥和已关联的拉取请求都会保留。重新连接同一实例仍会同时轮换令牌与 Webhook 密钥。-### 实例使用私有 CA如果点击 **连接** 后提示提供方的证书 "is signed by a certificate authority this server does not trust",说明实例的 HTTPS 证书由内部 CA 签发(或是自签名证书),而 Multica 服务端不信任这个 CA。需要由服务端管理员把该 CA 加入后端的信任库:使用 Helm 时设置 `backend.extraCACerts.configMap`;使用 Docker Compose 时挂载 CA 并设置 `SSL_CERT_DIR`。具体步骤见 [Private CA certificates](https://github.com/multica-ai/multica/blob/main/SELF_HOSTING_ADVANCED.md#private-ca-certificates-optional)。后端还会把该 CA 下发给守护进程,使守护进程的 git 也能克隆同一实例上的仓库。diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 7e612fb1ca..5820fbf1fb 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -2,7 +2,7 @@ import type { ZodType } from "zod";import { AgentRuntimeSchema, EMPTY_RUNTIME } from "../runtimes/schema";import type { IssueWakeup, IssueWakeupInput, IssueWakeupSummaryRow, PausedWakeup, SystemWakeup, WakeupRun, WorkspaceSystemWakeup } from "../types/issue-wakeup";import type { WorkspaceWakeupPage, WorkspaceWakeupFilters } from "../types/issue-wakeup";-import { WorkspaceWakeupPageSchema, IssueWakeupSchema, IssueWakeupSummaryRowSchema, PausedWakeupSchema, SystemWakeupSchema, WakeupRunSchema, WorkspaceSystemWakeupSchema, VCSConnectionSchema, EMPTY_VCS_CONNECTION } from "./schemas";+import { WorkspaceWakeupPageSchema, IssueWakeupSchema, IssueWakeupSummaryRowSchema, PausedWakeupSchema, SystemWakeupSchema, WakeupRunSchema, WorkspaceSystemWakeupSchema } from "./schemas";import { archivedInboxQuery, type ArchivedInboxFilters } from "../inbox/filters";import type { ArchivedInboxPage, ArchivedInboxFacets } from "../types/inbox";import { parseQoderConnection, parseQoderCatalog, type QoderInput } from "../runtimes/qoder-schema";@@ -196,7 +196,6 @@ import type {ListVCSConnectionsResponse,ConnectVCSRequest,ConnectVCSResponse,- VCSConnection,ListLarkInstallationsResponse,BeginLarkInstallResponse,LarkInstallStatusResponse,@@ -5435,23 +5434,6 @@ export class ApiClient {}// VCS integration (Forgejo / Gitea / GitLab)- async updateVCSConnectionToken(- workspaceId: string,- connectionId: string,- body: { access_token: string },- ): Promise<VCSConnection> {- const endpoint = `/api/workspaces/${workspaceId}/vcs/connections/${connectionId}/token`;- return parseWithFallback(- await this.fetch<unknown>(endpoint, {- method: "POST",- body: JSON.stringify(body),- }),- VCSConnectionSchema,- EMPTY_VCS_CONNECTION,- { endpoint },- );- }-async listVCSConnections(workspaceId: string): Promise<ListVCSConnectionsResponse> {return this.fetch(`/api/workspaces/${workspaceId}/vcs/connections`);}diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex ccad56c6bf..a6dd0923b5 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -105,7 +105,6 @@ import type {User,WebhookDelivery,WorkspaceMcpServer,- VCSConnection,} from "../types";import type { CloudRuntimeNode } from "../runtimes/cloud-runtime";import type { CreateFeedbackResponse } from "../feedback/types";@@ -4275,28 +4274,6 @@ export const RuntimeProfileSchema = z}));export const RuntimeProfileListSchema = z.array(RuntimeProfileSchema);-export const VCSConnectionSchema = z.object({- id: z.string(),- workspace_id: z.string(),- provider: z.string(),- instance_url: z.string(),- account_login: z.string().catch(""),- webhook_url: z.string().catch(""),- webhook_path: z.string().catch(""),- created_at: z.string().catch(""),-});--export const EMPTY_VCS_CONNECTION: VCSConnection = {- id: "",- workspace_id: "",- provider: "forgejo",- instance_url: "",- account_login: "",- webhook_url: "",- webhook_path: "",- created_at: "",-};-// Receipt evidence is optional across mixed server/desktop versions. A malformed// timestamp must never render the binding as verified.export const LarkInstallationSchema = z.object({diff --git a/packages/core/api/vcs.test.ts b/packages/core/api/vcs.test.tsdeleted file mode 100644index 98c39155ec..0000000000--- a/packages/core/api/vcs.test.ts+++ /dev/null@@ -1,58 +0,0 @@-// @vitest-environment node-import { afterEach, describe, expect, it, vi } from "vitest";-import { ApiClient } from "./client";-import { EMPTY_VCS_CONNECTION } from "./schemas";--afterEach(() => vi.unstubAllGlobals());--describe("updateVCSConnectionToken", () => {- const connection = {- id: "conn-1",- workspace_id: "ws-1",- provider: "gitlab",- instance_url: "https://gitlab.example.test",- account_login: "service-bot",- };-- function respond(body: unknown, status = 200) {- const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify(body), {- status, headers: { "Content-Type": "application/json" },- }));- vi.stubGlobal("fetch", fetchMock);- return fetchMock;- }-- it("posts only the replacement token and parses the connection response", async () => {- const fetchMock = respond({ ...connection, webhook_secret: "should-not-be-exposed" });- const client = new ApiClient("https://api.example.test");- const result = await client.updateVCSConnectionToken("ws-1", "conn-1", { access_token: "new-token" });- expect(fetchMock).toHaveBeenCalledWith(- "https://api.example.test/api/workspaces/ws-1/vcs/connections/conn-1/token",- expect.objectContaining({ method: "POST", body: JSON.stringify({ access_token: "new-token" }) }),- );- expect(result).toEqual({ ...connection, webhook_url: "", webhook_path: "", created_at: "" });- expect(result).not.toHaveProperty("webhook_secret");- });-- it.each([null, { id: 12 }, { ...connection, instance_url: [] }])(- "safely handles a malformed response: %j", async (body) => {- respond(body);- await expect(new ApiClient("").updateVCSConnectionToken("ws-1", "conn-1", {- access_token: "new-token",- })).resolves.toEqual(EMPTY_VCS_CONNECTION);- },- );-- it("preserves an unknown provider and defaults malformed optional fields", async () => {- respond({ ...connection, provider: "future-provider", account_login: null, webhook_url: 42 });- const result = await new ApiClient("").updateVCSConnectionToken("ws-1", "conn-1", { access_token: "new-token" });- expect(result).toMatchObject({ provider: "future-provider", account_login: "", webhook_url: "" });- });-- it("surfaces a rejected token without treating it as a successful update", async () => {- respond({ error: "the provider rejected the access token" }, 400);- await expect(new ApiClient("").updateVCSConnectionToken("ws-1", "conn-1", {- access_token: "bad-token",- })).rejects.toThrow("the provider rejected the access token");- });-});diff --git a/packages/core/vcs/index.ts b/packages/core/vcs/index.tsindex 868bf87e53..b69c251208 100644--- a/packages/core/vcs/index.ts+++ b/packages/core/vcs/index.ts@@ -1,2 +1 @@export * from "./queries";-export * from "./mutations";diff --git a/packages/core/vcs/mutations.ts b/packages/core/vcs/mutations.tsdeleted file mode 100644index 5cac78332d..0000000000--- a/packages/core/vcs/mutations.ts+++ /dev/null@@ -1,13 +0,0 @@-import { useMutation, useQueryClient } from "@tanstack/react-query";-import { api } from "../api";-import { vcsKeys } from "./queries";--export function useUpdateVCSConnectionToken(wsId: string) {- const qc = useQueryClient();- return useMutation({- gcTime: 0,- mutationFn: ({ connectionId, accessToken }: { connectionId: string; accessToken: string }) =>- api.updateVCSConnectionToken(wsId, connectionId, { access_token: accessToken }),- onSuccess: () => qc.invalidateQueries({ queryKey: vcsKeys.all(wsId) }),- });-}diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex c4bc9136f3..a1fab946d5 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -1038,11 +1038,6 @@"toast_connect_failed": "Could not connect to the provider","toast_disconnected": "Provider disconnected","toast_disconnect_failed": "Could not disconnect",- "update_token": "Update access token",- "update_token_description": "For {{url}}. Webhook settings and linked pull requests stay the same.",- "updating_token": "Updating...",- "toast_token_updated": "Access token updated",- "toast_update_token_failed": "Could not update access token","regenerate_webhook": "Regenerate webhook","rotate_confirm_title": "Regenerate webhook secret?","rotate_confirm_description": "The current webhook secret will stop working immediately. Deliveries from your Git provider will fail until you update the webhook secret in provider settings.",diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.jsonindex bebc0eb62a..087027d878 100644--- a/packages/views/locales/es/settings.json+++ b/packages/views/locales/es/settings.json@@ -1038,11 +1038,6 @@"toast_connect_failed": "No se ha podido conectar con el proveedor","toast_disconnected": "Proveedor desconectado","toast_disconnect_failed": "No se ha podido desconectar",- "update_token": "Actualizar token de acceso",- "update_token_description": "Para {{url}}. Se conservan la configuración del webhook y las pull requests vinculadas.",- "updating_token": "Actualizando...",- "toast_token_updated": "Token de acceso actualizado",- "toast_update_token_failed": "No se pudo actualizar el token de acceso","regenerate_webhook": "Regenerar webhook","rotate_confirm_title": "¿Regenerar el secreto del webhook?","rotate_confirm_description": "El secreto actual dejará de funcionar inmediatamente. Las entregas de tu proveedor de Git fallarán hasta que actualices el secreto del webhook en la configuración del proveedor.",diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.jsonindex f425a5c102..a56ec5a892 100644--- a/packages/views/locales/fr/settings.json+++ b/packages/views/locales/fr/settings.json@@ -1038,11 +1038,6 @@"toast_connect_failed": "Impossible de se connecter au fournisseur","toast_disconnected": "Fournisseur déconnecté","toast_disconnect_failed": "Impossible de déconnecter",- "update_token": "Mettre à jour le jeton d'accès",- "update_token_description": "Pour {{url}}. La configuration du webhook et les pull requests liées sont conservées.",- "updating_token": "Mise à jour...",- "toast_token_updated": "Jeton d'accès mis à jour",- "toast_update_token_failed": "Impossible de mettre à jour le jeton d'accès","regenerate_webhook": "Régénérer le webhook","rotate_confirm_title": "Régénérer le secret du webhook ?","rotate_confirm_description": "Le secret actuel du webhook cessera de fonctionner immédiatement. Les livraisons de votre fournisseur git échoueront tant que vous n'aurez pas mis à jour le secret dans ses paramètres.",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex d46a4bbbbf..456459232d 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -1029,11 +1029,6 @@"toast_connect_failed": "Could not connect to the provider","toast_disconnected": "Provider disconnected","toast_disconnect_failed": "Could not disconnect",- "update_token": "アクセストークンを更新",- "update_token_description": "{{url}} のトークンを更新します。Webhook 設定とリンク済みのプルリクエストは保持されます。",- "updating_token": "更新中...",- "toast_token_updated": "アクセストークンを更新しました",- "toast_update_token_failed": "アクセストークンを更新できませんでした","regenerate_webhook": "Regenerate webhook","rotate_confirm_title": "Regenerate webhook secret?","rotate_confirm_description": "The current webhook secret will stop working immediately. Deliveries from your Git provider will fail until you update the webhook secret in provider settings.",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex b5b06df717..b7b53e32eb 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -1029,11 +1029,6 @@"toast_connect_failed": "Could not connect to the provider","toast_disconnected": "Provider disconnected","toast_disconnect_failed": "Could not disconnect",- "update_token": "액세스 토큰 업데이트",- "update_token_description": "{{url}}의 토큰을 업데이트합니다. Webhook 설정과 연결된 풀 리퀘스트는 유지됩니다.",- "updating_token": "업데이트 중...",- "toast_token_updated": "액세스 토큰이 업데이트되었습니다",- "toast_update_token_failed": "액세스 토큰을 업데이트할 수 없습니다","regenerate_webhook": "Regenerate webhook","rotate_confirm_title": "Regenerate webhook secret?","rotate_confirm_description": "The current webhook secret will stop working immediately. Deliveries from your Git provider will fail until you update the webhook secret in provider settings.",diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.jsonindex 2e24c9a387..60d1557dc4 100644--- a/packages/views/locales/ru/settings.json+++ b/packages/views/locales/ru/settings.json@@ -1055,11 +1055,6 @@"toast_connect_failed": "Не удалось подключиться к провайдеру","toast_disconnected": "Провайдер отключён","toast_disconnect_failed": "Не удалось отключить",- "update_token": "Обновить токен доступа",- "update_token_description": "Для {{url}}. Настройки вебхука и связанные пул-реквесты сохраняются.",- "updating_token": "Обновление...",- "toast_token_updated": "Токен доступа обновлён",- "toast_update_token_failed": "Не удалось обновить токен доступа","regenerate_webhook": "Перегенерировать вебхук","rotate_confirm_title": "Перегенерировать секрет вебхука?","rotate_confirm_description": "Текущий секрет вебхука немедленно перестанет работать. Доставка событий от вашего Git-провайдера будет давать сбой, пока вы не обновите секрет вебхука в настройках провайдера.",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex 7c7cf47f6a..dad0b88d87 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -1029,11 +1029,6 @@"toast_connect_failed": "无法连接代码托管","toast_disconnected": "已断开代码托管连接","toast_disconnect_failed": "断开连接失败",- "update_token": "更新访问令牌",- "update_token_description": "更新 {{url}} 的令牌,保留 Webhook 配置和已关联的拉取请求。",- "updating_token": "更新中...",- "toast_token_updated": "访问令牌已更新",- "toast_update_token_failed": "无法更新访问令牌","regenerate_webhook": "重新生成 Webhook","rotate_confirm_title": "重新生成 Webhook 密钥?","rotate_confirm_description": "当前的 Webhook 密钥将立即失效。在代码托管设置中更新密钥前,来自该平台的推送将无法送达。",diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.jsonindex 15a6f1323e..91cd97cefb 100644--- a/packages/views/locales/zh-Hant/settings.json+++ b/packages/views/locales/zh-Hant/settings.json@@ -1029,11 +1029,6 @@"toast_connect_failed": "無法連線程式碼託管","toast_disconnected": "已斷開程式碼託管連線","toast_disconnect_failed": "斷開連線失敗",- "update_token": "更新存取權杖",- "update_token_description": "更新 {{url}} 的權杖,保留 Webhook 設定和已關聯的提取請求。",- "updating_token": "更新中...",- "toast_token_updated": "存取權杖已更新",- "toast_update_token_failed": "無法更新存取權杖","regenerate_webhook": "重新生成 Webhook","rotate_confirm_title": "重新生成 Webhook 金鑰?","rotate_confirm_description": "當前的 Webhook 金鑰將立即失效。在程式碼託管設定中更新金鑰前,來自該平臺的推送將無法送達。",diff --git a/packages/views/settings/components/code-vcs.test.tsx b/packages/views/settings/components/code-vcs.test.tsxindex ce50ba68d5..8630d6749c 100644--- a/packages/views/settings/components/code-vcs.test.tsx+++ b/packages/views/settings/components/code-vcs.test.tsx@@ -1,14 +1,11 @@import { beforeEach, describe, expect, it, vi } from "vitest";import { screen, waitFor, within } from "@testing-library/react";import userEvent from "@testing-library/user-event";-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { toast } from "sonner";import { renderWithI18n } from "../../test/i18n";const mockConnect = vi.hoisted(() => vi.fn());const mockRotate = vi.hoisted(() => vi.fn());const mockDelete = vi.hoisted(() => vi.fn());-const mockUpdateToken = vi.hoisted(() => vi.fn());const listing = vi.hoisted(() => ({current: {connections: [] as {@@ -22,8 +19,7 @@ const listing = vi.hoisted(() => ({},}));-vi.mock("@tanstack/react-query", async (importOriginal) => ({- ...await importOriginal<typeof import("@tanstack/react-query")>(),+vi.mock("@tanstack/react-query", () => ({useQuery: () => ({ data: listing.current }),useQueryClient: () => ({ invalidateQueries: vi.fn() }),queryOptions: <T,>(opts: T) => opts,@@ -34,22 +30,12 @@ vi.mock("@multica/core/api", () => ({connectVCS: mockConnect,rotateVCSWebhook: mockRotate,deleteVCSConnection: mockDelete,- updateVCSConnectionToken: mockUpdateToken,},}));vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));import { VCSConnectionRows } from "./code-vcs";-function renderRows() {- const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });- return renderWithI18n(- <QueryClientProvider client={client}>- <VCSConnectionRows />- </QueryClientProvider>,- );-}-const CONNECTION = {id: "vcs-1",provider: "gitea" as const,@@ -63,62 +49,6 @@ beforeEach(() => {});describe("VCSConnectionRows", () => {- async function openTokenDialog(user: ReturnType<typeof userEvent.setup>) {- await user.click(screen.getByRole("button", { name: "Actions for https://git.acme.dev" }));- await user.click(await screen.findByRole("menuitem", { name: "Update access token" }));- return screen.findByRole("dialog", { name: "Update access token" });- }-- it("updates only the selected connection's token and clears it after success", async () => {- listing.current.connections = [CONNECTION];- let finish!: (value: unknown) => void;- mockUpdateToken.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));- const user = userEvent.setup();- renderRows();- const dialog = await openTokenDialog(user);- const submit = within(dialog).getByRole("button", { name: "Update access token" });- expect(submit).toBeDisabled();- const input = within(dialog).getByLabelText("Access token");- expect(input).toHaveAttribute("type", "password");- await user.type(input, " replacement-token ");- await user.click(submit);- expect(mockUpdateToken).toHaveBeenCalledWith("ws-1", "vcs-1", { access_token: "replacement-token" });- expect(within(dialog).getByRole("button", { name: "Updating..." })).toBeDisabled();- expect(within(dialog).getByRole("button", { name: "Cancel" })).toBeDisabled();- await user.keyboard("{Escape}");- expect(dialog).toBeInTheDocument();- finish({ ...CONNECTION, account_login: "service-bot" });- await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());- expect(toast.success).toHaveBeenCalledWith("Access token updated");- expect(mockRotate).not.toHaveBeenCalled();- expect(mockConnect).not.toHaveBeenCalled();- const reopened = await openTokenDialog(user);- expect(within(reopened).getByLabelText("Access token")).toHaveValue("");- });-- it("keeps a rejected token available for correction and clears it when cancelled", async () => {- listing.current.connections = [CONNECTION];- mockUpdateToken.mockRejectedValue(new Error("the provider rejected the access token"));- const user = userEvent.setup();- renderRows();- const dialog = await openTokenDialog(user);- await user.type(within(dialog).getByLabelText("Access token"), "rejected-token");- await user.click(within(dialog).getByRole("button", { name: "Update access token" }));- await waitFor(() => expect(toast.error).toHaveBeenCalledWith("the provider rejected the access token"));- expect(within(dialog).getByLabelText("Access token")).toHaveValue("rejected-token");- await user.click(within(dialog).getByRole("button", { name: "Cancel" }));- await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());- const reopened = await openTokenDialog(user);- expect(within(reopened).getByLabelText("Access token")).toHaveValue("");- });-- it("hides connection actions from members", () => {- listing.current = { connections: [CONNECTION], configured: true, can_manage: false };- renderRows();- expect(screen.getByText("Gitea · https://git.acme.dev")).toBeInTheDocument();- expect(screen.queryByRole("button")).toBeNull();- });-it("connects an instance from a dialog and then shows the one-time webhook secret", async () => {mockConnect.mockResolvedValue({...CONNECTION,@@ -127,7 +57,7 @@ describe("VCSConnectionRows", () => {webhook_secret: "s3cret",});const user = userEvent.setup();- renderRows();+ renderWithI18n(<VCSConnectionRows />);await user.click(screen.getByRole("button", { name: "Connect" }));const form = await screen.findByRole("dialog");@@ -151,7 +81,7 @@ describe("VCSConnectionRows", () => {it("lists connected instances with their actions", async () => {listing.current.connections = [CONNECTION];const user = userEvent.setup();- renderRows();+ renderWithI18n(<VCSConnectionRows />);expect(screen.getByText("Gitea · https://git.acme.dev")).toBeInTheDocument();await user.click(@@ -167,7 +97,7 @@ describe("VCSConnectionRows", () => {it("explains the missing server key instead of offering a dead connect", () => {listing.current.configured = false;- renderRows();+ renderWithI18n(<VCSConnectionRows />);expect(screen.getByText("MULTICA_VCS_SECRET_KEY")).toBeInTheDocument();expect(screen.getByRole("button", { name: "Connect" })).toBeDisabled();@@ -175,7 +105,7 @@ describe("VCSConnectionRows", () => {it("asks members to contact an admin when nothing is connected", () => {listing.current.can_manage = false;- renderRows();+ renderWithI18n(<VCSConnectionRows />);expect(screen.queryByRole("button", { name: "Connect" })).toBeNull();expect(screen.getByText(/Ask a workspace admin/)).toBeInTheDocument();diff --git a/packages/views/settings/components/code-vcs.tsx b/packages/views/settings/components/code-vcs.tsxindex 3ea551592c..bfac2efd68 100644--- a/packages/views/settings/components/code-vcs.tsx+++ b/packages/views/settings/components/code-vcs.tsx@@ -3,7 +3,7 @@import { useState } from "react";import { useQuery, useQueryClient } from "@tanstack/react-query";import { toast } from "sonner";-import { Copy, FolderGit2, GitBranch, KeyRound, Loader2, MoreHorizontal, RefreshCw, Unplug } from "@multica/ui/icons";+import { Copy, FolderGit2, GitBranch, MoreHorizontal, RefreshCw, Unplug } from "@multica/ui/icons";import { Button } from "@multica/ui/components/ui/button";import { IconButton } from "@multica/ui/components/common/icon-button";import { Input } from "@multica/ui/components/ui/input";@@ -41,7 +41,7 @@ import {DropdownMenuTrigger,} from "@multica/ui/components/ui/dropdown-menu";import { useWorkspaceId } from "@multica/core/hooks";-import { useUpdateVCSConnectionToken, vcsConnectionsOptions } from "@multica/core/vcs";+import { vcsConnectionsOptions } from "@multica/core/vcs";import { api } from "@multica/core/api";import type { ConnectVCSResponse, VCSProvider } from "@multica/core/types";import { useT } from "../../i18n";@@ -80,9 +80,6 @@ export function VCSConnectionRows() {const [instanceUrl, setInstanceUrl] = useState("");const [token, setToken] = useState("");const [connecting, setConnecting] = useState(false);- const [tokenTarget, setTokenTarget] = useState<string | null>(null);- const [replacementToken, setReplacementToken] = useState("");- const updateToken = useUpdateVCSConnectionToken(wsId);const [webhook, setWebhook] = useState<ConnectVCSResponse | null>(null);const [rotateTarget, setRotateTarget] = useState<string | null>(null);const [rotating, setRotating] = useState(false);@@ -140,24 +137,6 @@ export function VCSConnectionRows() {}}- async function handleUpdateToken() {- if (!tokenTarget || updateToken.isPending || !replacementToken.trim()) return;- try {- await updateToken.mutateAsync({- connectionId: tokenTarget,- accessToken: replacementToken.trim(),- });- setReplacementToken("");- setTokenTarget(null);- toast.success(t(($) => $.vcs.toast_token_updated));- } catch (e) {- toast.error(e instanceof Error ? e.message : t(($) => $.vcs.toast_update_token_failed));- } finally {- // Mutation variables contain the token; retain it only in the open form.- updateToken.reset();- }- }-async function copy(value: string) {try {await navigator.clipboard.writeText(value);@@ -220,10 +199,6 @@ export function VCSConnectionRows() {<MoreHorizontal /></DropdownMenuTrigger><DropdownMenuContent align="end" className="w-auto">- <DropdownMenuItem onClick={() => setTokenTarget(c.id)}>- <KeyRound />- {t(($) => $.vcs.update_token)}- </DropdownMenuItem><DropdownMenuItem onClick={() => setRotateTarget(c.id)}><RefreshCw />{t(($) => $.vcs.regenerate_webhook)}@@ -358,68 +333,6 @@ export function VCSConnectionRows() {</DialogContent></Dialog>- <Dialog- open={!!tokenTarget}- onOpenChange={(open) => {- if (!open && !updateToken.isPending) {- setTokenTarget(null);- setReplacementToken("");- }- }}- >- <DialogContent className="sm:max-w-lg">- <DialogHeader>- <DialogTitle>{t(($) => $.vcs.update_token)}</DialogTitle>- <DialogDescription>- {t(($) => $.vcs.update_token_description, {- url: connections.find((connection) => connection.id === tokenTarget)?.instance_url ?? "",- })}- </DialogDescription>- </DialogHeader>- <form- className="space-y-4"- onSubmit={(event) => {- event.preventDefault();- void handleUpdateToken();- }}- >- <div className="space-y-1.5">- <Label htmlFor="vcs-replacement-token">{t(($) => $.vcs.form_token_label)}</Label>- <Input- id="vcs-replacement-token"- type="password"- autoComplete="off"- placeholder={t(($) => $.vcs.form_token_placeholder)}- value={replacementToken}- onChange={(event) => setReplacementToken(event.target.value)}- disabled={updateToken.isPending}- />- </div>- <DialogFooter>- <Button- type="button"- variant="outline"- disabled={updateToken.isPending}- onClick={() => {- setTokenTarget(null);- setReplacementToken("");- }}- >- {t(($) => $.vcs.disconnect_confirm_cancel)}- </Button>- <Button- type="submit"- disabled={updateToken.isPending || !replacementToken.trim()}- aria-busy={updateToken.isPending || undefined}- >- {updateToken.isPending ? <Loader2 className="animate-spin" aria-hidden="true" /> : null}- {updateToken.isPending ? t(($) => $.vcs.updating_token) : t(($) => $.vcs.update_token)}- </Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>-<Dialogopen={!!webhook}onOpenChange={(open) => {diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 8f56a21746..b5f33c4753 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1901,7 +1901,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Get("/github/connect", h.GitHubConnect)r.Get("/github/installations/{installationId}/repositories", h.ListGitHubInstallationRepositories)r.Delete("/github/installations/{installationId}", h.DeleteGitHubInstallation)- // VCS connection and credential management (admin-only).+ // VCS connect / disconnect / webhook regeneration (admin-only).r.Post("/vcs/connections", h.ConnectVCS)r.Put("/qoder", h.SaveQoderConnection)r.Post("/qoder/check", h.CheckQoderConnection)@@ -1910,7 +1910,6 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/qoder/resume", h.ResumeQoderConnection)r.Delete("/qoder", h.DisconnectQoderConnection)r.Post("/vcs/connections/{connectionId}/rotate-webhook", h.RotateVCSConnectionWebhook)- r.Post("/vcs/connections/{connectionId}/token", h.UpdateVCSConnectionToken)r.Delete("/vcs/connections/{connectionId}", h.DeleteVCSConnection)})diff --git a/server/cmd/server/vcs_token_test.go b/server/cmd/server/vcs_token_test.godeleted file mode 100644index 3c7bdc622c..0000000000--- a/server/cmd/server/vcs_token_test.go+++ /dev/null@@ -1,73 +0,0 @@-package main--import (- "bytes"- "encoding/base64"- "encoding/json"- "net/http"- "net/http/httptest"- "testing"-- "github.com/google/uuid"- "github.com/multica-ai/multica/server/internal/analytics"- "github.com/multica-ai/multica/server/internal/events"- "github.com/multica-ai/multica/server/internal/realtime"- "github.com/multica-ai/multica/server/internal/testutil"-)--func TestUpdateVCSConnectionTokenRoutePermissions(t *testing.T) {- t.Setenv("MULTICA_VCS_INTEGRATION_ENABLED", "true")- t.Setenv("MULTICA_VCS_SECRET_KEY", base64.StdEncoding.EncodeToString(bytes.Repeat([]byte("k"), 32)))- server := httptest.NewServer(NewRouter(testPool, realtime.NewHub(), events.New(), analytics.NoopClient{}, nil))- defer server.Close()- f := testutil.New(testPool, testWorkspaceID, testUserID)- for _, tt := range []struct {- role string- status int- }{- {"owner", http.StatusNotFound},- {"admin", http.StatusNotFound},- {"member", http.StatusForbidden},- {"outsider", http.StatusNotFound},- {"anonymous", http.StatusUnauthorized},- } {- t.Run(tt.role, func(t *testing.T) {- req, err := http.NewRequest(http.MethodPost,- server.URL+"/api/workspaces/"+testWorkspaceID+"/vcs/connections/"+uuid.NewString()+"/token", nil)- if err != nil {- t.Fatal(err)- }- if tt.role != "anonymous" {- email := "vcs-token-" + uuid.NewString() + "@example.test"- id := f.User(t, "VCS token test", email)- if tt.role != "outsider" {- f.Member(t, testWorkspaceID, id, tt.role)- }- token, err := generateTestJWT(id, email, "VCS token test")- if err != nil {- t.Fatal(err)- }- req.Header.Set("Authorization", "Bearer "+token)- }- resp, err := http.DefaultClient.Do(req)- if err != nil {- t.Fatal(err)- }- defer resp.Body.Close()- if resp.StatusCode != tt.status {- t.Fatalf("role %s: status = %d, want %d", tt.role, resp.StatusCode, tt.status)- }- if tt.role == "owner" || tt.role == "admin" {- var body struct {- Error string `json:"error"`- }- if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {- t.Fatal(err)- }- if body.Error != "vcs connection not found" {- t.Fatalf("admin request did not reach token handler: %s", body.Error)- }- }- })- }-}diff --git a/server/internal/handler/vcs.go b/server/internal/handler/vcs.goindex aa8ac52e2a..a383112acc 100644--- a/server/internal/handler/vcs.go+++ b/server/internal/handler/vcs.go@@ -356,81 +356,6 @@ func (h *Handler) RotateVCSConnectionWebhook(w http.ResponseWriter, r *http.Requ})}-type updateVCSConnectionTokenRequest struct {- AccessToken string `json:"access_token"`-}--// UpdateVCSConnectionToken validates and replaces a connection's access token-// without changing its instance, webhook secret, or mirrored pull requests.-func (h *Handler) UpdateVCSConnectionToken(w http.ResponseWriter, r *http.Request) {- workspaceID := chi.URLParam(r, "id")- wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")- if !ok {- return- }- connUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "connectionId"), "connection id")- if !ok {- return- }- if !h.isVCSAvailable() {- writeError(w, http.StatusNotFound, "vcs integration is not available on this deployment")- return- }- if !h.isVCSConfigured() {- writeFeatureDisabled(w, "vcs_not_configured", "vcs integration not configured (MULTICA_VCS_SECRET_KEY unset)")- return- }-- conn, err := h.Queries.GetVCSConnectionByID(r.Context(), connUUID)- if err != nil || conn.WorkspaceID != wsUUID {- writeError(w, http.StatusNotFound, "vcs connection not found")- return- }- var req updateVCSConnectionTokenRequest- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- writeError(w, http.StatusBadRequest, "invalid request body")- return- }- token := strings.TrimSpace(req.AccessToken)- if token == "" {- writeError(w, http.StatusBadRequest, "access_token is required")- return- }- provider, ok := vcs.For(conn.Provider)- if !ok {- writeError(w, http.StatusBadRequest, "unsupported provider")- return- }- account, err := provider.ValidateToken(r.Context(), conn.InstanceUrl, token)- if err != nil {- if errors.Is(err, vcs.ErrUnauthorized) {- writeError(w, http.StatusBadRequest, "the provider rejected the access token")- return- }- slog.Warn("vcs: token validation failed", "workspace_id", workspaceID, "provider", provider.Kind())- writeError(w, http.StatusBadGateway, vcsValidationFailureMessage(err))- return- }- tokenEnc, err := h.sealVCSSecret(token)- if err != nil {- writeError(w, http.StatusInternalServerError, "failed to encrypt token")- return- }- updated, err := h.Queries.UpdateVCSConnectionToken(r.Context(), db.UpdateVCSConnectionTokenParams{- ID: connUUID,- WorkspaceID: wsUUID,- AccessTokenEncrypted: tokenEnc,- AccountLogin: account.Login,- })- if err != nil {- writeError(w, http.StatusInternalServerError, "failed to update access token")- return- }- resp := h.vcsConnectionToResponse(updated)- h.publish(protocol.EventVCSConnectionCreated, workspaceID, "system", "", map[string]any{"id": resp.ID})- writeJSON(w, http.StatusOK, resp)-}-// newVCSWebhookSecret returns a 32-byte random secret as hex (64 chars).func newVCSWebhookSecret() (string, error) {b := make([]byte, 32)diff --git a/server/internal/handler/vcs_test.go b/server/internal/handler/vcs_test.goindex 617077e6f8..1c57ae076d 100644--- a/server/internal/handler/vcs_test.go+++ b/server/internal/handler/vcs_test.go@@ -4,7 +4,6 @@ import ("context""crypto/tls""encoding/json"- "errors""fmt""net/http""net/http/httptest"@@ -14,179 +13,9 @@ import ("time""github.com/go-chi/chi/v5"- "github.com/google/uuid"- "github.com/jackc/pgx/v5""github.com/multica-ai/multica/server/internal/testutil"- db "github.com/multica-ai/multica/server/pkg/db/generated")-func TestUpdateVCSConnectionToken(t *testing.T) {- for _, kind := range []string{"gitlab", "gitea", "forgejo"} {- t.Run(kind, func(t *testing.T) {- ctx := context.Background()- withVCSBox(t)- var validationCalls int- provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- validationCalls++- wantPath, header, wantToken := "/api/v1/user", "Authorization", "token replacement-token"- if kind == "gitlab" {- wantPath, header, wantToken = "/api/v4/user", "PRIVATE-TOKEN", "replacement-token"- }- if r.URL.Path != wantPath || r.Header.Get(header) != wantToken {- t.Errorf("unexpected validation request: %s, credential matches=%v", r.URL.Path, r.Header.Get(header) == wantToken)- }- w.Header().Set("Content-Type", "application/json")- _, _ = w.Write([]byte(`{"login":"service-bot","username":"service-bot"}`))- }))- defer provider.Close()- tokenEnc, err := testHandler.sealVCSSecret("old-token")- if err != nil {- t.Fatal(err)- }- secretEnc, err := testHandler.sealVCSSecret(vcsTestSecret)- if err != nil {- t.Fatal(err)- }- id := dbfx.Insert(t, "vcs_connection", testutil.Cols{- "workspace_id": testWorkspaceID, "provider": kind, "instance_url": provider.URL,- "account_login": "old-account", "access_token_encrypted": tokenEnc,- "webhook_secret_encrypted": secretEnc, "connected_by_id": testUserID,- })- before, err := testHandler.Queries.GetVCSConnectionByID(ctx, parseUUID(id))- if err != nil {- t.Fatal(err)- }- issueID := dbfx.Issue(t, "Keep linked pull request")- prID := dbfx.Insert(t, "vcs_pull_request", testutil.Cols{- "workspace_id": testWorkspaceID, "connection_id": id, "provider": kind,- "repo_owner": "acme", "repo_name": "app", "pr_number": 1, "title": "Keep me",- "state": "open", "html_url": provider.URL + "/acme/app/pulls/1",- "pr_created_at": time.Now(), "pr_updated_at": time.Now(),- })- dbfx.InsertNoID(t, "issue_vcs_pull_request",- testutil.Cols{"issue_id": issueID, "pull_request_id": prID},- "issue_id = $1 AND pull_request_id = $2", issueID, prID)-- req := vcsHandlerRequest(http.MethodPost, "/token", map[string]any{- "access_token": " replacement-token ",- "instance_url": "https://ignored.example.test",- "provider": "ignored",- }, id)- var resp map[string]any- testutil.Call(t, testHandler.UpdateVCSConnectionToken, req).Want(http.StatusOK).JSON(&resp)- if resp["id"] != id || resp["account_login"] != "service-bot" || resp["instance_url"] != provider.URL || resp["provider"] != kind {- t.Fatalf("unexpected connection response: %+v", resp)- }- for _, key := range []string{"access_token", "access_token_encrypted", "webhook_secret", "webhook_secret_encrypted"} {- if _, present := resp[key]; present {- t.Fatalf("response exposes %s", key)- }- }- after, err := testHandler.Queries.GetVCSConnectionByID(ctx, parseUUID(id))- if err != nil {- t.Fatal(err)- }- token, err := testHandler.openVCSSecret(after.AccessTokenEncrypted)- if err != nil || token != "replacement-token" || after.AccessTokenEncrypted == token {- t.Fatal("replacement token must be stored encrypted and decrypt correctly")- }- if after.WebhookSecretEncrypted != before.WebhookSecretEncrypted || after.ConnectedByID != before.ConnectedByID || after.CreatedAt != before.CreatedAt {- t.Fatal("token update changed webhook secret or connection identity")- }- linked, err := testHandler.Queries.ListVCSPullRequestsByIssue(ctx, parseUUID(issueID))- if err != nil || len(linked) != 1 || uuidToString(linked[0].ID) != prID {- t.Fatalf("linked pull request lost: %v, %+v", err, linked)- }- if validationCalls != 1 {- t.Fatalf("expected one provider validation, got %d", validationCalls)- }- _, err = testHandler.Queries.UpdateVCSConnectionToken(ctx, db.UpdateVCSConnectionTokenParams{- ID: parseUUID(id), WorkspaceID: parseUUID(uuid.NewString()),- AccessTokenEncrypted: "wrong-workspace", AccountLogin: "wrong-workspace",- })- if !errors.Is(err, pgx.ErrNoRows) {- t.Fatalf("cross-workspace write should return no rows, got %v", err)- }- })- }-}--func TestUpdateVCSConnectionTokenFailuresPreserveConnection(t *testing.T) {- tests := []struct {- name string- token string- providerStatus int- foreignWorkspace bool- missingConnection bool- disabled bool- unconfigured bool- wantStatus int- wantCalls int- wantError string- }{- {name: "rejected token", token: "rejected", providerStatus: http.StatusUnauthorized, wantStatus: http.StatusBadRequest, wantCalls: 1, wantError: "rejected"},- {name: "insufficient permissions", token: "rejected", providerStatus: http.StatusForbidden, wantStatus: http.StatusBadRequest, wantCalls: 1, wantError: "rejected"},- {name: "provider failure", token: "valid", providerStatus: http.StatusInternalServerError, wantStatus: http.StatusBadGateway, wantCalls: 1, wantError: "could not reach"},- {name: "empty token", token: " ", wantStatus: http.StatusBadRequest, wantError: "access_token is required"},- {name: "other workspace", token: "valid", foreignWorkspace: true, wantStatus: http.StatusNotFound},- {name: "missing connection", token: "valid", missingConnection: true, wantStatus: http.StatusNotFound},- {name: "disabled", token: "valid", disabled: true, wantStatus: http.StatusNotFound},- {name: "unconfigured", token: "valid", unconfigured: true, wantStatus: http.StatusForbidden},- }- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- withVCSBox(t)- var calls int- provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- calls++- w.WriteHeader(tt.providerStatus)- }))- defer provider.Close()- tokenEnc, err := testHandler.sealVCSSecret("old-token")- if err != nil {- t.Fatal(err)- }- secretEnc, err := testHandler.sealVCSSecret(vcsTestSecret)- if err != nil {- t.Fatal(err)- }- id := dbfx.Insert(t, "vcs_connection", testutil.Cols{- "workspace_id": testWorkspaceID, "provider": "gitlab", "instance_url": provider.URL,- "account_login": "old-account", "access_token_encrypted": tokenEnc, "webhook_secret_encrypted": secretEnc,- })- reqID := id- if tt.missingConnection {- reqID = uuid.NewString()- }- req := vcsHandlerRequest(http.MethodPost, "/token", map[string]any{"access_token": tt.token}, reqID)- if tt.foreignWorkspace {- chi.RouteContext(req.Context()).URLParams.Add("id", uuid.NewString())- }- if tt.disabled {- testHandler.cfg.VCSIntegrationEnabled = false- }- if tt.unconfigured {- testHandler.VCSSecretBox = nil- }- var resp map[string]any- testutil.Call(t, testHandler.UpdateVCSConnectionToken, req).Want(tt.wantStatus).JSON(&resp)- if tt.wantError != "" && !strings.Contains(fmt.Sprint(resp["error"]), tt.wantError) {- t.Fatalf("unexpected error: %+v", resp)- }- if calls != tt.wantCalls {- t.Fatalf("provider calls = %d, want %d", calls, tt.wantCalls)- }- after, err := testHandler.Queries.GetVCSConnectionByID(context.Background(), parseUUID(id))- if err != nil {- t.Fatal(err)- }- if after.AccessTokenEncrypted != tokenEnc || after.WebhookSecretEncrypted != secretEnc || after.AccountLogin != "old-account" {- t.Fatal("failed update modified the connection")- }- })- }-}-func vcsHandlerRequest(method, path string, body any, connectionID string) *http.Request {req := newRequest(method, path, body)rctx := chi.NewRouteContext()diff --git a/server/pkg/db/generated/vcs.sql.go b/server/pkg/db/generated/vcs.sql.goindex b794f2ba43..ed88522652 100644--- a/server/pkg/db/generated/vcs.sql.go+++ b/server/pkg/db/generated/vcs.sql.go@@ -550,45 +550,6 @@ func (q *Queries) UnlinkIssueFromVCSPullRequest(ctx context.Context, arg UnlinkIreturn result.RowsAffected(), nil}-const updateVCSConnectionToken = `-- name: UpdateVCSConnectionToken :one-UPDATE vcs_connection-SET access_token_encrypted = $3,- account_login = $4,- updated_at = now()-WHERE id = $1 AND workspace_id = $2-RETURNING id, workspace_id, provider, instance_url, account_login, access_token_encrypted, webhook_secret_encrypted, connected_by_id, created_at, updated_at-`--type UpdateVCSConnectionTokenParams struct {- ID pgtype.UUID `json:"id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`- AccessTokenEncrypted string `json:"access_token_encrypted"`- AccountLogin string `json:"account_login"`-}--func (q *Queries) UpdateVCSConnectionToken(ctx context.Context, arg UpdateVCSConnectionTokenParams) (VcsConnection, error) {- row := q.db.QueryRow(ctx, updateVCSConnectionToken,- arg.ID,- arg.WorkspaceID,- arg.AccessTokenEncrypted,- arg.AccountLogin,- )- var i VcsConnection- err := row.Scan(- &i.ID,- &i.WorkspaceID,- &i.Provider,- &i.InstanceUrl,- &i.AccountLogin,- &i.AccessTokenEncrypted,- &i.WebhookSecretEncrypted,- &i.ConnectedByID,- &i.CreatedAt,- &i.UpdatedAt,- )- return i, err-}-const upsertVCSCommitStatus = `-- name: UpsertVCSCommitStatus :execINSERT INTO vcs_commit_status (diff --git a/server/pkg/db/queries/vcs.sql b/server/pkg/db/queries/vcs.sqlindex d265abe2c6..94ef3cf9c0 100644--- a/server/pkg/db/queries/vcs.sql+++ b/server/pkg/db/queries/vcs.sql@@ -61,14 +61,6 @@ SET webhook_secret_encrypted = $3,WHERE id = $1 AND workspace_id = $2RETURNING *;--- name: UpdateVCSConnectionToken :one-UPDATE vcs_connection-SET access_token_encrypted = $3,- account_login = $4,- updated_at = now()-WHERE id = $1 AND workspace_id = $2-RETURNING *;--- =====================-- VCS Pull Request-- =====================