diff --git a/apps/docs/openapi.json b/apps/docs/openapi.json index 292ee4f8..126422e7 100644 --- a/apps/docs/openapi.json +++ b/apps/docs/openapi.json @@ -4860,8 +4860,9 @@ }, "provider": { "enum": [ + "forgejo", "github", - "forgejo" + "gitea" ], "type": "string" }, @@ -4926,8 +4927,15 @@ "properties": { "provider": { "enum": [ - "github", "forgejo", + "github", + "gitlab", + "gitea", + "bitbucket", + "gitee", + "gitcafe", + "pushin", + "upstream", "generic" ], "type": "string" @@ -5085,8 +5093,15 @@ }, "provider": { "enum": [ - "github", "forgejo", + "github", + "gitlab", + "gitea", + "bitbucket", + "gitee", + "gitcafe", + "pushin", + "upstream", "generic" ], "type": "string" diff --git a/apps/web/src/lib/components/connections/connection-dialog.svelte b/apps/web/src/lib/components/connections/connection-dialog.svelte index 1ce59525..2ecdf2f1 100644 --- a/apps/web/src/lib/components/connections/connection-dialog.svelte +++ b/apps/web/src/lib/components/connections/connection-dialog.svelte @@ -28,10 +28,16 @@ SelectValue, } from "$lib/components/ui/select"; import { Textarea } from "$lib/components/ui/textarea"; - import { connectionFormParsers } from "$lib/params/git-query-params"; + import { + connectionFormParsers, + gitOAuthProviderKind, + gitProviderLabels, + gitProviders, + gitProviderServerUrls, + type GitProvider, + } from "$lib/params/git-query-params"; import { client, orpc, queryClient } from "$lib/api/orpc"; import { createQuery } from "@tanstack/svelte-query"; - import { Match } from "effect"; import { parseAsStringLiteral, useQueryStates, @@ -39,13 +45,10 @@ import { watch } from "runed"; import { onDestroy, untrack } from "svelte"; - type Provider = "forgejo" | "github" | "generic"; - - const providerOptions: { value: Provider; label: string }[] = [ - { value: "forgejo", label: "Forgejo" }, - { value: "github", label: "GitHub" }, - { value: "generic", label: "Generic Git server" }, - ]; + const providerOptions = gitProviders.map((value) => ({ + value, + label: gitProviderLabels[value], + })); type Repository = { url: string; @@ -58,7 +61,7 @@ type OAuthProvider = { id: string; name: string; - provider: Provider; + provider: GitProvider; serverUrl: string; }; @@ -73,7 +76,7 @@ connection: { id: string; name: string; - provider: Provider; + provider: GitProvider; serverUrl: string; authType: "token" | "oauth"; account: Account | null; @@ -118,17 +121,18 @@ { history: "replace", shallow: true, scroll: false }, ); - // A crafted URL must not enable OAuth for a generic server. + // Only forges with GitHub-style OAuth endpoints offer OAuth. + const oauthKind = $derived( + gitOAuthProviderKind(fields.provider.current), + ); + + // A crafted URL must not enable OAuth for a provider without it. const authMode = $derived( - fields.provider.current === "generic" - ? "token" - : fields.authMode.current, + oauthKind ? fields.authMode.current : "token", ); const providerLabel = $derived( - providerOptions.find( - (option) => option.value === fields.provider.current, - )?.label ?? fields.provider.current, + gitProviderLabels[fields.provider.current], ); const authOptions = $derived([ @@ -153,9 +157,9 @@ (option) => option.id === fields.oauthProviderId.current, )?.serverUrl ?? - (fields.provider.current === "github" - ? "https://github.com" - : (providers[0]?.serverUrl ?? "")) + gitProviderServerUrls[fields.provider.current] ?? + providers[0]?.serverUrl ?? + "" ); }), ); @@ -247,7 +251,7 @@ // Reject controls before URL parsing can discard them. if ( - fields.provider.current === "generic" || + !oauthKind || raw.length > 2048 || /[\s\p{Cc}\\]/u.test(raw) ) @@ -311,11 +315,7 @@ ); const appName = $derived( - fields.name.current.trim() || - `${Match.value(fields.provider.current).pipe( - Match.when("github", () => "GitHub"), - Match.orElse(() => "Forgejo"), - )} OAuth`, + fields.name.current.trim() || `${providerLabel} OAuth`, ); const setupReady = $derived( @@ -335,12 +335,13 @@ ); watch.pre( - () => [ - fields.provider.current, - authMode, - serverUrl, - fields.oauthProviderId.current, - ], + () => + [ + fields.provider.current, + authMode, + serverUrl, + fields.oauthProviderId.current, + ] as const, (current, previous) => { if ( !previous || @@ -366,10 +367,9 @@ if (selected) serverUrl = selected.serverUrl; else if (provider !== previousProvider) { serverUrl = - provider === "github" - ? "https://github.com" - : (matchingOAuthProviders[0]?.serverUrl ?? - ""); + gitProviderServerUrls[provider] ?? + matchingOAuthProviders[0]?.serverUrl ?? + ""; } } @@ -487,12 +487,7 @@ async function saveOAuthProvider(event: SubmitEvent) { event.preventDefault(); - if ( - busy || - authMode !== "oauth" || - fields.provider.current === "generic" || - !setupReady - ) + if (busy || authMode !== "oauth" || !oauthKind || !setupReady) return; pending = "app"; setupError = setupStatus = ""; @@ -503,7 +498,7 @@ await client.connections.createOAuthProvider({ organizationId: initialOrganizationId, name: appName, - provider: fields.provider.current, + provider: oauthKind, serverUrl: oauthServerUrl, clientId: clientId.trim(), clientSecret, @@ -807,15 +802,16 @@ next === fields.provider.current ) return; - const provider = next as Provider; + const provider = next as GitProvider; void fields.set({ provider, oauthProviderId: null, setupExpanded: null, - authMode: - provider === "generic" - ? "token" - : authMode, + authMode: gitOAuthProviderKind( + provider, + ) + ? authMode + : "token", }); }} > @@ -893,11 +889,9 @@ onValueChange={(next) => { if (!next) return; void fields.set({ - authMode: - fields.provider.current === - "generic" - ? "token" - : (next as "token" | "oauth"), + authMode: oauthKind + ? (next as "token" | "oauth") + : "token", setupExpanded: null, }); }} @@ -911,9 +905,7 @@ value={option.value} label={option.label} disabled={option.value === - "oauth" && - fields.provider.current === - "generic"} + "oauth" && !oauthKind} /> {/each} diff --git a/apps/web/src/lib/components/connections/connection-oauth-fields.svelte b/apps/web/src/lib/components/connections/connection-oauth-fields.svelte index eefd43c4..aa0a9391 100644 --- a/apps/web/src/lib/components/connections/connection-oauth-fields.svelte +++ b/apps/web/src/lib/components/connections/connection-oauth-fields.svelte @@ -1,4 +1,5 @@ {#if provider === "github"} @@ -15,23 +26,9 @@ aria-hidden="true" class="hidden size-4 shrink-0 dark:block" /> -{:else if provider === "gitea"} - -{:else if provider === "forgejo"} - {:else} = { - forgejo: "Forgejo", - github: "GitHub", - generic: "Generic Git", -}; +export { + gitOAuthProviderKind, + gitProviderLabels, + gitProviders, + gitProviderServerUrls, + type GitProvider, +} from "@clowder/api/git/providers"; // Only non-secret fields belong in the URL. export const connectionFormParsers = { diff --git a/apps/web/src/routes/(app)/git/+page.svelte b/apps/web/src/routes/(app)/git/+page.svelte index 16b46c8b..8adde892 100644 --- a/apps/web/src/routes/(app)/git/+page.svelte +++ b/apps/web/src/routes/(app)/git/+page.svelte @@ -27,6 +27,7 @@ import { connectionDialogParsers, connectionDialogUrl, + gitProviderLabels, } from "$lib/params/git-query-params"; import { orpc } from "$lib/api/orpc"; import ChevronRight from "phosphor-svelte/lib/CaretRightIcon"; @@ -101,12 +102,6 @@ !editingConnection, ); - const providerNames = { - github: "GitHub", - forgejo: "Forgejo", - generic: "Generic Git server", - }; - const oauthErrors = { configuration: "OAuth is not configured for this server. In Add connection (or Edit), select OAuth and set up a new OAuth application. An organization administrator can complete setup there, or use an access token instead.", @@ -332,7 +327,9 @@ - {providerNames[connection.provider]} · {connection.serverUrl} + {gitProviderLabels[ + connection.provider + ]} · {connection.serverUrl}

- {providerNames[connection.provider]} + {gitProviderLabels[connection.provider]}

diff --git a/apps/web/static/icons/bitbucket.svg b/apps/web/static/icons/bitbucket.svg new file mode 100644 index 00000000..20cfca48 --- /dev/null +++ b/apps/web/static/icons/bitbucket.svg @@ -0,0 +1 @@ +Bitbucket \ No newline at end of file diff --git a/apps/web/static/icons/gitcafe.svg b/apps/web/static/icons/gitcafe.svg new file mode 100644 index 00000000..0500427e --- /dev/null +++ b/apps/web/static/icons/gitcafe.svg @@ -0,0 +1,3 @@ + + + diff --git a/apps/web/static/icons/gitea.svg b/apps/web/static/icons/gitea.svg new file mode 100644 index 00000000..071e5149 --- /dev/null +++ b/apps/web/static/icons/gitea.svg @@ -0,0 +1 @@ +Gitea \ No newline at end of file diff --git a/apps/web/static/icons/gitee.svg b/apps/web/static/icons/gitee.svg new file mode 100644 index 00000000..67e0ecf9 --- /dev/null +++ b/apps/web/static/icons/gitee.svg @@ -0,0 +1 @@ +Gitee \ No newline at end of file diff --git a/apps/web/static/icons/gitlab.svg b/apps/web/static/icons/gitlab.svg new file mode 100644 index 00000000..509fa7f4 --- /dev/null +++ b/apps/web/static/icons/gitlab.svg @@ -0,0 +1 @@ +GitLab \ No newline at end of file diff --git a/apps/web/static/icons/pushin.png b/apps/web/static/icons/pushin.png new file mode 100644 index 00000000..972e1e9d Binary files /dev/null and b/apps/web/static/icons/pushin.png differ diff --git a/apps/web/static/icons/upstream.svg b/apps/web/static/icons/upstream.svg new file mode 100644 index 00000000..7d2d857a --- /dev/null +++ b/apps/web/static/icons/upstream.svg @@ -0,0 +1,27 @@ + + + + + diff --git a/packages/api/package.json b/packages/api/package.json index ff299fd5..4f6cb884 100644 --- a/packages/api/package.json +++ b/packages/api/package.json @@ -28,6 +28,7 @@ "@orpc/valibot": "catalog:", "drizzle-orm": "catalog:", "effect": "4.0.0-rc.116", + "forges": "0.4.1", "ofetch": "catalog:", "ssh2": "^1.17.0", "unstorage": "^1.17.5", diff --git a/packages/api/src/git/oauth.ts b/packages/api/src/git/oauth.ts index fb2c2eed..6aaacc3b 100644 --- a/packages/api/src/git/oauth.ts +++ b/packages/api/src/git/oauth.ts @@ -18,17 +18,19 @@ import type { Context } from "../context"; import type { GitCredentials } from "./index"; import { getGitAccount, + gitCloneUsername, gitProviderRequest, listGitRepositories, validateGitServerUrl, } from "./provider"; +import { gitOAuthProviderKinds } from "./providers"; import { encryptGitCredentials } from "./secrets"; import { decryptGitOAuthClientSecret, encryptGitOAuthClientSecret } from "./oauth-secrets"; const providerSchema = v.strictObject({ id: v.pipe(v.string(), v.regex(/^[a-zA-Z0-9_-]{1,64}$/)), name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100)), - provider: v.picklist(["github", "forgejo"]), + provider: v.picklist(gitOAuthProviderKinds), serverUrl: v.pipe(v.string(), v.minLength(1), v.maxLength(2048)), clientId: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(2048)), clientSecret: v.pipe(v.string(), v.minLength(1), v.maxLength(8192)), @@ -631,7 +633,7 @@ export async function exchangeGitOAuthCode( const credentials: GitCredentials = { ...token, - username: provider.provider === "github" ? "x-access-token" : account.login, + username: gitCloneUsername(provider.provider, account), }; return { provider, account, credentials }; diff --git a/packages/api/src/git/provider.ts b/packages/api/src/git/provider.ts index 66c932c2..555d0b2b 100644 --- a/packages/api/src/git/provider.ts +++ b/packages/api/src/git/provider.ts @@ -1,16 +1,31 @@ /* eslint-disable no-control-regex -- Reject control bytes at URL and credential boundaries. */ import { lookup } from "node:dns/promises"; -import { validateHeaderName, validateHeaderValue } from "node:http"; +import { type OutgoingHttpHeaders, validateHeaderName, validateHeaderValue } from "node:http"; import { Agent, request } from "node:https"; import { isIP } from "node:net"; import { ORPCError } from "@orpc/server"; import { Predicate } from "effect"; -import * as v from "valibot"; +import { + bitbucket, + forgejo, + type ForgeEvent, + type ForgeProvider, + gitcafe, + gitea, + gitee, + github, + gitlab, + pushin, + repoRef, + repoSlug, + upstream, +} from "forges"; import { isBlockedAddress, validateGitBranch, validateGitUrl } from "./index"; +import { type GitForge, type GitProvider, gitProviders } from "./providers"; -export type GitProvider = "github" | "forgejo" | "generic"; +export type { GitForge, GitProvider }; export type GitAccount = { id: string; login: string; name: string | null }; @@ -24,17 +39,8 @@ export type JsonValue = | JsonValue[] | { [key: string]: JsonValue }; -// The body comes from JSON.parse, so every value is already JSON; only the object shape is checked. -const jsonObject = v.pipe( - v.record( - v.string(), - v.custom(() => true), - ), - v.check((value) => !Array.isArray(value)), -); - type AccountInput = { - provider: Exclude; + provider: GitForge; serverUrl: string; token: string; }; @@ -49,6 +55,9 @@ const maxResponseBytes = 4 * 1024 * 1024; const maxRepositories = 1000; +// Requests one forge client may send; 1000 repositories take 11 pages of 100, with room for smaller pages. +const maxForgeRequests = 110; + function invalid(): never { throw new ORPCError("BAD_REQUEST", { message: "Invalid Git provider request" }); } @@ -57,6 +66,10 @@ function badResponse(): never { throw new ORPCError("BAD_GATEWAY", { message: "Invalid Git provider response" }); } +function requestFailed(): never { + throw new ORPCError("BAD_GATEWAY", { message: "Git provider request failed" }); +} + function parseUrl(value: string, ssh = false, query = false): URL { if ( !Predicate.isString(value) || @@ -100,8 +113,9 @@ function parseUrl(value: string, ssh = false, query = false): URL { } export function validateGitServerUrl(value: string, provider: GitProvider): string { - if (!["github", "forgejo", "generic"].includes(provider)) invalid(); + if (!gitProviders.includes(provider)) invalid(); const url = parseUrl(value, provider === "generic"); + const server = url.toString().replace(/\/$/u, ""); if ( provider === "github" && @@ -110,7 +124,10 @@ export function validateGitServerUrl(value: string, provider: GitProvider): stri ) invalid(); - return url.toString().replace(/\/$/u, ""); + // forges only speaks to Bitbucket Cloud. + if (provider === "bitbucket" && server !== "https://bitbucket.org") invalid(); + + return server; } async function pinnedAddress(host: string): Promise { @@ -139,43 +156,23 @@ async function pinnedAddress(host: string): Promise { } } -/** JSON-only transport for API calls and OAuth exchanges. Never follows redirects. */ -export async function gitProviderRequest( - url: string, - options: RequestOptions = {}, -): Promise { - const parsed = parseUrl(url, false, true); - const method = options.method ?? "GET"; - - if ( - !["GET", "POST"].includes(method) || - (options.body !== undefined && - (method !== "POST" || - !Predicate.isString(options.body) || - Buffer.byteLength(options.body) > 64 * 1024)) - ) - invalid(); - - const headers: Record = {}; - headers.accept = "application/json"; - headers["user-agent"] = "Clowder"; +function requestHeaders(input: RequestInit["headers"]): OutgoingHttpHeaders { + const headers: OutgoingHttpHeaders = { accept: "application/json", "user-agent": "Clowder" }; try { let size = 0; - for (const [key, value] of Object.entries(options.headers ?? {})) { - validateHeaderName(key); - validateHeaderValue(key, value); - const name = key.toLowerCase(); + for (const [name, value] of new Headers(input)) { + validateHeaderName(name); + validateHeaderValue(name, value); if ( - !Predicate.isString(value) || /^(?:host|connection|proxy-.*|content-length|transfer-encoding|upgrade|te|trailer)$/u.test( name, ) ) invalid(); - size += Buffer.byteLength(key) + Buffer.byteLength(value); + size += Buffer.byteLength(name) + Buffer.byteLength(value); if (size > 32 * 1024) invalid(); headers[name] = value; @@ -186,8 +183,45 @@ export async function gitProviderRequest( headers["accept-encoding"] = "identity"; - if (options.body !== undefined) - headers["content-length"] = String(Buffer.byteLength(options.body)); + return headers; +} + +/** + * The `fetch` every forges provider uses: HTTPS only, DNS pinned to a public address, no proxies, + * no redirects followed, bounded in time and size. Non-2xx responses pass through so forges can + * map them to its own errors. + */ +export async function gitProviderFetch(input: string, init: RequestInit = {}): Promise { + init.signal?.throwIfAborted(); + let parsed: URL; + + try { + parsed = new URL(input); + // Reuse the literal-host policy; the path is the forge's own API path. + parsed.hostname = new URL(validateGitUrl(`https://${parsed.host}/server`)).hostname; + } catch { + return invalid(); + } + + const method = (init.method ?? "GET").toUpperCase(); + + if ( + parsed.protocol !== "https:" || + parsed.username || + parsed.password || + !["GET", "HEAD", "POST"].includes(method) + ) + invalid(); + + const body = + init.body === undefined || init.body === null + ? undefined + : Buffer.from(await new Response(init.body).arrayBuffer()); + + if (body && (method !== "POST" || body.length > 64 * 1024)) invalid(); + const headers = requestHeaders(init.headers); + + if (body) headers["content-length"] = String(body.length); const host = parsed.hostname.replace(/^\[|\]$/gu, ""); const address = await pinnedAddress(host); // A fresh explicit agent avoids global-agent proxy settings and reused sockets. @@ -197,7 +231,7 @@ export async function gitProviderRequest( let timer: ReturnType | undefined; try { - return await new Promise((resolve, reject) => { + return await new Promise((resolve, reject) => { let settled = false; const fail = ( @@ -211,6 +245,15 @@ export async function gitProviderRequest( }; timer = setTimeout(() => fail("TIMEOUT"), 15_000); + + // Aborted during the DNS lookup: fail without sending the request. + if (init.signal?.aborted) { + fail("TIMEOUT"); + + return; + } + + init.signal?.addEventListener("abort", () => fail("TIMEOUT"), { once: true }); req = request( parsed, { @@ -241,13 +284,11 @@ export async function gitProviderRequest( return; } + const status = res.statusCode ?? 0; + if ( - !res.statusCode || - res.statusCode < 200 || - res.statusCode >= 300 || - !/^application\/(?:[\w.-]+\+)?json(?:\s*;|$)/iu.test( - res.headers["content-type"] ?? "", - ) || + status < 200 || + status > 599 || (res.headers["content-encoding"] && res.headers["content-encoding"] !== "identity") ) { @@ -267,27 +308,32 @@ export async function gitProviderRequest( }); res.on("end", () => { if (settled) return; + settled = true; + const responseHeaders = new Headers(); - try { - const text = new TextDecoder("utf-8", { fatal: true }).decode( - Buffer.concat(chunks), - ); - - const data: JsonValue = JSON.parse(text); - settled = true; - resolve(data); - } catch { - fail(); + for (const [name, value] of Object.entries(res.headers)) { + for (const item of [value ?? []].flat()) + responseHeaders.append(name, item); } + + const empty = method === "HEAD" || [204, 205, 304].includes(status); + + resolve( + new Response(empty ? null : Buffer.concat(chunks), { + status, + headers: responseHeaders, + }), + ); }); }, ); req.on("error", () => fail()); - req.end(options.body); + req.end(body); }); } catch (error) { if (error instanceof ORPCError) throw error; - throw new ORPCError("BAD_GATEWAY", { message: "Git provider request failed" }); + + return requestFailed(); } finally { clearTimeout(timer); response?.destroy(); @@ -296,37 +342,113 @@ export async function gitProviderRequest( } } -function accountConfig(input: AccountInput) { +/** JSON-only transport for OAuth exchanges. Never follows redirects. */ +export async function gitProviderRequest( + url: string, + options: RequestOptions = {}, +): Promise { + parseUrl(url, false, true); + const method = options.method ?? "GET"; + if ( - !["github", "forgejo"].includes(input.provider) || - !Predicate.isString(input.token) || - !/^[\x21-\x7e]{1,16384}$/u.test(input.token) + !["GET", "POST"].includes(method) || + (options.body !== undefined && (method !== "POST" || !Predicate.isString(options.body))) ) invalid(); - const server = validateGitServerUrl(input.serverUrl, input.provider); - const api = - input.provider === "github" - ? server === "https://github.com" - ? "https://api.github.com" - : `${server}/api/v3` - : `${server}/api/v1`; + const response = await gitProviderFetch(url, { + method, + headers: options.headers, + body: options.body, + }); + + if ( + !response.ok || + !/^application\/(?:[\w.-]+\+)?json(?:\s*;|$)/iu.test( + response.headers.get("content-type") ?? "", + ) + ) + requestFailed(); + + try { + const text = new TextDecoder("utf-8", { fatal: true }).decode(await response.arrayBuffer()); + + const data: JsonValue = JSON.parse(text); + + return data; + } catch { + return requestFailed(); + } +} + +type ForgeOptions = { + baseUrl: string; + auth: { type: "token"; token: string } | { type: "anonymous" }; + fetch: typeof gitProviderFetch; + userAgent: string; + timeout: number; + webhookSecret?: string; +}; - // Forgejo accepts Bearer for both personal access and OAuth tokens. - const headers = { authorization: `Bearer ${input.token}` }; +// `baseUrl` is the instance root for every forge but GitHub (its API root) and Bitbucket (Cloud only). +const forgeFactories: Record ForgeProvider> = { + forgejo, + github: (options) => + github({ + ...options, + baseUrl: + options.baseUrl === "https://github.com" + ? "https://api.github.com" + : `${options.baseUrl}/api/v3`, + }), + gitlab, + gitea, + bitbucket: ({ baseUrl: _cloud, ...options }) => bitbucket(options), + gitee, + gitcafe, + pushin, + upstream, +}; - return { server, api, headers }; +function forge(input: AccountInput, webhookSecret?: string): ForgeProvider { + if ( + !Object.hasOwn(forgeFactories, input.provider) || + (webhookSecret === undefined && + (!Predicate.isString(input.token) || !/^[\x21-\x7e]{1,16384}$/u.test(input.token))) + ) + invalid(); + let requests = 0; + + return forgeFactories[input.provider]({ + baseUrl: validateGitServerUrl(input.serverUrl, input.provider), + auth: + webhookSecret === undefined + ? { type: "token", token: input.token } + : { type: "anonymous" }, + // forges follows next-page links even from empty pages, so a hostile server could page forever. + fetch: (url, init) => + ++requests > maxForgeRequests ? badResponse() : gitProviderFetch(url, init), + userAgent: "Clowder", + timeout: 15_000, + webhookSecret, + }); } -function record(value: JsonValue) { - const result = v.safeParse(jsonObject, value); +/** Calls the forge, keeping our transport errors and reporting anything else as a bad response. */ +async function forgeCall(call: () => Promise): Promise { + try { + return await call(); + } catch (error) { + if (error instanceof ORPCError) throw error; - if (!result.success) badResponse(); + // forges wraps what our fetch throws in its own network error. + if (error instanceof Error && error.cause instanceof ORPCError) throw error.cause; - return result.output; + return requestFailed(); + } } -function safeText(value: unknown, limit: number): value is string { +function safeText(value: string | undefined, limit: number): value is string { return ( Predicate.isString(value) && value.length > 0 && @@ -337,97 +459,87 @@ function safeText(value: unknown, limit: number): value is string { } export async function getGitAccount(input: AccountInput): Promise { - const { api, headers } = accountConfig(input); - const data = record(await gitProviderRequest(`${api}/user`, { headers })); - - const id = - Predicate.isNumber(data.id) && Number.isSafeInteger(data.id) && data.id > 0 - ? String(data.id) - : data.id; + const user = await forgeCall(() => forge(input).users.me()); - if ( - !Predicate.isString(id) || - !/^[1-9][0-9]{0,63}$/u.test(id) || - !Predicate.isString(data.login) || - !/^[a-zA-Z0-9_][a-zA-Z0-9_.-]{0,254}$/u.test(data.login) - ) + // The login can become the HTTPS username, which git splits on ":". + if (!safeText(user.id, 256) || !safeText(user.login, 255) || user.login.includes(":")) badResponse(); - const name = input.provider === "github" ? data.name : data.full_name; - return { id, login: data.login, name: safeText(name, 256) ? name : null }; + return { id: user.id, login: user.login, name: safeText(user.name, 256) ? user.name : null }; +} + +/** The HTTPS username to clone with an account token; GitHub, GitLab and Bitbucket expect a fixed one. */ +export function gitCloneUsername(provider: GitForge, account: GitAccount): string { + if (provider === "github") return "x-access-token"; + + if (provider === "gitlab") return "oauth2"; + + if (provider === "bitbucket") return "x-token-auth"; + + return account.login; +} + +function repositoryName(name: string): boolean { + return safeText(name, 512) && /^[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)+$/u.test(name); } export async function listGitRepositories(input: AccountInput): Promise<{ repositories: GitDiscoveredRepository[]; truncated: boolean; }> { - const { server, api, headers } = accountConfig(input); - const base = new URL(server); + const provider = forge(input); + const base = new URL(validateGitServerUrl(input.serverUrl, input.provider)); const prefix = `${base.pathname.replace(/\/$/u, "")}/`; const repositories: GitDiscoveredRepository[] = []; const seen = new Set(); let count = 0; - // Do not trust Link URLs or assume the server honors the requested page size. - // The extra empty-page probe distinguishes exactly 1000 results from truncation. - for (let page = 1; page <= 100; page++) { - const url = new URL(`${api}/user/repos`); - url.searchParams.set("page", String(page)); - url.searchParams.set(input.provider === "github" ? "per_page" : "limit", "100"); + return forgeCall(async () => { + for await (const repo of provider.repos.list({ perPage: 100 })) { + if (count++ >= maxRepositories) return { repositories, truncated: true }; + const https = repo.cloneUrls?.https; - if (input.provider === "github") - url.searchParams.set("affiliation", "owner,collaborator,organization_member"); - const data = await gitProviderRequest(url.toString(), { headers }); + // Some forges list repositories without an HTTPS remote; those cannot be cloned with a token. + if (!https) continue; + let clone: URL; - if (!Array.isArray(data)) badResponse(); + try { + const remote = new URL(https); + // Bitbucket puts the account in its clone URL; credentials come from the connection instead. + remote.username = ""; + clone = parseUrl(remote.href); + } catch { + return badResponse(); + } - if (data.length === 0) return { repositories, truncated: false }; + const name = repoSlug(repo.ref); - for (const item of data) { - if (count++ >= maxRepositories) return { repositories, truncated: true }; - const repo = record(item); + // Credentials are scoped to the server, so a forged clone URL elsewhere is a bad response. + if ( + clone.search || + clone.origin !== base.origin || + !clone.pathname.startsWith(prefix) || + clone.pathname === prefix || + !repositoryName(name) + ) + badResponse(); + const normalized = validateGitUrl(clone.toString()); + let defaultBranch = ""; try { - if ( - !Predicate.isString(repo.clone_url) || - (repo.default_branch !== null && !Predicate.isString(repo.default_branch)) - ) - badResponse(); - const clone = parseUrl(repo.clone_url); - - if ( - clone.search || - repo.clone_url.includes("?") || - clone.origin !== base.origin || - !clone.pathname.startsWith(prefix) || - clone.pathname === prefix - ) - badResponse(); - const normalized = validateGitUrl(clone.toString()); - const name = repo.full_name ?? repo.name; - - if (!safeText(name, 512) || !/^[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)?$/u.test(name)) - badResponse(); - let defaultBranch = ""; - - try { - if (repo.default_branch !== null) - defaultBranch = validateGitBranch(repo.default_branch); - } catch { - // Unusable default-branch metadata must not hide accessible repositories. - } - - if (!seen.has(normalized)) { - seen.add(normalized); - repositories.push({ url: normalized, name, defaultBranch }); - } + if (repo.defaultBranch) defaultBranch = validateGitBranch(repo.defaultBranch); } catch { - badResponse(); + // Unusable default-branch metadata must not hide accessible repositories. + } + + if (!seen.has(normalized)) { + seen.add(normalized); + repositories.push({ url: normalized, name, defaultBranch }); } } - } - return { repositories, truncated: true }; + return { repositories, truncated: false }; + }); } /** Adds a push webhook to the repository unless one already points at `hookUrl`. */ @@ -437,42 +549,61 @@ export async function ensureGitWebhook( hookUrl: string, secret: string, ): Promise { - const { server, api, headers } = accountConfig(input); - const prefix = `${new URL(server).pathname.replace(/\/$/u, "")}/`; + const provider = forge(input); + + if (!provider.can("webhooks.create")) return; + const server = new URL(validateGitServerUrl(input.serverUrl, input.provider)); + const prefix = `${server.pathname.replace(/\/$/u, "")}/`; const repository = new URL(validateGitUrl(repositoryUrl)); const name = repository.pathname.slice(prefix.length).replace(/\.git$/u, ""); if ( - repository.origin !== new URL(server).origin || + repository.origin !== server.origin || !repository.pathname.startsWith(prefix) || - !/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/u.test(name) + !repositoryName(name) ) invalid(); - const hooks = `${api}/repos/${name}/hooks`; - - // GitHub caps a repository at 20 hooks, so one page of 100 sees all of them. - const existing = await gitProviderRequest( - `${hooks}?${input.provider === "github" ? "per_page" : "limit"}=100`, - { headers }, - ); - - if (!Array.isArray(existing)) badResponse(); + const ref = repoRef(provider, name); - const ours = v.object({ config: v.object({ url: v.literal(hookUrl) }) }); + await forgeCall(async () => { + // shortcut: an existing hook is not checked, so a rotated APP_SECRET leaves it failing; + // update it if secret rotation becomes common. + for await (const hook of provider.webhooks.list(ref)) if (hook.url === hookUrl) return; - // shortcut: an existing hook is not checked, so a rotated APP_SECRET leaves it failing; - // PATCH it if secret rotation becomes common. - if (existing.some((hook) => v.is(ours, hook))) return; - - await gitProviderRequest(hooks, { - method: "POST", - headers: { ...headers, "content-type": "application/json" }, - body: JSON.stringify({ - // GitHub requires "web"; Forgejo names its own hook type. - ...(input.provider === "github" ? { name: "web" } : { type: "forgejo" }), - config: { url: hookUrl, content_type: "json", secret }, + await provider.webhooks.create(ref, { + url: hookUrl, events: ["push"], + secret, + contentType: "json", active: true, - }), + }); }); } + +/** + * Verifies a webhook delivery against `secret` and returns its events, or `undefined` when the + * signature or token does not match. + */ +export async function readGitWebhook( + provider: GitForge, + serverUrl: string, + secret: string, + headers: Headers, + body: Uint8Array, +): Promise { + const forgeProvider = forge({ provider, serverUrl, token: "" }, secret); + + try { + // Forges without webhook verification throw rather than answer false. + if (!(await forgeProvider.webhooks.verify({ headers, body }))) return undefined; + } catch { + return undefined; + } + + try { + return await forgeProvider.webhooks.ingest({ headers, body }); + } catch { + // A verified delivery forges cannot translate, such as a ping, carries no push. + return []; + } +} diff --git a/packages/api/src/git/providers.ts b/packages/api/src/git/providers.ts new file mode 100644 index 00000000..c84710b0 --- /dev/null +++ b/packages/api/src/git/providers.ts @@ -0,0 +1,53 @@ +import type { GitProvider } from "@clowder/db/schema/index"; + +export type { GitProvider }; + +// Client-safe catalog of Git connection providers. Order drives the order of provider pickers. +// Every one but "generic" talks to its forge through the `forges` client (see provider.ts). +export const gitProviders = [ + "forgejo", + "github", + "gitlab", + "gitea", + "bitbucket", + "gitee", + "gitcafe", + "pushin", + "upstream", + "generic", +] as const satisfies readonly GitProvider[]; + +export type GitForge = Exclude; + +// Forgejo and Gitea share GitHub's /login/oauth endpoints; the other forges take access tokens only. +export const gitOAuthProviderKinds = ["forgejo", "github", "gitea"] as const satisfies GitForge[]; + +/** The provider as an OAuth kind, or `undefined` when it takes access tokens only. */ +export function gitOAuthProviderKind(provider: GitProvider) { + return gitOAuthProviderKinds.find((kind) => kind === provider); +} + +export const gitProviderLabels: Record = { + forgejo: "Forgejo", + github: "GitHub", + gitlab: "GitLab", + gitea: "Gitea", + bitbucket: "Bitbucket", + gitee: "Gitee", + gitcafe: "GitCafe", + pushin: "Pushin", + upstream: "Upstream", + generic: "Generic Git server", +}; + +// The public instance new connections start from; Forgejo and generic servers have none. +export const gitProviderServerUrls: Partial> = { + github: "https://github.com", + gitlab: "https://gitlab.com", + gitea: "https://gitea.com", + bitbucket: "https://bitbucket.org", + gitee: "https://gitee.com", + gitcafe: "https://git.cafe", + pushin: "https://pushin.eu", + upstream: "https://upstream.codes", +}; diff --git a/packages/api/src/git/webhook.ts b/packages/api/src/git/webhook.ts index 7b78b765..28bedfc6 100644 --- a/packages/api/src/git/webhook.ts +++ b/packages/api/src/git/webhook.ts @@ -7,6 +7,8 @@ import { eq } from "drizzle-orm"; import { createHmac, hkdfSync, timingSafeEqual } from "node:crypto"; import * as v from "valibot"; +import { readGitWebhook } from "./provider"; + // Derived from APP_SECRET, so there is nothing to store. Rotating APP_SECRET rotates every one. // The label keeps the legacy name on purpose: Git hosts hold the derived secret, so renaming it breaks every webhook. export function gitWebhookSecret(connectionId: string): string { @@ -28,8 +30,8 @@ export function gitWebhookUrl(connectionId: string): string { } /** - * A push webhook from Forgejo or GitHub. The payload is only a signed nudge: it queues a check of - * the connection's resources, which reads Git itself, so nothing in the body is trusted. + * A push webhook from any forge. The payload is only a signed nudge: it queues a check of the + * connection's resources, which reads Git itself, so nothing in the body is trusted. */ export async function receiveGitWebhook( db: Database, @@ -41,32 +43,50 @@ export async function receiveGitWebhook( return { status: 404, message: "Unknown webhook." }; const [connection] = await db - .select({ id: gitConnections.id }) + .select({ provider: gitConnections.provider, serverUrl: gitConnections.serverUrl }) .from(gitConnections) .where(eq(gitConnections.id, connectionId)); if (!connection) return { status: 404, message: "Unknown webhook." }; + const secret = gitWebhookSecret(connectionId); + + const push = + connection.provider === "generic" + ? signedPush(secret, headers, body) + : ( + await readGitWebhook( + connection.provider, + connection.serverUrl, + secret, + headers, + body, + ) + )?.some((event) => event.kind === "push"); + + if (push === undefined) return { status: 401, message: "Invalid webhook signature." }; + + if (!push) return { status: 200, message: "Webhook is active." }; + + await queueGitWatch(connectionId); + + return { status: 202, message: "Checking for changes." }; +} + +// A generic server's hook is set up by hand in GitHub's or Forgejo's format, which forges cannot pick for us. +function signedPush(secret: string, headers: Headers, body: Buffer): boolean | undefined { // GitHub prefixes its hex HMAC-SHA256 with "sha256="; Forgejo sends it bare. const signature = headers.get("x-hub-signature-256")?.replace(/^sha256=/u, "") ?? headers.get("x-forgejo-signature") ?? ""; - const expected = createHmac("sha256", gitWebhookSecret(connectionId)).update(body).digest(); + const expected = createHmac("sha256", secret).update(body).digest(); const received = Buffer.from(signature, "hex"); if (received.length !== expected.length || !timingSafeEqual(received, expected)) - return { status: 401, message: "Invalid webhook signature." }; + return undefined; // Forgejo also sends X-GitHub-Event, so this header covers both. - const event = headers.get("x-forgejo-event") ?? headers.get("x-github-event"); - - if (event === "ping") return { status: 200, message: "Webhook is active." }; - - if (event !== "push") return { status: 202, message: `Ignored ${event ?? "unknown"} event.` }; - - await queueGitWatch(connectionId); - - return { status: 202, message: "Checking for changes." }; + return (headers.get("x-forgejo-event") ?? headers.get("x-github-event")) === "push"; } diff --git a/packages/api/src/resources/deployment.ts b/packages/api/src/resources/deployment.ts index 7efb4200..4b010bbc 100644 --- a/packages/api/src/resources/deployment.ts +++ b/packages/api/src/resources/deployment.ts @@ -4,6 +4,7 @@ import { deploymentLogs, deployments, type DeploymentMetadata, + type GitProvider, resourceDeploymentInputs, resources, } from "@clowder/db/schema/index"; @@ -65,9 +66,7 @@ export async function readComposeConfigFiles( * `configFiles` comes from `readComposeConfigFiles` for Git-backed resources. */ // The deployment source for a Git connection's provider; a plain Git server is just "git". -export function deploymentSource( - provider: "github" | "forgejo" | "generic", -): DeploymentMetadata["source"] { +export function deploymentSource(provider: GitProvider): DeploymentMetadata["source"] { return provider === "generic" ? "git" : provider; } diff --git a/packages/api/src/routers/connections/index.ts b/packages/api/src/routers/connections/index.ts index cc5600d8..231821fc 100644 --- a/packages/api/src/routers/connections/index.ts +++ b/packages/api/src/routers/connections/index.ts @@ -19,11 +19,13 @@ import { import { ensureGitWebhook, getGitAccount, + gitCloneUsername, listGitRepositories, validateGitServerUrl, type GitProvider, type GitDiscoveredRepository, } from "../../git/provider"; +import { gitOAuthProviderKinds, gitProviders } from "../../git/providers"; import { createOrganizationGitOAuthProvider, getGitOAuthCallbackUrl, @@ -58,7 +60,7 @@ const repositoryInput = v.object({ const repositoriesInput = v.optional(v.pipe(v.array(repositoryInput), v.maxLength(100))); const accountInput = { - provider: v.picklist(["github", "forgejo", "generic"]), + provider: v.picklist(gitProviders), serverUrl: url, credentials: credentialsInput, repositories: repositoriesInput, @@ -174,7 +176,7 @@ async function verifyAccount(input: { truncated: result.truncated, credentials: { ...input.credentials, - username: input.provider === "github" ? "x-access-token" : account.login, + username: gitCloneUsername(input.provider, account), }, }; } @@ -376,7 +378,7 @@ export const connectionsRouter = { v.object({ organizationId: v.pipe(v.string(), v.minLength(1), v.maxLength(256)), name, - provider: v.picklist(["github", "forgejo"]), + provider: v.picklist(gitOAuthProviderKinds), serverUrl: v.pipe(v.string(), v.minLength(1), v.maxLength(2048)), clientId: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(2048)), clientSecret: v.pipe(v.string(), v.minLength(1), v.maxLength(8192)), diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.ts index 045aa507..b6c61240 100644 --- a/packages/db/src/schema/index.ts +++ b/packages/db/src/schema/index.ts @@ -161,6 +161,18 @@ export const projectFavorites = t.pgTable( ], ); +export type GitProvider = + | "forgejo" + | "github" + | "gitlab" + | "gitea" + | "bitbucket" + | "gitee" + | "gitcafe" + | "pushin" + | "upstream" + | "generic"; + export type GitAccount = { id: string; login: string; name: string | null }; export type GitKnownRepository = { url: string; name: string; defaultBranch: string }; @@ -174,7 +186,7 @@ export const gitOAuthProviders = t.pgTable( .notNull() .references(() => organization.id, { onDelete: "cascade" }), name: t.text("name").notNull(), - provider: t.text("provider").$type<"github" | "forgejo">().notNull(), + provider: t.text("provider").$type<"forgejo" | "github" | "gitea">().notNull(), serverUrl: t.text("server_url").notNull(), clientId: t.text("client_id").notNull(), encryptedClientSecret: t.text("encrypted_client_secret").notNull(), @@ -196,7 +208,7 @@ export const gitConnections = t.pgTable( .notNull() .references(() => organization.id, { onDelete: "cascade" }), name: t.text("name").notNull(), - provider: t.text("provider").$type<"github" | "forgejo" | "generic">().notNull(), + provider: t.text("provider").$type().notNull(), serverUrl: t.text("server_url").notNull(), authType: t.text("auth_type").$type<"token" | "oauth">().notNull().default("token"), account: t.jsonb("account").$type(), @@ -328,7 +340,7 @@ export type DeploymentStatus = "queued" | "running" | "ready" | "failed" | "canc // Where a resource deployment came from. "docker" is a Compose edited in Clowder, without Git. export type DeploymentMetadata = { - source: "forgejo" | "github" | "git" | "docker"; + source: Exclude | "git" | "docker"; trigger: "manual" | "webhook" | "poll"; commit?: { sha: string; message: string }; /** Each service's image with Variables and references resolved, saved by the worker. */ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 61bb96ca..df0599b6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -641,6 +641,9 @@ importers: effect: specifier: 4.0.0-rc.116 version: 4.0.0-rc.116 + forges: + specifier: 0.4.1 + version: 0.4.1 ofetch: specifier: 'catalog:' version: 1.5.1 @@ -5330,6 +5333,10 @@ packages: resolution: {integrity: sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==} engines: {node: '>=14'} + forges@0.4.1: + resolution: {integrity: sha512-FFvFo0gSAGpR/MWs/Rr7p0a4sp+quMk2Ysbe4sbCbS7FVtTjzyjWynMIVV43V/AlLbQRZmynnaiOHF/7yEM23w==} + engines: {node: '>=22.18'} + framer-motion@12.43.0: resolution: {integrity: sha512-1eaL3RvR/kAlbG7UYcpMptEyzPoENO0c6w7ZnB3/hh2vSAz/6uGAFn6fdoqTBguNstf3MsFhJHsD/0DHiclG+g==} peerDependencies: @@ -11152,6 +11159,8 @@ snapshots: cross-spawn: 7.0.6 signal-exit: 4.1.0 + forges@0.4.1: {} + framer-motion@12.43.0(react-dom@19.3.1(react@19.3.1))(react@19.3.1): dependencies: motion-dom: 12.43.0 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 15f2ac73..d5755fd4 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -28,6 +28,7 @@ minimumReleaseAgeExclude: - effect@4.0.0-rc.116 - skullet@0.0.3 - "@regular-ppl/hitbox@0.1.0" + - forges@0.4.1 overrides: vite@*: "catalog:" "@esbuild-kit/core-utils>esbuild": ^0.28.2 diff --git a/tests/api/git-provider.test.ts b/tests/api/git-provider.test.ts index 56790236..ef56bb64 100644 --- a/tests/api/git-provider.test.ts +++ b/tests/api/git-provider.test.ts @@ -5,6 +5,7 @@ import https, { Agent, type RequestOptions } from "node:https"; import type { IncomingMessage } from "node:http"; import { syncBuiltinESMExports } from "node:module"; import assert from "node:assert/strict"; +import { createHmac } from "node:crypto"; import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; @@ -23,7 +24,7 @@ const network = { calls: [] as { url: URL; options: RequestOptions; - body?: string; + body?: Buffer; destroy: ReturnType; }[], }; @@ -53,7 +54,7 @@ const fakeRequest = ( const req = Object.assign(new EventEmitter(), { destroy: vi.fn(), - end: (_body?: string) => {}, + end: (_body?: Buffer) => {}, }); req.end = (body) => { @@ -115,8 +116,10 @@ afterAll(() => { import { ensureGitWebhook, getGitAccount, + gitCloneUsername, gitProviderRequest, listGitRepositories, + readGitWebhook, validateGitServerUrl, } from "../../packages/api/src/git/provider"; import type { GitProvider } from "../../packages/api/src/git/provider"; @@ -135,8 +138,11 @@ const forgejo = { function repo(index: number, server = "https://github.com") { return { + id: index + 1, name: `repo-${index}`, full_name: `team/repo-${index}`, + owner: { login: "team", id: 1 }, + html_url: `${server}/team/repo-${index}`, clone_url: `${server}/team/repo-${index}.git`, default_branch: "release/stable", token: "must-not-return", @@ -161,8 +167,11 @@ describe("Git server validation", () => { expect(Object.keys(await import("../../packages/api/src/git/provider")).sort()).toEqual([ "ensureGitWebhook", "getGitAccount", + "gitCloneUsername", + "gitProviderFetch", "gitProviderRequest", "listGitRepositories", + "readGitWebhook", "validateGitServerUrl", ]); }); @@ -207,16 +216,21 @@ describe("Git server validation", () => { expect(() => validateGitServerUrl(url, "forgejo")).toThrow(); }); - it("does not accept GitLab or public GitHub API prefixes/alternate ports", () => { - // SAFETY: intentionally unsupported provider exercises runtime validation. - expect(() => validateGitServerUrl("https://gitlab.com", "gitlab" as GitProvider)).toThrow(); + it("does not accept public GitHub API prefixes/alternate ports or Bitbucket servers", () => { expect(() => validateGitServerUrl("https://github.com/api/v3", "github")).toThrow(); expect(() => validateGitServerUrl("https://github.com:8443", "github")).toThrow(); + expect(() => validateGitServerUrl("https://bitbucket.example.com", "bitbucket")).toThrow(); + expect(validateGitServerUrl("https://bitbucket.org/", "bitbucket")).toBe( + "https://bitbucket.org", + ); + expect(validateGitServerUrl("https://gitlab.example.com/", "gitlab")).toBe( + "https://gitlab.example.com", + ); }); - it("rejects Gitea as a runtime provider", () => { + it("rejects a forge forges does not cover as a runtime provider", () => { // SAFETY: intentionally unsupported provider exercises runtime validation. - expect(() => validateGitServerUrl(forgejo.serverUrl, "gitea" as GitProvider)).toThrow(); + expect(() => validateGitServerUrl(forgejo.serverUrl, "sourcehut" as GitProvider)).toThrow(); }); it("rejects long invalid paths without pathological regex backtracking", () => { @@ -291,7 +305,7 @@ describe("Pinned HTTPS JSON transport", () => { body, }), ).resolves.toEqual({ access_token: "new-token", token_type: "bearer" }); - expect(network.calls[0]!.body).toBe(body); + expect(String(network.calls[0]!.body)).toBe(body); expect(network.calls[0]!.options.headers).toMatchObject({ accept: "application/json", "content-type": "application/x-www-form-urlencoded", @@ -502,11 +516,16 @@ describe("Account discovery", () => { "https://github.com.example/forge/api/v3/user", ], [forgejo, "https://git.example.com/forge/api/v1/user"], + [ + { provider: "gitlab" as const, serverUrl: "https://gitlab.com", token: "secret-token" }, + "https://gitlab.com/api/v4/user", + ], ])("uses the correct /user endpoint for %j", async (input, endpoint) => { network.reply = () => ({ data: { id: 123, login: "alice.smith", + username: "alice.smith", name: "Alice", full_name: "Alice", token: "never-return", @@ -518,22 +537,26 @@ describe("Account discovery", () => { name: "Alice", }); expect(network.calls[0]!.url.toString()).toBe(endpoint); - expect(network.calls[0]!.options.headers).toMatchObject({ - authorization: "Bearer secret-token", - }); + expect(JSON.stringify(network.calls[0]!.options.headers)).toContain("secret-token"); }); - it.each([ - null, - {}, - { id: {}, login: "alice" }, - { id: Number.MAX_SAFE_INTEGER + 1, login: "alice" }, - { id: 1, login: "alice:password" }, - { id: 1, login: "-option" }, - { id: 1, login: "alice\n" }, - ])("rejects invalid account data %j", async (data) => { - network.reply = () => ({ data }); - await expect(getGitAccount(github)).rejects.toMatchObject({ code: "BAD_GATEWAY" }); + it.each([null, {}, { id: 1, login: "alice:password" }, { id: 1, login: "alice\n" }])( + "rejects invalid account data %j", + async (data) => { + network.reply = () => ({ data }); + await expect(getGitAccount(github)).rejects.toMatchObject({ code: "BAD_GATEWAY" }); + }, + ); + + // forges wraps transport errors, so these check the codes survive its client. + it("keeps the transport's error codes through forges", async () => { + network.addresses = [{ address: "127.0.0.1", family: 4 }]; + await expect(getGitAccount(github)).rejects.toMatchObject({ code: "BAD_REQUEST" }); + expect(request).not.toHaveBeenCalled(); + + network.addresses = [{ address: "93.184.216.34", family: 4 }]; + network.reply = () => ({ chunks: [Buffer.alloc(4 * 1024 * 1024 + 1)] }); + await expect(getGitAccount(github)).rejects.toMatchObject({ code: "PAYLOAD_TOO_LARGE" }); }); it("preserves string IDs and drops unsafe optional display names", async () => { @@ -555,19 +578,42 @@ describe("Account discovery", () => { await expect(getGitAccount({ ...github, token: "secret\n" })).rejects.toThrow(); expect(request).not.toHaveBeenCalled(); }); + + it("clones with each forge's token username", () => { + const account = { id: "1", login: "alice", name: null }; + expect(gitCloneUsername("github", account)).toBe("x-access-token"); + expect(gitCloneUsername("gitlab", account)).toBe("oauth2"); + expect(gitCloneUsername("bitbucket", account)).toBe("x-token-auth"); + expect(gitCloneUsername("forgejo", account)).toBe("alice"); + }); }); +// Answers /user/repos with `total` repositories, 100 per page, linking same-origin next pages. +function pagedRepos(total: number, server = "https://github.com") { + return (url: URL): Reply => { + const page = Number(url.searchParams.get("page") ?? "1"); + const start = (page - 1) * 100; + const next = new URL(url); + next.searchParams.set("page", String(page + 1)); + + return { + data: Array.from({ length: Math.max(0, Math.min(100, total - start)) }, (_, i) => + repo(start + i, server), + ), + headers: start + 100 < total ? { link: `<${next.href}>; rel="next"` } : {}, + }; + }; +} + describe("Repository discovery", () => { it("uses the Enterprise API while retaining the Enterprise clone origin", async () => { const server = "https://github.enterprise.example:8443"; - network.reply = (url) => ({ - data: url.searchParams.get("page") === "1" ? [repo(1, server)] : [], - }); + network.reply = pagedRepos(1, server); await expect(listGitRepositories({ ...github, serverUrl: server })).resolves.toEqual({ repositories: [ { - url: `${server}/team/repo-1.git`, - name: "team/repo-1", + url: `${server}/team/repo-0.git`, + name: "team/repo-0", defaultBranch: "release/stable", }, ], @@ -577,63 +623,54 @@ describe("Repository discovery", () => { expect(network.calls[0]!.url.pathname).toBe("/api/v3/user/repos"); }); - it("paginates all affiliations, ignores untrusted links and returns only sanitized fields", async () => { - network.reply = (url) => ({ - data: - Number(url.searchParams.get("page")) <= 2 - ? [repo(Number(url.searchParams.get("page")))] - : [], - headers: { link: '; rel="next"' }, - }); - await expect(listGitRepositories(github)).resolves.toEqual({ - repositories: [1, 2].map((id) => ({ - url: repo(id).clone_url, - name: repo(id).full_name, - defaultBranch: "release/stable", - })), - truncated: false, + it("follows same-origin pages and returns only sanitized fields", async () => { + network.reply = pagedRepos(150); + const result = await listGitRepositories(github); + expect(result.truncated).toBe(false); + expect(result.repositories).toHaveLength(150); + expect(result.repositories[0]).toEqual({ + url: repo(0).clone_url, + name: repo(0).full_name, + defaultBranch: "release/stable", }); - expect(network.calls).toHaveLength(3); - - for (const { url } of network.calls) { - expect(url.origin).toBe("https://api.github.com"); - expect(url.pathname).toBe("/user/repos"); - expect(url.searchParams.get("affiliation")).toBe( - "owner,collaborator,organization_member", - ); - expect(url.searchParams.get("per_page")).toBe("100"); - } + expect(network.calls).toHaveLength(2); + + for (const { url } of network.calls) expect(url.origin).toBe("https://api.github.com"); }); - it("keeps Forgejo path prefixes and continues server-capped short pages", async () => { + it("refuses pagination links to another origin without sending the token there", async () => { network.reply = (url) => ({ - data: - Number(url.searchParams.get("page")) <= 3 - ? [repo(Number(url.searchParams.get("page")), forgejo.serverUrl)] - : [], + data: url.host === "api.github.com" ? [repo(1)] : [], + headers: { link: '; rel="next"' }, }); + await expect(listGitRepositories(github)).rejects.toMatchObject({ code: "BAD_GATEWAY" }); + expect(network.calls.map(({ url }) => url.host)).toEqual(["api.github.com"]); + }); + + it("stops a server that links empty pages forever", async () => { + network.reply = (url) => { + const next = new URL(url); + next.searchParams.set("page", String(Number(url.searchParams.get("page") ?? "1") + 1)); + + return { data: [], headers: { link: `<${next.href}>; rel="next"` } }; + }; + + await expect(listGitRepositories(github)).rejects.toMatchObject({ code: "BAD_GATEWAY" }); + expect(network.calls).toHaveLength(110); + }); + + it("keeps Forgejo path prefixes", async () => { + network.reply = pagedRepos(3, forgejo.serverUrl); const result = await listGitRepositories(forgejo); expect(result.repositories).toHaveLength(3); expect(result.truncated).toBe(false); - expect(network.calls).toHaveLength(4); expect(network.calls[0]!.url.pathname).toBe("/forge/api/v1/user/repos"); - expect(network.calls[0]!.url.searchParams.get("limit")).toBe("100"); }); it.each([999, 1000, 1001, 1200])( "reports truncation correctly for %s repositories", async (total) => { - network.reply = (url) => { - const start = (Number(url.searchParams.get("page")) - 1) * 100; - - return { - data: Array.from( - { length: Math.max(0, Math.min(100, total - start)) }, - (_, i) => repo(start + i), - ), - }; - }; - + network.reply = pagedRepos(total); const result = await listGitRepositories(github); expect(result.repositories).toHaveLength(Math.min(total, 1000)); expect(result.truncated).toBe(total > 1000); @@ -641,14 +678,6 @@ describe("Repository discovery", () => { }, ); - it("bounds repeated pages without reporting a complete result", async () => { - network.reply = () => ({ data: [repo(1)] }); - const result = await listGitRepositories(github); - expect(result.repositories).toHaveLength(1); - expect(result.truncated).toBe(true); - expect(network.calls).toHaveLength(100); - }); - it.each([ "https://evil.example/forge/team/repo.git", "https://git.example.com/forge-other/team/repo.git", @@ -656,38 +685,38 @@ describe("Repository discovery", () => { "https://git.example.com:8443/forge/team/repo.git", "http://git.example.com/forge/team/repo.git", "ssh://git.example.com/forge/team/repo.git", - "https://secret@git.example.com/forge/team/repo.git", "https://git.example.com/forge/team/repo.git?token=secret", "https://git.example.com/forge/team/repo.git#fragment", "https://git.example.com/forge/../team/repo.git", "https://git.example.com/forge/%2e%2e/team/repo.git", "https://git.example.com/forge/", ])("rejects clone URL outside the configured trust boundary: %s", async (clone_url) => { - network.reply = () => ({ data: [{ ...repo(1), clone_url }] }); - await expect(listGitRepositories(forgejo)).rejects.toMatchObject({ - code: "BAD_GATEWAY", - message: "Invalid Git provider response", - }); + network.reply = () => ({ data: [{ ...repo(1, forgejo.serverUrl), clone_url }] }); + await expect(listGitRepositories(forgejo)).rejects.toMatchObject({ code: "BAD_GATEWAY" }); expect(request).toHaveBeenCalledTimes(1); }); + it("drops the account a forge puts in its clone URL", async () => { + network.reply = () => ({ + data: [ + { + ...repo(1, forgejo.serverUrl), + clone_url: "https://alice@git.example.com/forge/team/repo-1.git", + }, + ], + }); + await expect(listGitRepositories(forgejo)).resolves.toMatchObject({ + repositories: [{ url: "https://git.example.com/forge/team/repo-1.git" }], + }); + }); + it("does not allow api.github.com as a public GitHub clone origin", async () => { network.reply = () => ({ data: [repo(1, "https://api.github.com")] }); await expect(listGitRepositories(github)).rejects.toThrow(); }); - it.each([ - { message: "secret" }, - [null], - [{}], - [{ ...repo(1), default_branch: 123 }], - [{ ...repo(1), default_branch: false }], - [{ ...repo(1), default_branch: {} }], - [{ ...repo(1), default_branch: [] }], - [{ ...repo(1), default_branch: undefined }], - [{ ...repo(1), full_name: "unsafe\nname" }], - ])("rejects malformed repository data %j without silent omissions", async (data) => { - network.reply = () => ({ data }); + it("rejects a non-list repository response", async () => { + network.reply = () => ({ data: { message: "secret" } }); await expect(listGitRepositories(github)).rejects.toMatchObject({ code: "BAD_GATEWAY" }); }); @@ -697,18 +726,17 @@ describe("Repository discovery", () => { "HEAD", "", null, + 123, "unsafe\nbranch", "unsafe\0branch", "unsafe\x7fbranch", "a".repeat(256), - "\u00e9".repeat(128), + "é".repeat(128), "\ud800", ])( "retains repositories with unavailable or unsupported default branch %j", async (default_branch) => { - network.reply = (url) => ({ - data: url.searchParams.get("page") === "1" ? [{ ...repo(1), default_branch }] : [], - }); + network.reply = () => ({ data: [{ ...repo(1), default_branch }] }); await expect(listGitRepositories(github)).resolves.toEqual({ repositories: [ { url: repo(1).clone_url, name: repo(1).full_name, defaultBranch: "" }, @@ -718,36 +746,13 @@ describe("Repository discovery", () => { }, ); - it("lists empty and unsupported Forgejo repositories without blocking unrelated pages", async () => { - network.reply = (url) => { - const page = url.searchParams.get("page"); - - if (page === "1") - return { - data: ["refs/release", "", null].map((default_branch, i) => ({ - ...repo(i, forgejo.serverUrl), - default_branch, - })), - }; - - return { data: page === "2" ? [repo(3, forgejo.serverUrl)] : [] }; - }; - - await expect(listGitRepositories(forgejo)).resolves.toEqual({ - repositories: [0, 1, 2, 3].map((i) => ({ - url: repo(i, forgejo.serverUrl).clone_url, - name: repo(i).full_name, - defaultBranch: i === 3 ? "release/stable" : "", - })), - truncated: false, - }); - expect(network.calls).toHaveLength(3); - }); - it("does not return a partial success when a later page fails", async () => { network.reply = (url) => - Number(url.searchParams.get("page")) === 1 - ? { data: [repo(1)] } + url.searchParams.get("page") === null + ? { + data: [repo(1)], + headers: { link: '; rel="next"' }, + } : { status: 500, data: "secret" }; await expect(listGitRepositories(github)).rejects.toMatchObject({ code: "BAD_GATEWAY" }); }); @@ -756,15 +761,20 @@ describe("Repository discovery", () => { describe("Push webhooks", () => { const hookUrl = "https://clowder.example/git/webhook/connection"; - it("creates a GitHub hook for the repository", async () => { - network.reply = (url) => ({ data: url.search ? [] : { id: 1 } }); + it("creates a GitHub push hook for the repository", async () => { + network.reply = () => ({ + data: + network.calls.at(-1)?.options.method === "POST" + ? { id: 1, config: { url: hookUrl }, events: ["push"], active: true } + : [], + }); await ensureGitWebhook(github, "https://github.com/team/repo.git", hookUrl, "secret"); const [list, create] = network.calls; - expect(list!.url.href).toBe("https://api.github.com/repos/team/repo/hooks?per_page=100"); - expect(create!.url.href).toBe("https://api.github.com/repos/team/repo/hooks"); - expect(JSON.parse(create!.body!)).toEqual({ - name: "web", + expect(list!.url.pathname).toBe("/repos/team/repo/hooks"); + expect(create!.url.pathname).toBe("/repos/team/repo/hooks"); + expect(create!.options.method).toBe("POST"); + expect(JSON.parse(String(create!.body))).toMatchObject({ config: { url: hookUrl, content_type: "json", secret: "secret" }, events: ["push"], active: true, @@ -772,7 +782,17 @@ describe("Push webhooks", () => { }); it("skips a Forgejo repository that already has the hook", async () => { - network.reply = () => ({ data: [{ id: 1, config: { url: hookUrl } }] }); + network.reply = () => ({ + data: [ + { + id: 1, + type: "forgejo", + config: { url: hookUrl }, + events: ["push"], + active: true, + }, + ], + }); await ensureGitWebhook( forgejo, "https://git.example.com/forge/team/repo.git", @@ -780,8 +800,8 @@ describe("Push webhooks", () => { "secret", ); - expect(network.calls.map(({ url }) => url.href)).toEqual([ - "https://git.example.com/forge/api/v1/repos/team/repo/hooks?limit=100", + expect(network.calls.map(({ url }) => url.pathname)).toEqual([ + "/forge/api/v1/repos/team/repo/hooks", ]); }); @@ -792,3 +812,91 @@ describe("Push webhooks", () => { expect(network.calls).toEqual([]); }); }); + +describe("Webhook deliveries", () => { + const body = Buffer.from( + JSON.stringify({ + ref: "refs/heads/main", + before: "0".repeat(40), + after: "1".repeat(40), + commits: [], + repository: { + id: 1, + name: "repo", + full_name: "team/repo", + owner: { login: "team", id: 1 }, + }, + sender: { login: "alice", id: 2 }, + }), + ); + + it("accepts a signed GitHub push and reads it as a push", async () => { + const signature = createHmac("sha256", "secret").update(body).digest("hex"); + + const events = await readGitWebhook( + "github", + github.serverUrl, + "secret", + new Headers({ + "x-github-event": "push", + "x-github-delivery": "1", + "x-hub-signature-256": `sha256=${signature}`, + "content-type": "application/json", + }), + body, + ); + + expect(events?.some((event) => event.kind === "push")).toBe(true); + expect(request).not.toHaveBeenCalled(); + }); + + // Hooks created before forges sign with X-Forgejo-Signature; live installs depend on them. + it("accepts a signed push from an existing Forgejo hook", async () => { + const signature = createHmac("sha256", "secret").update(body).digest("hex"); + + const events = await readGitWebhook( + "forgejo", + forgejo.serverUrl, + "secret", + new Headers({ "x-forgejo-event": "push", "x-forgejo-signature": signature }), + body, + ); + + expect(events?.some((event) => event.kind === "push")).toBe(true); + }); + + it("rejects deliveries for a forge without webhook verification", async () => { + await expect( + readGitWebhook("pushin", "https://pushin.eu", "secret", new Headers(), body), + ).resolves.toBeUndefined(); + }); + + it("rejects a GitHub delivery with the wrong signature", async () => { + const signature = createHmac("sha256", "other").update(body).digest("hex"); + + await expect( + readGitWebhook( + "github", + github.serverUrl, + "secret", + new Headers({ + "x-github-event": "push", + "x-hub-signature-256": `sha256=${signature}`, + }), + body, + ), + ).resolves.toBeUndefined(); + }); + + it("checks GitLab's plain secret token", async () => { + const headers = (token: string) => + new Headers({ "x-gitlab-event": "Push Hook", "x-gitlab-token": token }); + + await expect( + readGitWebhook("gitlab", "https://gitlab.com", "secret", headers("wrong"), body), + ).resolves.toBeUndefined(); + await expect( + readGitWebhook("gitlab", "https://gitlab.com", "secret", headers("secret"), body), + ).resolves.toBeDefined(); + }); +}); diff --git a/tests/api/git-resources.test.ts b/tests/api/git-resources.test.ts index b5ad159c..410feee7 100644 --- a/tests/api/git-resources.test.ts +++ b/tests/api/git-resources.test.ts @@ -3197,7 +3197,7 @@ describe("Git connections/resources (PostgreSQL)", () => { it("answers pings and ignores other events", async () => { expect(await deliver("ping", "{}", sign("{}"))).toMatchObject({ status: 200 }); - expect(await deliver("issues", "{}", sign("{}"))).toMatchObject({ status: 202 }); + expect(await deliver("issues", "{}", sign("{}"))).toMatchObject({ status: 200 }); expect(queue).not.toHaveBeenCalled(); }); diff --git a/tests/web/git-query-params.test.ts b/tests/web/git-query-params.test.ts index 583ef3de..51ab6eba 100644 --- a/tests/web/git-query-params.test.ts +++ b/tests/web/git-query-params.test.ts @@ -4,12 +4,12 @@ import { connectionFormParsers, } from "../../apps/web/src/lib/params/git-query-params"; -it("accepts supported query providers and rejects Gitea", () => { - for (const provider of ["github", "forgejo", "generic"]) { +it("accepts supported query providers and rejects unsupported ones", () => { + for (const provider of ["github", "forgejo", "gitea", "gitlab", "generic"]) { expect(connectionFormParsers.provider.parse(provider)).toBe(provider); } - expect(connectionFormParsers.provider.parse("gitea")).toBeNull(); + expect(connectionFormParsers.provider.parse("sourcehut")).toBeNull(); }); it("preserves connection drafts on close/reopen and clears them on save or switching connections", () => {