⚡ 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(api): block SSRF through the Gitea integration endpoints
Andrej26ae20fff617
diff --git a/apps/api/src/gitea-integration/index.ts b/apps/api/src/gitea-integration/index.tsindex 0a4e56bdb..50cb3a40c 100644--- a/apps/api/src/gitea-integration/index.ts+++ b/apps/api/src/gitea-integration/index.ts@@ -89,10 +89,13 @@ const giteaIntegration = new Hono<{validator("json",v.object({- baseUrl: v.pipe(v.string(), v.minLength(1)),+ projectId: v.pipe(v.string(), v.minLength(1)),+ baseUrl: v.pipe(v.string(), v.url()),accessToken: v.pipe(v.string(), v.minLength(1)),}),),+ workspaceAccess.fromProject("projectId"),+ requireWorkspacePermission({ workspace: ["manage_settings"] }),async (c) => {const { baseUrl, accessToken } = c.req.valid("json");const result = await listGiteaRepositories({ baseUrl, accessToken });@@ -119,12 +122,15 @@ const giteaIntegration = new Hono<{validator("json",v.object({- baseUrl: v.pipe(v.string(), v.minLength(1)),+ projectId: v.pipe(v.string(), v.minLength(1)),+ baseUrl: v.pipe(v.string(), v.url()),accessToken: v.pipe(v.string(), v.minLength(1)),repositoryOwner: v.pipe(v.string(), v.minLength(1)),repositoryName: v.pipe(v.string(), v.minLength(1)),}),),+ workspaceAccess.fromProject("projectId"),+ requireWorkspacePermission({ workspace: ["manage_settings"] }),async (c) => {const body = c.req.valid("json");const result = await verifyGiteaAccess(body);diff --git a/apps/api/src/plugins/generic-webhook/config.ts b/apps/api/src/plugins/generic-webhook/config.tsindex aac2c9b3a..e9bbbc848 100644--- a/apps/api/src/plugins/generic-webhook/config.ts+++ b/apps/api/src/plugins/generic-webhook/config.ts@@ -1,91 +1,10 @@-import { lookup } from "node:dns/promises";-import net from "node:net";import * as v from "valibot";--function isDisallowedIpv4(ip: string): boolean {- const parts = ip.split(".").map((part) => Number.parseInt(part, 10));- if (parts.length !== 4 || parts.some(Number.isNaN)) {- return true;- }-- const [a, b] = parts as [number, number, number, number];-- return (- a === 0 ||- a === 10 ||- a === 127 ||- (a === 169 && b === 254) ||- (a === 172 && b >= 16 && b <= 31) ||- (a === 192 && b === 168)- );-}--function isDisallowedIpv6(ip: string): boolean {- const normalized = ip.toLowerCase();-- return (- normalized === "::" ||- normalized === "::1" ||- normalized.startsWith("fe8") ||- normalized.startsWith("fe9") ||- normalized.startsWith("fea") ||- normalized.startsWith("feb") ||- normalized.startsWith("fc") ||- normalized.startsWith("fd")- );-}--function isDisallowedAddress(address: string): boolean {- if (address === "localhost") {- return true;- }-- const version = net.isIP(address);- if (version === 4) {- return isDisallowedIpv4(address);- }-- if (version === 6) {- return isDisallowedIpv6(address);- }-- return false;-}+import { assertPublicDestination } from "../../utils/assert-public-destination";export async function assertPublicWebhookDestination(webhookUrl: string,): Promise<void> {- const url = new URL(webhookUrl);-- if (!["http:", "https:"].includes(url.protocol)) {- throw new Error("Generic webhook URL must use http or https");- }-- // Self-hosters whose receivers (Gotify, ntfy, ...) live on a private network- // can opt out of the SSRF/private-address guard. Default off keeps protection on.- if (- process.env.KANEO_ALLOW_PRIVATE_WEBHOOK_DESTINATIONS === "true" ||- process.env.KANEO_ALLOW_PRIVATE_WEBHOOK_DESTINATIONS === "1"- ) {- return;- }-- if (isDisallowedAddress(url.hostname)) {- throw new Error(- "Generic webhook destination resolves to a non-routable address",- );- }-- const addresses = await lookup(url.hostname, { all: true, verbatim: true });- if (addresses.length === 0) {- throw new Error("Generic webhook destination could not be resolved");- }-- if (addresses.some((entry) => isDisallowedAddress(entry.address))) {- throw new Error(- "Generic webhook destination resolves to a non-routable address",- );- }+ await assertPublicDestination(webhookUrl, "Generic webhook");}export const genericWebhookEventKeys = [diff --git a/apps/api/src/plugins/gitea/config.ts b/apps/api/src/plugins/gitea/config.tsindex b0e4ff14d..fef1155b1 100644--- a/apps/api/src/plugins/gitea/config.ts+++ b/apps/api/src/plugins/gitea/config.ts@@ -54,7 +54,22 @@ export const defaultGiteaConfig: Partial<GiteaConfig> = {};export function normalizeGiteaBaseUrl(url: string): string {- return url.trim().replace(/\/+$/, "");+ const trimmed = url.trim().replace(/\/+$/, "");+ const parsed = new URL(trimmed);++ if (!["http:", "https:"].includes(parsed.protocol)) {+ throw new Error("Gitea base URL must use http or https");+ }++ // A query or fragment would swallow the appended /api/v1/... path and let a+ // caller aim the request at an arbitrary path on the target host.+ if (parsed.search || parsed.hash || parsed.username || parsed.password) {+ throw new Error(+ "Gitea base URL must not contain a query, fragment, or credentials",+ );+ }++ return `${parsed.origin}${parsed.pathname.replace(/\/+$/, "")}`;}export function getDefaultGiteaConfig(diff --git a/apps/api/src/plugins/gitea/utils/gitea-api.ts b/apps/api/src/plugins/gitea/utils/gitea-api.tsindex a38f72280..aba4712de 100644--- a/apps/api/src/plugins/gitea/utils/gitea-api.ts+++ b/apps/api/src/plugins/gitea/utils/gitea-api.ts@@ -1,3 +1,4 @@+import { assertPublicDestination } from "../../../utils/assert-public-destination";import type { GiteaConfig } from "../config";import { normalizeGiteaBaseUrl } from "../config";@@ -68,6 +69,8 @@ export async function giteaFetch<T>(const root = normalizeGiteaBaseUrl(baseUrl);const url = `${root}/api/v1${path.startsWith("/") ? path : `/${path}`}`;+ await assertPublicDestination(root, "Gitea");+const controller = new AbortController();let timedOut = false;const timeoutId = setTimeout(() => {@@ -88,12 +91,19 @@ export async function giteaFetch<T>(const res = await fetch(url, {...init,signal: controller.signal,+ // Following redirects would let a public host bounce the request to an+ // internal address after the destination check has already passed.+ redirect: "manual",headers: {...authHeaders(token),...init?.headers,},});+ if (res.status >= 300 && res.status < 400) {+ throw new GiteaApiError("Gitea request was redirected", res.status);+ }+const text = await res.text();clearTimeout(timeoutId);diff --git a/apps/api/src/utils/assert-public-destination.ts b/apps/api/src/utils/assert-public-destination.tsnew file mode 100644index 000000000..351eacc86--- /dev/null+++ b/apps/api/src/utils/assert-public-destination.ts@@ -0,0 +1,110 @@+import { lookup } from "node:dns/promises";+import net from "node:net";++function isDisallowedIpv4(ip: string): boolean {+ const parts = ip.split(".").map((part) => Number.parseInt(part, 10));+ if (parts.length !== 4 || parts.some(Number.isNaN)) {+ return true;+ }++ const [a, b] = parts as [number, number, number, number];++ return (+ a === 0 ||+ a === 10 ||+ a === 127 ||+ (a === 169 && b === 254) ||+ (a === 172 && b >= 16 && b <= 31) ||+ (a === 192 && b === 168)+ );+}++// ::ffff:127.0.0.1 is an IPv4 destination wearing an IPv6 shape, and the URL+// parser rewrites it to the hex form ::ffff:7f00:1, so both must be unwrapped.+function mappedIpv4(ip: string): string | null {+ const dotted = ip.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);+ if (dotted?.[1]) return dotted[1];++ const hex = ip.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);+ if (!hex?.[1] || !hex[2]) return null;++ const high = Number.parseInt(hex[1], 16);+ const low = Number.parseInt(hex[2], 16);+ return `${high >> 8}.${high & 0xff}.${low >> 8}.${low & 0xff}`;+}++function isDisallowedIpv6(ip: string): boolean {+ const normalized = ip.toLowerCase();++ const mapped = mappedIpv4(normalized);+ if (mapped) {+ return isDisallowedIpv4(mapped);+ }++ return (+ normalized === "::" ||+ normalized === "::1" ||+ normalized.startsWith("fe8") ||+ normalized.startsWith("fe9") ||+ normalized.startsWith("fea") ||+ normalized.startsWith("feb") ||+ normalized.startsWith("fc") ||+ normalized.startsWith("fd")+ );+}++export function isDisallowedAddress(address: string): boolean {+ // URL.hostname keeps the brackets on IPv6 literals, and net.isIP rejects+ // those, which would let http://[::1] slip past the checks below.+ const bare = address.replace(/^\[|\]$/g, "");++ if (bare === "localhost") {+ return true;+ }++ const version = net.isIP(bare);+ if (version === 4) {+ return isDisallowedIpv4(bare);+ }++ if (version === 6) {+ return isDisallowedIpv6(bare);+ }++ return false;+}++function privateDestinationsAllowed(): boolean {+ return (+ process.env.KANEO_ALLOW_PRIVATE_WEBHOOK_DESTINATIONS === "true" ||+ process.env.KANEO_ALLOW_PRIVATE_WEBHOOK_DESTINATIONS === "1"+ );+}++export async function assertPublicDestination(+ destinationUrl: string,+ label: string,+): Promise<void> {+ const url = new URL(destinationUrl);++ if (!["http:", "https:"].includes(url.protocol)) {+ throw new Error(`${label} URL must use http or https`);+ }++ if (privateDestinationsAllowed()) {+ return;+ }++ if (isDisallowedAddress(url.hostname)) {+ throw new Error(`${label} destination resolves to a non-routable address`);+ }++ const addresses = await lookup(url.hostname, { all: true, verbatim: true });+ if (addresses.length === 0) {+ throw new Error(`${label} destination could not be resolved`);+ }++ if (addresses.some((entry) => isDisallowedAddress(entry.address))) {+ throw new Error(`${label} destination resolves to a non-routable address`);+ }+}diff --git a/apps/web/src/components/project/gitea-integration-settings.tsx b/apps/web/src/components/project/gitea-integration-settings.tsxindex fb5651419..230303e20 100644--- a/apps/web/src/components/project/gitea-integration-settings.tsx+++ b/apps/web/src/components/project/gitea-integration-settings.tsx@@ -181,6 +181,7 @@ export function GiteaIntegrationSettings({ projectId }: { projectId: string }) {try {const snapshot = createVerificationSnapshot(data);const result = await verifyAccess({+ projectId,baseUrl: snapshot.baseUrl,accessToken: snapshot.accessToken,repositoryOwner: snapshot.repositoryOwner,@@ -210,7 +211,7 @@ export function GiteaIntegrationSettings({ projectId }: { projectId: string }) {setVerificationResult(null);}},- [verifyAccess, integration, t],+ [verifyAccess, integration, projectId, t],);const baseUrl = form.watch("baseUrl");@@ -295,6 +296,7 @@ export function GiteaIntegrationSettings({ projectId }: { projectId: string }) {if (data.accessToken.trim() && !hasMatchingVerification) {const verification = await verifyAccess({+ projectId,baseUrl: snapshot.baseUrl,accessToken: snapshot.accessToken,repositoryOwner: snapshot.repositoryOwner,@@ -881,6 +883,7 @@ export function GiteaIntegrationSettings({ projectId }: { projectId: string }) {<GiteaRepositoryBrowserModalopen={showRepositoryBrowser}+ projectId={projectId}onOpenChange={setShowRepositoryBrowser}onSelectRepository={handleRepositorySelect}selectedRepository={diff --git a/apps/web/src/components/project/gitea-repository-browser-modal.tsx b/apps/web/src/components/project/gitea-repository-browser-modal.tsxindex ff767ed92..002997e8d 100644--- a/apps/web/src/components/project/gitea-repository-browser-modal.tsx+++ b/apps/web/src/components/project/gitea-repository-browser-modal.tsx@@ -19,6 +19,7 @@ import { cn } from "@/lib/cn";type GiteaRepositoryBrowserModalProps = {open: boolean;+ projectId: string;onOpenChange: (open: boolean) => void;onSelectRepository: (repository: { owner: string; name: string }) => void;selectedRepository?: string;@@ -28,6 +29,7 @@ type GiteaRepositoryBrowserModalProps = {export function GiteaRepositoryBrowserModal({open,+ projectId,onOpenChange,onSelectRepository,selectedRepository,@@ -41,8 +43,8 @@ export function GiteaRepositoryBrowserModal({open && baseUrl.trim().length > 0 && accessToken.trim().length > 0;const { data, isLoading, error, refetch } = useQuery({- queryKey: ["gitea-repositories", baseUrl],- queryFn: () => listGiteaRepositories({ baseUrl, accessToken }),+ queryKey: ["gitea-repositories", projectId, baseUrl],+ queryFn: () => listGiteaRepositories({ projectId, baseUrl, accessToken }),enabled: canFetch,});diff --git a/tests/api/plugins/gitea-ssrf.test.ts b/tests/api/plugins/gitea-ssrf.test.tsnew file mode 100644index 000000000..d52ecd586--- /dev/null+++ b/tests/api/plugins/gitea-ssrf.test.ts@@ -0,0 +1,63 @@+import { describe, expect, it } from "vitest";+import { normalizeGiteaBaseUrl } from "../../../apps/api/src/plugins/gitea/config";+import { giteaFetch } from "../../../apps/api/src/plugins/gitea/utils/gitea-api";++describe("normalizeGiteaBaseUrl", () => {+ it("keeps a plain base URL usable", () => {+ expect(normalizeGiteaBaseUrl("https://gitea.example/")).toBe(+ "https://gitea.example",+ );+ expect(normalizeGiteaBaseUrl("https://gitea.example/sub/")).toBe(+ "https://gitea.example/sub",+ );+ });++ it("rejects a query or fragment that would hijack the request path", () => {+ expect(() => normalizeGiteaBaseUrl("http://example.com/?x=1")).toThrow(+ /query, fragment, or credentials/,+ );+ expect(() => normalizeGiteaBaseUrl("http://example.com/#frag")).toThrow(+ /query, fragment, or credentials/,+ );+ });++ it("strips a bare trailing # so the api path cannot be truncated", () => {+ expect(+ normalizeGiteaBaseUrl(+ "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(() => normalizeGiteaBaseUrl("http://user:[email protected]")).toThrow(+ /query, fragment, or credentials/,+ );+ expect(() => normalizeGiteaBaseUrl("file:///etc/passwd")).toThrow(+ /must use http or https/,+ );+ });+});++describe("giteaFetch 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(giteaFetch(target, "token", "/user")).rejects.toThrow(+ /non-routable/,+ );+ });+ }+});