⚡ 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(gitea): verify saved repository connections (#1796)
Tin Severb3c219edfe53
diff --git a/apps/api/src/gitea-integration/controllers/resolve-verification-token.ts b/apps/api/src/gitea-integration/controllers/resolve-verification-token.tsnew file mode 100644index 000000000..9a6acd23a--- /dev/null+++ b/apps/api/src/gitea-integration/controllers/resolve-verification-token.ts@@ -0,0 +1,59 @@+import { and, eq } from "drizzle-orm";+import { HTTPException } from "hono/http-exception";+import db from "../../database";+import { integrationTable } from "../../database/schema";+import { normalizeGiteaBaseUrl } from "../../plugins/gitea/config";++export async function resolveVerificationToken(input: {+ projectId: string;+ baseUrl: string;+ accessToken?: string;+}) {+ let baseUrl: string;+ try {+ baseUrl = normalizeGiteaBaseUrl(input.baseUrl);+ } catch {+ throw new HTTPException(400, {+ message:+ "Enter a valid HTTP or HTTPS Gitea URL without credentials, a query, or a fragment.",+ });+ }+ if (input.accessToken?.trim()) return input.accessToken.trim();+ const integration = await db.query.integrationTable.findFirst({+ where: and(+ eq(integrationTable.projectId, input.projectId),+ eq(integrationTable.type, "gitea"),+ ),+ });+ let config: { accessToken?: unknown; baseUrl?: unknown } | null = null;+ try {+ config = integration ? JSON.parse(integration.config) : null;+ } catch {+ throw new HTTPException(400, {+ message: "Invalid saved Gitea configuration. Reconnect the integration.",+ });+ }+ let savedBaseUrl: string | undefined;+ if (typeof config?.baseUrl === "string") {+ try {+ savedBaseUrl = normalizeGiteaBaseUrl(config.baseUrl);+ } catch {+ throw new HTTPException(400, {+ message:+ "Invalid saved Gitea configuration. Reconnect the integration.",+ });+ }+ }+ // Never forward a stored credential to an edited destination.+ if (+ typeof config?.accessToken !== "string" ||+ !config.accessToken.trim() ||+ typeof config.baseUrl !== "string" ||+ savedBaseUrl !== baseUrl+ ) {+ throw new HTTPException(400, {+ message: "Enter a personal access token to verify this Gitea instance.",+ });+ }+ return String(config.accessToken);+}diff --git a/apps/api/src/gitea-integration/index.ts b/apps/api/src/gitea-integration/index.tsindex a2a0018a0..74bf98838 100644--- a/apps/api/src/gitea-integration/index.ts+++ b/apps/api/src/gitea-integration/index.ts@@ -24,6 +24,7 @@ import deleteGiteaIntegration from "./controllers/delete-gitea-integration";import getGiteaIntegration from "./controllers/get-gitea-integration";import { importGiteaIssues } from "./controllers/import-gitea-issues";import listGiteaRepositories from "./controllers/list-gitea-repositories";+import { resolveVerificationToken } from "./controllers/resolve-verification-token";import verifyGiteaAccess from "./controllers/verify-gitea-access";import {giteaDeleteResultSchema,@@ -76,7 +77,7 @@ const verifyRoute = createRoute({tags: ["Gitea"],summary: "Verify Gitea access",description:- "Check that the base URL is a Gitea instance and that the token can reach the repository with the permissions Kaneo needs. Always 200 -- problems are reported in the body.",+ "Check that the base URL is a Gitea instance and that the token can reach the repository with the permissions Kaneo needs. Repository permission failures are reported in the body; invalid credentials and upstream errors return an error status. Omit accessToken to use the saved token for the unchanged base URL.",middleware: manageAccess,request: {body: {@@ -86,6 +87,8 @@ const verifyRoute = createRoute({},responses: {200: jsonResponse("Verification result", giteaVerificationResultSchema),+ 401: errorResponse("Gitea rejected the token"),+ 500: errorResponse("Gitea verification failed"),400: errorResponse("Invalid body, or unknown project"),403: errorResponse("No workspace access, or missing workspace:manage_settings",@@ -223,7 +226,8 @@ const giteaIntegration = apiRouter<BaseVariables & { workspaceId: string }>()}).openapi(verifyRoute, async (c) => {const body = c.req.valid("json");- const result = await verifyGiteaAccess(body);+ const accessToken = await resolveVerificationToken(body);+ const result = await verifyGiteaAccess({ ...body, accessToken });return c.json(result, 200);}).openapi(getIntegrationRoute, async (c) => {diff --git a/apps/api/src/gitea-integration/schema.ts b/apps/api/src/gitea-integration/schema.tsindex fcbfa0cbc..b33bb7004 100644--- a/apps/api/src/gitea-integration/schema.ts+++ b/apps/api/src/gitea-integration/schema.ts@@ -10,6 +10,10 @@ export const listGiteaRepositoriesBody = z.object(giteaCredentials);export const verifyGiteaBody = z.object({...giteaCredentials,+ accessToken: z.string().min(1).optional().openapi({+ description:+ "Omit to verify with this project's saved token. The base URL must match the saved integration.",+ }),repositoryOwner: z.string().min(1),repositoryName: z.string().min(1),});diff --git a/apps/docs/openapi.json b/apps/docs/openapi.jsonindex f57f6b0c2..53277d51e 100644--- a/apps/docs/openapi.json+++ b/apps/docs/openapi.json@@ -13002,7 +13002,7 @@"Gitea"],"summary": "Verify Gitea access",- "description": "Check that the base URL is a Gitea instance and that the token can reach the repository with the permissions Kaneo needs. Always 200 -- problems are reported in the body.",+ "description": "Check that the base URL is a Gitea instance and that the token can reach the repository with the permissions Kaneo needs. Repository permission failures are reported in the body; invalid credentials and upstream errors return an error status. Omit accessToken to use the saved token for the unchanged base URL.","requestBody": {"required": true,"content": {@@ -13020,7 +13020,8 @@},"accessToken": {"type": "string",- "minLength": 1+ "minLength": 1,+ "description": "Omit to verify with this project's saved token. The base URL must match the saved integration."},"repositoryOwner": {"type": "string",@@ -13034,7 +13035,6 @@"required": ["projectId","baseUrl",- "accessToken","repositoryOwner","repositoryName"]@@ -13064,7 +13064,14 @@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Gitea rejected the token",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }},"403": {"description": "No workspace access, or missing workspace:manage_settings",@@ -13075,6 +13082,16 @@}}}+ },+ "500": {+ "description": "Gitea verification failed",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }}}}diff --git a/apps/web/src/components/project/gitea-integration-settings.test.tsx b/apps/web/src/components/project/gitea-integration-settings.test.tsxnew file mode 100644index 000000000..8c64bc65c--- /dev/null+++ b/apps/web/src/components/project/gitea-integration-settings.test.tsx@@ -0,0 +1,86 @@+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { GiteaIntegrationSettings } from "./gitea-integration-settings";++const { verify, success, failure, integration, translate } = vi.hoisted(() => ({+ verify: vi.fn(),+ success: vi.fn(),+ failure: vi.fn(),+ translate: (key: string) => key,+ integration: {+ baseUrl: "https://gitea.example",+ repositoryOwner: "owner",+ repositoryName: "repo",+ isActive: true,+ },+}));+vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: translate }) }));+vi.mock("@/hooks/queries/gitea-integration/use-get-gitea-integration", () => ({+ default: () => ({ data: integration }),+}));+vi.mock(+ "@/hooks/mutations/gitea-integration/use-create-gitea-integration",+ () => ({+ useVerifyGiteaAccess: () => ({ mutateAsync: verify, isPending: false }),+ useCreateGiteaIntegration: () => ({ mutateAsync: vi.fn() }),+ useDeleteGiteaIntegration: () => ({ mutateAsync: vi.fn() }),+ }),+);+vi.mock(+ "@/hooks/mutations/gitea-integration/use-update-gitea-integration",+ () => ({ useUpdateGiteaIntegration: () => ({ mutateAsync: vi.fn() }) }),+);+vi.mock("@/hooks/mutations/gitea-integration/use-import-gitea-issues", () => ({+ default: () => ({ mutateAsync: vi.fn() }),+}));+vi.mock("@/components/project/gitea-repository-browser-modal", () => ({+ GiteaRepositoryBrowserModal: () => null,+}));+vi.mock("@/lib/toast", () => ({+ toast: { success, error: failure, warning: vi.fn() },+}));+afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});+describe("saved Gitea verification", () => {+ it("verifies an existing integration without exposing or reentering its saved token", async () => {+ verify.mockResolvedValue({+ isInstalled: true,+ hasRequiredPermissions: true,+ });+ render(<GiteaIntegrationSettings projectId="project" />);+ const button = screen.getByRole("button", {+ name: "settings:giteaIntegration.verify",+ });+ await waitFor(() => expect(button).toBeEnabled());+ fireEvent.click(button);+ await waitFor(() => expect(success).toHaveBeenCalled());+ expect(verify).toHaveBeenCalledWith({+ projectId: "project",+ baseUrl: integration.baseUrl,+ repositoryOwner: "owner",+ repositoryName: "repo",+ accessToken: undefined,+ });+ });+ it("shows verification errors for a saved integration", async () => {+ verify.mockRejectedValue(new Error("Verification failed"));+ render(<GiteaIntegrationSettings projectId="project" />);+ const button = screen.getByRole("button", {+ name: "settings:giteaIntegration.verify",+ });+ await waitFor(() => expect(button).toBeEnabled());+ fireEvent.click(button);+ await waitFor(() =>+ expect(failure).toHaveBeenCalledWith("Verification failed"),+ );+ expect(success).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/components/project/gitea-integration-settings.tsx b/apps/web/src/components/project/gitea-integration-settings.tsxindex 7488c5858..1667bf9c9 100644--- a/apps/web/src/components/project/gitea-integration-settings.tsx+++ b/apps/web/src/components/project/gitea-integration-settings.tsx@@ -168,9 +168,6 @@ export function GiteaIntegrationSettings({ projectId }: { projectId: string }) {const runVerify = React.useCallback(async (data: GiteaIntegrationFormValues, showToast = true) => {const token = data.accessToken.trim();- if (!token && integration) {- return;- }if (!token && !integration) {if (showToast) {toast.error(t("settings:giteaIntegration.toast.tokenRequiredVerify"));@@ -183,7 +180,7 @@ export function GiteaIntegrationSettings({ projectId }: { projectId: string }) {const result = await verifyAccess({projectId,baseUrl: snapshot.baseUrl,- accessToken: snapshot.accessToken,+ accessToken: snapshot.accessToken || undefined,repositoryOwner: snapshot.repositoryOwner,repositoryName: snapshot.repositoryName,});@@ -302,7 +299,7 @@ export function GiteaIntegrationSettings({ projectId }: { projectId: string }) {const verification = await verifyAccess({projectId,baseUrl: snapshot.baseUrl,- accessToken: snapshot.accessToken,+ accessToken: snapshot.accessToken || undefined,repositoryOwner: snapshot.repositoryOwner,repositoryName: snapshot.repositoryName,});diff --git a/tests/api-integration/gitea-verification.test.ts b/tests/api-integration/gitea-verification.test.tsnew file mode 100644index 000000000..5fbdd042e--- /dev/null+++ b/tests/api-integration/gitea-verification.test.ts@@ -0,0 +1,139 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { resolveVerificationToken } from "../../apps/api/src/gitea-integration/controllers/resolve-verification-token";+import verifyGiteaAccess from "../../apps/api/src/gitea-integration/controllers/verify-gitea-access";+import { createApp } from "../../apps/api/src/index";+import { mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++vi.mock(+ "../../apps/api/src/gitea-integration/controllers/verify-gitea-access",+ () => ({+ default: vi.fn(async () => ({+ isInstalled: true,+ hasRequiredPermissions: true,+ repositoryExists: true,+ repositoryPrivate: false,+ missingPermissions: [],+ message: "Verified",+ failureReason: null,+ })),+ }),+);+beforeEach(async () => {+ await resetTestDatabase();+ vi.clearAllMocks();+});+async function fixture(baseUrl = "https://gitea.example") {+ const owner = await createWorkspaceMember({ role: "owner" });+ const { project } = await createProjectFixture({+ workspaceId: owner.workspace.id,+ });+ await db.insert(schema.integrationTable).values({+ projectId: project.id,+ type: "gitea",+ config: JSON.stringify({+ baseUrl,+ accessToken: "saved-secret",+ }),+ });+ mockAuthenticatedSession(owner.user);+ return { project };+}+function verify(projectId: string, baseUrl = "https://gitea.example") {+ return createApp().app.request("/api/gitea-integration/verify", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ projectId,+ baseUrl,+ repositoryOwner: "owner",+ repositoryName: "repo",+ }),+ });+}+describe("saved Gitea token verification route", () => {+ it("verifies the saved token without returning it", async () => {+ const { project } = await fixture();+ const response = await verify(project.id);+ expect(response.status).toBe(200);+ expect(verifyGiteaAccess).toHaveBeenCalledWith(+ expect.objectContaining({+ projectId: project.id,+ accessToken: "saved-secret",+ }),+ );+ expect(await response.text()).not.toContain("saved-secret");+ });+ it("rejects another destination before any outbound verification", async () => {+ const { project } = await fixture();+ expect((await verify(project.id, "https://other.example")).status).toBe(+ 400,+ );+ expect(verifyGiteaAccess).not.toHaveBeenCalled();+ });+ it.each([+ "ftp://gitea.example",+ "https://gitea.example?token=secret",+ "https://gitea.example#fragment",+ "https://user:[email protected]",+ ])(+ "rejects invalid submitted URL %s without verification",+ async (baseUrl) => {+ const { project } = await fixture();+ const response = await verify(project.id, baseUrl);+ expect(response.status).toBe(400);+ expect(await response.text()).not.toContain("secret");+ expect(verifyGiteaAccess).not.toHaveBeenCalled();+ },+ );+ it("reports malformed saved configuration without revealing it", async () => {+ const { project } = await fixture("https://user:[email protected]");+ const response = await verify(project.id);+ expect(response.status).toBe(400);+ const body = await response.text();+ expect(body).toContain("Reconnect the integration");+ expect(body).not.toContain("secret");+ expect(verifyGiteaAccess).not.toHaveBeenCalled();+ });+ it("requires workspace management permission to use stored credentials", async () => {+ const { project } = await fixture();+ const outsider = await createWorkspaceMember();+ mockAuthenticatedSession(outsider.user);+ expect((await verify(project.id)).status).toBe(403);+ expect(verifyGiteaAccess).not.toHaveBeenCalled();+ });+ it("uses a saved Gitea token only for its project and unchanged destination", async () => {+ const member = await createWorkspaceMember();+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ await db.insert(schema.integrationTable).values({+ projectId: project.id,+ type: "gitea",+ config: JSON.stringify({+ baseUrl: "https://gitea.example",+ accessToken: "stored-token",+ }),+ });+ const input = { projectId: project.id, baseUrl: "https://gitea.example/" };+ expect(await resolveVerificationToken(input)).toBe("stored-token");+ await expect(+ resolveVerificationToken({ ...input, baseUrl: "https://other.example" }),+ ).rejects.toMatchObject({ status: 400 });+ await expect(+ resolveVerificationToken({ ...input, projectId: "other-project" }),+ ).rejects.toMatchObject({ status: 400 });+ expect(+ await resolveVerificationToken({+ ...input,+ baseUrl: "https://other.example",+ accessToken: "new-token",+ }),+ ).toBe("new-token");+ });+});