⚡ 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
feat: gitlab plugin tests
zaralX0b2871088f83
diff --git a/tests/api/plugins/gitlab-ssrf.test.ts b/tests/api/plugins/gitlab-ssrf.test.tsnew file mode 100644index 000000000..bf1c94c2b--- /dev/null+++ b/tests/api/plugins/gitlab-ssrf.test.ts@@ -0,0 +1,89 @@+import { describe, expect, it } from "vitest";+import {+ normalizeGitlabBaseUrl,+ normalizeProjectPath,+} from "../../../apps/api/src/plugins/gitlab/config";+import { gitlabFetch } from "../../../apps/api/src/plugins/gitlab/utils/gitlab-api";++describe("normalizeGitlabBaseUrl", () => {+ it("keeps a plain base URL usable", () => {+ expect(normalizeGitlabBaseUrl("https://gitlab.com/")).toBe(+ "https://gitlab.com",+ );+ expect(normalizeGitlabBaseUrl("https://git.example/gitlab/")).toBe(+ "https://git.example/gitlab",+ );+ });++ it("rejects a query or fragment that would hijack the request path", () => {+ expect(() => normalizeGitlabBaseUrl("http://example.com/?x=1")).toThrow(+ /query, fragment, or credentials/,+ );+ expect(() => normalizeGitlabBaseUrl("http://example.com/#frag")).toThrow(+ /query, fragment, or credentials/,+ );+ });++ it("strips a bare trailing # so the api path cannot be truncated", () => {+ expect(+ normalizeGitlabBaseUrl(+ "http://169.254.169.254/latest/meta-data/iam/security-credentials/role#",+ ),+ ).toBe(+ "http://169.254.169.254/latest/meta-data/iam/security-credentials/role",+ );+ });++ it("rejects embedded credentials and non-http schemes", () => {+ expect(() =>+ normalizeGitlabBaseUrl("http://user:[email protected]"),+ ).toThrow(/query, fragment, or credentials/);+ expect(() => normalizeGitlabBaseUrl("file:///etc/passwd")).toThrow(+ /must use http or https/,+ );+ });+});++describe("normalizeProjectPath", () => {+ it("keeps a nested group path and drops surrounding slashes", () => {+ expect(normalizeProjectPath("/acme/platform/web/")).toBe(+ "acme/platform/web",+ );+ });++ it("requires a namespace", () => {+ expect(() => normalizeProjectPath("web")).toThrow(+ /must include a namespace/,+ );+ });++ it("rejects relative segments that would escape the project path", () => {+ expect(() => normalizeProjectPath("acme/../admin")).toThrow(+ /relative segments/,+ );+ expect(() => normalizeProjectPath("acme/./web")).toThrow(+ /relative segments/,+ );+ });+});++describe("gitlabFetch destination guard", () => {+ const internalTargets = [+ "http://127.0.0.1:1337",+ "http://localhost:1337",+ "http://169.254.169.254",+ "http://10.0.0.5",+ "http://192.168.1.10",+ "http://172.16.0.1",+ "http://[::1]",+ "http://[::ffff:127.0.0.1]",+ ];++ for (const target of internalTargets) {+ it(`refuses to request ${target}`, async () => {+ await expect(+ gitlabFetch(target, "token", "private", "/user"),+ ).rejects.toThrow(/non-routable/);+ });+ }+});diff --git a/tests/api/plugins/gitlab/utils/link-sync.test.ts b/tests/api/plugins/gitlab/utils/link-sync.test.tsnew file mode 100644index 000000000..d8f378c57--- /dev/null+++ b/tests/api/plugins/gitlab/utils/link-sync.test.ts@@ -0,0 +1,119 @@+import { describe, expect, it } from "vitest";+import {+ isEchoOf,+ type LinkSyncState,+ parseLinkSyncMetadata,+ TEXT_ECHO_WINDOW_MS,+ withLastSync,+} from "../../../../../apps/api/src/plugins/gitlab/utils/link-sync";++function writtenAgo(+ ms: number,+ value: string,+ source = "kaneo",+): LinkSyncState {+ return {+ timestamp: new Date(Date.now() - ms).toISOString(),+ source,+ value,+ };+}++describe("isEchoOf", () => {+ it("treats the same value written by the other side as an echo", () => {+ expect(isEchoOf(writtenAgo(500, "Fix login"), "kaneo", "Fix login")).toBe(+ true,+ );+ });++ it("keeps a different value arriving right after a write", () => {+ expect(isEchoOf(writtenAgo(500, "Fix login"), "kaneo", "Fix logout")).toBe(+ false,+ );+ });++ it("keeps the value once the echo window has passed, so a revert still lands", () => {+ expect(+ isEchoOf(+ writtenAgo(TEXT_ECHO_WINDOW_MS + 1000, "Fix login"),+ "kaneo",+ "Fix login",+ ),+ ).toBe(false);+ });++ it("only matches the source it is asked about", () => {+ expect(+ isEchoOf(writtenAgo(500, "Fix login", "gitlab"), "kaneo", "Fix login"),+ ).toBe(false);+ });++ it("is not an echo when there is nothing recorded", () => {+ expect(isEchoOf(undefined, "kaneo", "Fix login")).toBe(false);+ });++ it("is not an echo when the recorded timestamp is unusable", () => {+ expect(+ isEchoOf(+ { timestamp: "not a date", source: "kaneo", value: "Fix login" },+ "kaneo",+ "Fix login",+ ),+ ).toBe(false);+ });+});++describe("parseLinkSyncMetadata", () => {+ const context = { externalLinkId: "link-1", field: "title" };++ it("returns an empty object for a row with no metadata", () => {+ expect(parseLinkSyncMetadata(null, context)).toEqual({});+ expect(parseLinkSyncMetadata(undefined, context)).toEqual({});+ });++ it("returns an empty object rather than throwing on unparseable metadata", () => {+ expect(parseLinkSyncMetadata("{not json", context)).toEqual({});+ });++ it("ignores metadata that parses to something other than an object", () => {+ expect(parseLinkSyncMetadata("null", context)).toEqual({});+ expect(parseLinkSyncMetadata('"kaneo"', context)).toEqual({});+ expect(parseLinkSyncMetadata("[1,2]", context)).toEqual({});+ });++ it("keeps the fields a previous write left behind", () => {+ expect(+ parseLinkSyncMetadata('{"state":"open","createdFrom":"kaneo"}', context),+ ).toEqual({ state: "open", createdFrom: "kaneo" });+ });+});++describe("withLastSync", () => {+ it("records the field without dropping the rest of the metadata", () => {+ const result = withLastSync(+ { state: "open", syncedNoteIds: [1] },+ "title",+ "kaneo",+ "Fix login",+ );++ expect(result.state).toBe("open");+ expect(result.syncedNoteIds).toEqual([1]);+ expect(result.lastSync?.title).toMatchObject({+ source: "kaneo",+ value: "Fix login",+ });+ });++ it("leaves the other field's state alone", () => {+ const result = withLastSync(+ { lastSync: { description: writtenAgo(0, "body") } },+ "title",+ "gitlab",+ "Fix login",+ );++ expect(result.lastSync?.description?.value).toBe("body");+ expect(result.lastSync?.title?.value).toBe("Fix login");+ });+});diff --git a/tests/api/plugins/gitlab/utils/verify-token.test.ts b/tests/api/plugins/gitlab/utils/verify-token.test.tsnew file mode 100644index 000000000..ec33a5d7b--- /dev/null+++ b/tests/api/plugins/gitlab/utils/verify-token.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from "vitest";+import { verifyGitlabToken } from "../../../../../apps/api/src/plugins/gitlab/utils/verify-token";++describe("verifyGitlabToken", () => {+ const secret = "3f7a9c2e5b1d8046af32be7190c4d5e6";++ it("accepts the exact token GitLab echoes back", () => {+ expect(verifyGitlabToken(secret, secret)).toBe(true);+ });++ it("rejects a different token of the same length", () => {+ const other = `${secret.slice(0, -1)}0`;+ expect(other).toHaveLength(secret.length);+ expect(verifyGitlabToken(secret, other)).toBe(false);+ });++ it("rejects a token that only shares a prefix", () => {+ expect(verifyGitlabToken(secret, secret.slice(0, 8))).toBe(false);+ });++ it("rejects a missing header", () => {+ expect(verifyGitlabToken(secret, undefined)).toBe(false);+ expect(verifyGitlabToken(secret, "")).toBe(false);+ });++ it("rejects every token when no secret is configured", () => {+ expect(verifyGitlabToken("", "anything")).toBe(false);+ });+});diff --git a/tests/api/plugins/gitlab/utils/webhook-project.test.ts b/tests/api/plugins/gitlab/utils/webhook-project.test.tsnew file mode 100644index 000000000..12c9e56d7--- /dev/null+++ b/tests/api/plugins/gitlab/utils/webhook-project.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from "vitest";+import { baseUrlFromProjectWebUrl } from "../../../../../apps/api/src/plugins/gitlab/utils/webhook-project";++describe("baseUrlFromProjectWebUrl", () => {+ it("returns the origin for a project at the instance root", () => {+ expect(+ baseUrlFromProjectWebUrl("https://gitlab.com/acme/web", "acme/web"),+ ).toBe("https://gitlab.com");+ });++ it("keeps the path prefix of an instance served under a subpath", () => {+ expect(+ baseUrlFromProjectWebUrl(+ "https://git.example.com/gitlab/acme/web",+ "acme/web",+ ),+ ).toBe("https://git.example.com/gitlab");+ });++ it("handles a project in nested groups", () => {+ expect(+ baseUrlFromProjectWebUrl(+ "https://gitlab.com/acme/platform/web",+ "acme/platform/web",+ ),+ ).toBe("https://gitlab.com");+ });++ it("returns empty when the web URL does not end in the project path", () => {+ expect(+ baseUrlFromProjectWebUrl("https://gitlab.com/acme/web", "other/repo"),+ ).toBe("");+ });++ it("returns empty for a URL it cannot parse", () => {+ expect(baseUrlFromProjectWebUrl("not a url", "acme/web")).toBe("");+ });+});diff --git a/tests/api/plugins/gitlab/webhooks/issue-opened.test.ts b/tests/api/plugins/gitlab/webhooks/issue-opened.test.tsnew file mode 100644index 000000000..d061f2171--- /dev/null+++ b/tests/api/plugins/gitlab/webhooks/issue-opened.test.ts@@ -0,0 +1,174 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { handleGitlabIssueOpened } from "../../../../../apps/api/src/plugins/gitlab/webhooks/issue-opened";++const mocks = vi.hoisted(() => {+ const insertedValues: Array<Record<string, unknown>> = [];++ return {+ insertedValues,+ findAllIntegrationsByGitlabProject: vi.fn(),+ findExternalLink: vi.fn(),+ createExternalLink: vi.fn(),+ claimTaskNumber: vi.fn(),+ resolveTargetStatus: vi.fn(),+ publishEvent: vi.fn(),+ columnFindFirst: vi.fn(),+ projectFindFirst: vi.fn(),+ createGitlabClient: vi.fn(),+ addLabelsToIssueGitlab: vi.fn(),+ db: {+ insert: () => ({+ values: (values: Record<string, unknown>) => {+ insertedValues.push(values);+ return { returning: async () => [{ id: "task-1", number: 7 }] };+ },+ }),+ query: {+ columnTable: {+ findFirst: (...args: unknown[]) => mocks.columnFindFirst(...args),+ },+ projectTable: {+ findFirst: (...args: unknown[]) => mocks.projectFindFirst(...args),+ },+ },+ },+ };+});++vi.mock("../../../../../apps/api/src/database", () => ({ default: mocks.db }));++vi.mock("../../../../../apps/api/src/events", () => ({+ publishEvent: (...args: unknown[]) => mocks.publishEvent(...args),+}));++vi.mock(+ "../../../../../apps/api/src/task/controllers/claim-task-numbers",+ () => ({+ claimTaskNumber: (...args: unknown[]) => mocks.claimTaskNumber(...args),+ }),+);++vi.mock(+ "../../../../../apps/api/src/plugins/github/services/link-manager",+ () => ({+ createExternalLink: (...args: unknown[]) =>+ mocks.createExternalLink(...args),+ findExternalLink: (...args: unknown[]) => mocks.findExternalLink(...args),+ }),+);++vi.mock(+ "../../../../../apps/api/src/plugins/gitlab/services/integration-lookup",+ () => ({+ findAllIntegrationsByGitlabProject: (...args: unknown[]) =>+ mocks.findAllIntegrationsByGitlabProject(...args),+ }),+);++vi.mock(+ "../../../../../apps/api/src/plugins/gitlab/utils/resolve-column",+ () => ({+ resolveTargetStatus: (...args: unknown[]) =>+ mocks.resolveTargetStatus(...args),+ }),+);++vi.mock("../../../../../apps/api/src/plugins/gitlab/utils/gitlab-api", () => ({+ createGitlabClient: (...args: unknown[]) => mocks.createGitlabClient(...args),+}));++vi.mock("../../../../../apps/api/src/plugins/gitlab/utils/labels", () => ({+ addLabelsToIssueGitlab: (...args: unknown[]) =>+ mocks.addLabelsToIssueGitlab(...args),+}));++const integration = {+ id: "integration-1",+ projectId: "project-1",+ isActive: true,+ type: "gitlab",+ config: JSON.stringify({+ baseUrl: "https://gitlab.com",+ projectPath: "usekaneo/kaneo",+ accessToken: "token",+ }),+};++// A webhook payload names a label in `title`, unlike the REST API, which returns+// issue labels as plain strings.+function issueOpenedPayload(labels: Array<{ title: string }>) {+ return {+ user: { username: "octocat" },+ object_attributes: {+ iid: 42,+ title: "Fix the login bug",+ description: "Steps to reproduce",+ url: "https://gitlab.com/usekaneo/kaneo/-/issues/42",+ action: "open",+ },+ labels,+ project: {+ name: "kaneo",+ web_url: "https://gitlab.com/usekaneo/kaneo",+ path_with_namespace: "usekaneo/kaneo",+ },+ };+}++beforeEach(() => {+ vi.clearAllMocks();+ mocks.insertedValues.length = 0;+ mocks.findAllIntegrationsByGitlabProject.mockResolvedValue([integration]);+ mocks.findExternalLink.mockResolvedValue(null);+ mocks.claimTaskNumber.mockResolvedValue(7);+ mocks.resolveTargetStatus.mockResolvedValue("to-do");+ mocks.columnFindFirst.mockResolvedValue(null);+ mocks.projectFindFirst.mockResolvedValue(null);+ mocks.createExternalLink.mockResolvedValue({ id: "link-1" });+ mocks.publishEvent.mockResolvedValue(undefined);+});++describe("handleGitlabIssueOpened", () => {+ it("persists a valid default priority when the issue has no priority: label", async () => {+ await handleGitlabIssueOpened(issueOpenedPayload([{ title: "type:bug" }]));++ expect(mocks.insertedValues).toHaveLength(1);+ expect(mocks.insertedValues[0].priority).toBe("low");+ });++ it("reads the priority label out of the webhook's label titles", async () => {+ await handleGitlabIssueOpened(+ issueOpenedPayload([{ title: "type:bug" }, { title: "priority:high" }]),+ );++ expect(mocks.insertedValues).toHaveLength(1);+ expect(mocks.insertedValues[0].priority).toBe("high");+ });++ it("records the issue link before publishing task.created", async () => {+ await handleGitlabIssueOpened(issueOpenedPayload([]));++ const linkOrder = mocks.createExternalLink.mock.invocationCallOrder[0];+ const eventOrder = mocks.publishEvent.mock.invocationCallOrder[0];+ expect(linkOrder).toBeLessThan(eventOrder);+ expect(mocks.createExternalLink).toHaveBeenCalledWith(+ expect.objectContaining({+ resourceType: "issue",+ externalId: "42",+ url: "https://gitlab.com/usekaneo/kaneo/-/issues/42",+ }),+ );+ });++ it("skips an issue that already has a task", async () => {+ mocks.findExternalLink.mockResolvedValue({+ id: "link-1",+ taskId: "task-1",+ });++ await handleGitlabIssueOpened(issueOpenedPayload([]));++ expect(mocks.insertedValues).toHaveLength(0);+ expect(mocks.claimTaskNumber).not.toHaveBeenCalled();+ });+});diff --git a/tests/api/plugins/gitlab/webhooks/issue-updated.test.ts b/tests/api/plugins/gitlab/webhooks/issue-updated.test.tsnew file mode 100644index 000000000..b7b9fdb04--- /dev/null+++ b/tests/api/plugins/gitlab/webhooks/issue-updated.test.ts@@ -0,0 +1,172 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { handleGitlabIssueUpdated } from "../../../../../apps/api/src/plugins/gitlab/webhooks/issue-updated";++const mocks = vi.hoisted(() => {+ const taskUpdates: Array<Record<string, unknown>> = [];++ return {+ taskUpdates,+ findAllIntegrationsByGitlabProject: vi.fn(),+ findExternalLink: vi.fn(),+ updateExternalLink: vi.fn(),+ updateTaskStatus: vi.fn(),+ publishEvent: vi.fn(),+ taskFindFirst: vi.fn(),+ db: {+ update: () => ({+ set: (values: Record<string, unknown>) => {+ taskUpdates.push(values);+ return { where: async () => undefined };+ },+ }),+ query: {+ taskTable: {+ findFirst: (...args: unknown[]) => mocks.taskFindFirst(...args),+ },+ },+ },+ };+});++vi.mock("../../../../../apps/api/src/database", () => ({ default: mocks.db }));++vi.mock("../../../../../apps/api/src/events", () => ({+ publishEvent: (...args: unknown[]) => mocks.publishEvent(...args),+}));++vi.mock(+ "../../../../../apps/api/src/plugins/github/services/link-manager",+ () => ({+ findExternalLink: (...args: unknown[]) => mocks.findExternalLink(...args),+ updateExternalLink: (...args: unknown[]) =>+ mocks.updateExternalLink(...args),+ }),+);++vi.mock(+ "../../../../../apps/api/src/plugins/github/services/task-service",+ () => ({+ updateTaskStatus: (...args: unknown[]) => mocks.updateTaskStatus(...args),+ }),+);++vi.mock(+ "../../../../../apps/api/src/plugins/gitlab/services/integration-lookup",+ () => ({+ findAllIntegrationsByGitlabProject: (...args: unknown[]) =>+ mocks.findAllIntegrationsByGitlabProject(...args),+ }),+);++const integration = {+ id: "integration-1",+ projectId: "project-1",+ isActive: true,+ type: "gitlab",+ config: JSON.stringify({+ baseUrl: "https://gitlab.com",+ projectPath: "usekaneo/kaneo",+ accessToken: "token",+ }),+};++function titleChangedPayload(title: string) {+ return {+ object_attributes: {+ iid: 42,+ title,+ description: "Steps to reproduce",+ url: "https://gitlab.com/usekaneo/kaneo/-/issues/42",+ action: "update",+ },+ changes: {+ title: { previous: "Old title", current: title },+ },+ project: {+ name: "kaneo",+ web_url: "https://gitlab.com/usekaneo/kaneo",+ path_with_namespace: "usekaneo/kaneo",+ },+ };+}++function linkWithLastTitleWrittenByKaneo(title: string) {+ return {+ id: "link-1",+ taskId: "task-1",+ metadata: JSON.stringify({+ state: "open",+ lastSync: {+ title: {+ // Just now, so a window-based guard would swallow both cases below.+ timestamp: new Date().toISOString(),+ source: "kaneo",+ value: title,+ },+ },+ }),+ };+}++beforeEach(() => {+ vi.clearAllMocks();+ mocks.taskUpdates.length = 0;+ mocks.findAllIntegrationsByGitlabProject.mockResolvedValue([integration]);+ mocks.taskFindFirst.mockResolvedValue({+ id: "task-1",+ projectId: "project-1",+ project: { workspaceId: "workspace-1" },+ });+ mocks.updateExternalLink.mockResolvedValue(undefined);+});++describe("handleGitlabIssueUpdated", () => {+ it("applies a title edit that arrives from GitLab", async () => {+ mocks.findExternalLink.mockResolvedValue({+ id: "link-1",+ taskId: "task-1",+ metadata: JSON.stringify({ state: "open" }),+ });++ await handleGitlabIssueUpdated(titleChangedPayload("Fix the login bug"));++ expect(mocks.taskUpdates).toEqual([{ title: "Fix the login bug" }]);+ });++ it("ignores the echo of a title Kaneo just wrote", async () => {+ mocks.findExternalLink.mockResolvedValue(+ linkWithLastTitleWrittenByKaneo("Written by Kaneo"),+ );++ await handleGitlabIssueUpdated(titleChangedPayload("Written by Kaneo"));++ expect(mocks.taskUpdates).toHaveLength(0);+ expect(mocks.updateExternalLink).not.toHaveBeenCalled();+ });++ it("keeps a different title edited right after Kaneo's own write", async () => {+ mocks.findExternalLink.mockResolvedValue(+ linkWithLastTitleWrittenByKaneo("Written by Kaneo"),+ );++ await handleGitlabIssueUpdated(titleChangedPayload("Edited in GitLab"));++ expect(mocks.taskUpdates).toEqual([{ title: "Edited in GitLab" }]);+ });++ it("does nothing when the update changed neither text nor labels", async () => {+ mocks.findExternalLink.mockResolvedValue({+ id: "link-1",+ taskId: "task-1",+ metadata: null,+ });++ await handleGitlabIssueUpdated({+ ...titleChangedPayload("Fix the login bug"),+ changes: {},+ });++ expect(mocks.findExternalLink).not.toHaveBeenCalled();+ expect(mocks.taskUpdates).toHaveLength(0);+ });+});