⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(integrations): guard imported issue linking writes
Tind356119c53a2
diff --git a/apps/api/src/plugins/gitea/webhooks/issue-opened.ts b/apps/api/src/plugins/gitea/webhooks/issue-opened.tsindex e18dd8d83..f5dd9c996 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-opened.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-opened.ts@@ -1,6 +1,7 @@import { acceptsIssue } from "../../sync/rules";import { importIssueLabels } from "../../sync/issue-labels";import { canSyncTask } from "../../sync/eligibility";+import { createIssueWrite } from "../../sync/dispatch-issue-write";import { and, eq } from "drizzle-orm";import db from "../../../database";import {@@ -169,11 +170,16 @@ export async function handleGiteaIssueOpened(issue.labels,tx,);- await canSyncTask(task.id, integration.id, tx, integration.config);- return { task, link, linkMetadata };+ const eligible = await canSyncTask(+ task.id,+ integration.id,+ tx,+ integration.config,+ );+ return { task, link, linkMetadata, eligible };});if (!result) continue;- const { task: createdTask } = result;+ const { task: createdTask, link, eligible } = result;await publishEvent("task.created", {...createdTask,@@ -185,6 +191,11 @@ export async function handleGiteaIssueOpened(externalId: issue.number.toString(),actor: issue.user?.login ?? issue.user?.username ?? "gitea-webhook",});+ if (!eligible) continue;+ const write = createIssueWrite(+ { id: link.id, taskId: createdTask.id, integrationId: integration.id },+ integration.config,+ );const project = await db.query.projectTable.findFirst({where: eq(projectTable.id, projectId),@@ -217,19 +228,32 @@ export async function handleGiteaIssueOpened(}if (labelsToAdd.length > 0) {- await addLabelsToIssueGitea(config, issue.number, labelsToAdd);+ await addLabelsToIssueGitea(+ config,+ issue.number,+ labelsToAdd,+ true,+ write,+ );}if (config.commentTaskLinkOnGiteaIssue !== false) {- await client.createIssueComment(- config.repositoryOwner,- config.repositoryName,- issue.number,- markKaneoComment(`[${taskIdentifier}](${taskUrl})`),+ await write(() =>+ client.createIssueComment(+ config.repositoryOwner,+ config.repositoryName,+ issue.number,+ markKaneoComment(`[${taskIdentifier}](${taskUrl})`),+ ),);}- } catch (error) {- console.error("Failed to process Gitea issue:", error);+ } catch {+ console.error("Gitea imported issue linking write failed", {+ projectId,+ taskId: createdTask.id,+ integrationId: integration.id,+ linkId: link.id,+ });}}}diff --git a/apps/api/src/plugins/github/webhooks/issue-opened.ts b/apps/api/src/plugins/github/webhooks/issue-opened.tsindex c9828448f..81a2fc3df 100644--- a/apps/api/src/plugins/github/webhooks/issue-opened.ts+++ b/apps/api/src/plugins/github/webhooks/issue-opened.ts@@ -1,6 +1,7 @@import { acceptsIssue } from "../../sync/rules";import { importIssueLabels } from "../../sync/issue-labels";import { canSyncTask } from "../../sync/eligibility";+import { createIssueWrite } from "../../sync/dispatch-issue-write";import { and, eq } from "drizzle-orm";import db from "../../../database";import { publishEvent } from "../../../events";@@ -79,7 +80,7 @@ export async function handleIssueOpened(const priority = extractIssuePriority(issue.labels);const status = extractIssueStatus(issue.labels);- const createdTask = await db.transaction(async (tx) => {+ const result = await db.transaction(async (tx) => {// Use the same integration lock as resumable imports before checking the// link. The task and link must either both commit or both roll back.const [current] = await tx@@ -131,7 +132,7 @@ export async function handleIssueOpened(}).returning();if (!task) throw new Error("Failed to create task from GitHub issue");- await createExternalLink(+ const link = await createExternalLink({taskId: task.id,integrationId: integration.id,@@ -153,10 +154,16 @@ export async function handleIssueOpened(issue.labels,tx,);- await canSyncTask(task.id, integration.id, tx, integration.config);- return task;+ const eligible = await canSyncTask(+ task.id,+ integration.id,+ tx,+ integration.config,+ );+ return { task, link, eligible };});- if (!createdTask) continue;+ if (!result) continue;+ const { task: createdTask, link, eligible } = result;await publishEvent("task.created", {...createdTask,taskId: createdTask.id,@@ -167,6 +174,11 @@ export async function handleIssueOpened(externalId: issue.number.toString(),actor: issue.user?.login ?? "github-webhook",});+ if (!eligible) continue;+ const write = createIssueWrite(+ { id: link.id, taskId: createdTask.id, integrationId: integration.id },+ integration.config,+ );const project = await db.query.projectTable.findFirst({where: eq(projectTable.id, projectId),@@ -216,19 +228,28 @@ export async function handleIssueOpened(repository.name,issue.number,labelsToAdd,+ true,+ write,);}if (config.commentTaskLinkOnGitHubIssue !== false) {- await octokit.rest.issues.createComment({- owner: repository.owner.login,- repo: repository.name,- issue_number: issue.number,- body: `[${taskIdentifier}](${taskUrl})`,- });+ await write(() =>+ octokit.rest.issues.createComment({+ owner: repository.owner.login,+ repo: repository.name,+ issue_number: issue.number,+ body: `[${taskIdentifier}](${taskUrl})`,+ }),+ );}- } catch (error) {- console.error("Failed to process GitHub issue:", error);+ } catch {+ console.error("GitHub imported issue linking write failed", {+ projectId,+ taskId: createdTask.id,+ integrationId: integration.id,+ linkId: link.id,+ });}}}diff --git a/apps/api/src/plugins/gitlab/webhooks/issue-opened.ts b/apps/api/src/plugins/gitlab/webhooks/issue-opened.tsindex a7dba399c..a70becc1f 100644--- a/apps/api/src/plugins/gitlab/webhooks/issue-opened.ts+++ b/apps/api/src/plugins/gitlab/webhooks/issue-opened.ts@@ -1,6 +1,7 @@import { acceptsIssue } from "../../sync/rules";import { importIssueLabels } from "../../sync/issue-labels";import { canSyncTask } from "../../sync/eligibility";+import { createIssueWrite } from "../../sync/dispatch-issue-write";import { and, eq } from "drizzle-orm";import db from "../../../database";import {@@ -175,11 +176,21 @@ export async function handleGitlabIssueOpened(payload.labels,tx,);- await canSyncTask(task.id, integration.id, tx, integration.config);- return { task, link, linkMetadata };+ const eligible = await canSyncTask(+ task.id,+ integration.id,+ tx,+ integration.config,+ );+ return { task, link, linkMetadata, eligible };});if (!result) continue;- const { task: createdTask, link: issueLink, linkMetadata } = result;+ const {+ task: createdTask,+ link: issueLink,+ linkMetadata,+ eligible,+ } = result;await publishEvent("task.created", {...createdTask,@@ -191,6 +202,15 @@ export async function handleGitlabIssueOpened(externalId: issue.iid.toString(),actor: author ?? "gitlab-webhook",});+ if (!eligible) continue;+ const write = createIssueWrite(+ {+ id: issueLink.id,+ taskId: createdTask.id,+ integrationId: integration.id,+ },+ integration.config,+ );const kaneoProject = await db.query.projectTable.findFirst({where: eq(projectTable.id, projectId),@@ -216,14 +236,22 @@ export async function handleGitlabIssueOpened(}if (labelsToAdd.length > 0) {- await addLabelsToIssueGitlab(config, issue.iid, labelsToAdd);+ await addLabelsToIssueGitlab(+ config,+ issue.iid,+ labelsToAdd,+ true,+ write,+ );}if (config.commentTaskLinkOnGitlabIssue !== false) {- const note = await createGitlabClient(config).createIssueNote(- config.projectPath,- issue.iid,- `[${taskIdentifier}](${taskUrl})`,+ const note = await write(() =>+ createGitlabClient(config).createIssueNote(+ config.projectPath,+ issue.iid,+ `[${taskIdentifier}](${taskUrl})`,+ ),);await updateExternalLink(issueLink.id, {@@ -233,8 +261,13 @@ export async function handleGitlabIssueOpened(},});}- } catch (error) {- console.error("Failed to process GitLab issue:", error);+ } catch {+ console.error("GitLab imported issue linking write failed", {+ projectId,+ taskId: createdTask.id,+ integrationId: integration.id,+ linkId: issueLink.id,+ });}}}diff --git a/tests/api-integration/integration-sync-issue-opened-writes.test.ts b/tests/api-integration/integration-sync-issue-opened-writes.test.tsnew file mode 100644index 000000000..35eee4775--- /dev/null+++ b/tests/api-integration/integration-sync-issue-opened-writes.test.ts@@ -0,0 +1,228 @@+import { and, eq, sql } from "drizzle-orm";+import { beforeEach, expect, it, vi } from "vite-plus/test";+import db, { schema } from "../../apps/api/src/database";+import * as events from "../../apps/api/src/events";+import { handleIssueOpened } from "../../apps/api/src/plugins/github/webhooks/issue-opened";+import { handleGiteaIssueOpened } from "../../apps/api/src/plugins/gitea/webhooks/issue-opened";+import { handleGitlabIssueOpened } from "../../apps/api/src/plugins/gitlab/webhooks/issue-opened";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++const provider = vi.hoisted(() => ({ labels: vi.fn(), comment: vi.fn() }));+vi.mock("../../apps/api/src/plugins/github/utils/github-app", () => ({+ getGithubApp: () => ({+ getInstallationOctokit: async () => ({+ rest: { issues: { createComment: provider.comment } },+ }),+ }),+}));+vi.mock("../../apps/api/src/plugins/gitea/utils/gitea-api", () => ({+ createGiteaClient: () => ({ createIssueComment: provider.comment }),+}));+vi.mock("../../apps/api/src/plugins/gitlab/utils/gitlab-api", () => ({+ createGitlabClient: () => ({ createIssueNote: provider.comment }),+}));+vi.mock("../../apps/api/src/plugins/github/utils/labels", () => ({+ addLabelsToIssue: async (...args: unknown[]) => {+ const write = args.at(-1);+ const send = () => provider.labels();+ return typeof write === "function" ? write(send) : send();+ },+}));+vi.mock("../../apps/api/src/plugins/gitea/utils/labels", () => ({+ addLabelsToIssueGitea: async (...args: unknown[]) => {+ const write = args.at(-1);+ const send = () => provider.labels();+ return typeof write === "function" ? write(send) : send();+ },+}));+vi.mock("../../apps/api/src/plugins/gitlab/utils/labels", () => ({+ addLabelsToIssueGitlab: async (...args: unknown[]) => {+ const write = args.at(-1);+ const send = () => provider.labels();+ return typeof write === "function" ? write(send) : send();+ },+}));++beforeEach(async () => {+ await resetTestDatabase();+ vi.clearAllMocks();+ provider.labels.mockReset().mockResolvedValue(undefined);+ provider.comment.mockReset().mockResolvedValue({ id: 123 });+});++it.each(+ (["github", "gitea", "gitlab"] as const).flatMap((type) =>+ (+ [+ "excluded",+ "eligible",+ "before-write",+ "after-label",+ "failure",+ ] as const+ ).map((phase) => ({ type, phase })),+ ),+)(+ "guards $type issue-opened writes in the $phase case",+ async ({ type, phase }) => {+ const { workspace } = await createWorkspaceMember();+ const { project } = await createProjectFixture({+ workspaceId: workspace.id,+ });+ const [label] = await db+ .insert(schema.labelTable)+ .values({+ workspaceId: workspace.id,+ name: "export",+ color: "#123456",+ })+ .returning();+ const baseUrl =+ type === "github" ? "https://github.com" : `https://${type}.example`;+ const [integration] = await db+ .insert(schema.integrationTable)+ .values({+ projectId: project.id,+ type,+ isActive: true,+ config: JSON.stringify({+ baseUrl,+ repositoryOwner: "team",+ repositoryName: "repo",+ repositoryId: 1,+ installationId: 2,+ verifiedGithubAccountId: "3",+ verifiedByUserId: "test-user",+ accessToken: "test-only",+ projectPath: "team/repo",+ syncRules: {+ outgoing: { mode: "labels", match: "any", labels: [label!.id] },+ incoming: { mode: "all" },+ },+ }),+ })+ .returning();+ const removeQualifyingLabel = async () => {+ const task = await db.query.taskTable.findFirst({+ where: eq(schema.taskTable.projectId, project.id),+ });+ await db+ .delete(schema.labelTable)+ .where(+ and(+ eq(schema.labelTable.taskId, task!.id),+ eq(schema.labelTable.name, "export"),+ ),+ );+ };+ const publish = vi+ .spyOn(events, "publishEvent")+ .mockImplementation(async (name) => {+ if (name === "task.created" && phase === "before-write")+ await removeQualifyingLabel();+ });+ if (phase === "after-label")+ provider.labels.mockImplementationOnce(async () => {+ await vi.waitFor(async () => {+ const activity = await db.execute<{ count: number }>(sql`+ select count(*)::int as count from pg_stat_activity+ where datname = current_database() and state = 'idle in transaction'+ `);+ expect(activity.rows[0]!.count).toBe(0);+ });+ await removeQualifyingLabel();+ });+ if (phase === "failure")+ provider.comment.mockRejectedValueOnce(+ Object.assign(new Error("private-provider-write-response"), {+ request: {+ headers: { authorization: "private-provider-write-token" },+ },+ }),+ );+ const log = vi.spyOn(console, "error").mockImplementation(() => {});+ const labels =+ phase === "excluded"+ ? ["status:IN-PROGRESS"]+ : ["export", "status:IN-PROGRESS"];+ const issue = {+ number: 99,+ title: "Imported issue",+ body: "Imported body",+ html_url: `${baseUrl}/team/repo/issues/99`,+ labels,+ user: { login: "author" },+ };+ if (type === "github")+ await handleIssueOpened(+ {+ action: "opened",+ issue,+ installation: { id: 2 },+ repository: {+ id: 1,+ owner: { login: "team" },+ name: "repo",+ full_name: "team/repo",+ },+ },+ integration!.id,+ );+ else if (type === "gitea")+ await handleGiteaIssueOpened(+ {+ action: "opened",+ issue,+ repository: {+ owner: { login: "team" },+ name: "repo",+ html_url: `${baseUrl}/team/repo`,+ },+ },+ integration!.id,+ );+ else+ await handleGitlabIssueOpened(+ {+ object_attributes: {+ iid: 99,+ title: issue.title,+ description: issue.body,+ url: issue.html_url,+ },+ labels: labels.map((title) => ({ title })),+ project: {+ name: "repo",+ path_with_namespace: "team/repo",+ web_url: `${baseUrl}/team/repo`,+ },+ },+ integration!.id,+ );+ const tasks = await db.query.taskTable.findMany({+ where: eq(schema.taskTable.projectId, project.id),+ });+ expect(tasks).toHaveLength(1);+ expect(tasks[0]).toMatchObject({ title: issue.title });+ const link = await db.query.externalLinkTable.findFirst({+ where: eq(schema.externalLinkTable.integrationId, integration!.id),+ });+ expect(link).toMatchObject({ taskId: tasks[0]!.id, externalId: "99" });+ expect(+ publish.mock.calls.filter(([name]) => name === "task.created"),+ ).toHaveLength(1);+ const paused = ["excluded", "before-write", "after-label"].includes(phase);+ expect(JSON.parse(link!.metadata!).syncFilterPaused === true).toBe(paused);+ expect(provider.labels).toHaveBeenCalledTimes(+ ["excluded", "before-write"].includes(phase) ? 0 : 1,+ );+ expect(provider.comment).toHaveBeenCalledTimes(paused ? 0 : 1);+ expect(JSON.stringify(log.mock.calls)).not.toContain(+ "private-provider-write",+ );+ },+);diff --git a/tests/api/plugins/gitea/webhooks/issue-opened.test.ts b/tests/api/plugins/gitea/webhooks/issue-opened.test.tsindex 7bc07d358..c74391ea3 100644--- a/tests/api/plugins/gitea/webhooks/issue-opened.test.ts+++ b/tests/api/plugins/gitea/webhooks/issue-opened.test.ts@@ -46,6 +46,13 @@ vi.mock("../../../../../apps/api/src/plugins/sync/eligibility", () => ({canSyncTask: async () => true,}));+vi.mock(+ "../../../../../apps/api/src/plugins/sync/dispatch-issue-write",+ () => ({+ createIssueWrite: () => (send: () => Promise<unknown>) => send(),+ }),+);+vi.mock("../../../../../apps/api/src/database", () => ({ default: mocks.db }));vi.mock("../../../../../apps/api/src/events", () => ({