Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

move app manifest creation to backend

Thiago Araujo da Silva7d50929744d8
diff --git a/backend/src/server/routes/v1/github-app-router.ts b/backend/src/server/routes/v1/github-app-router.ts
index 9cfb4c915b..4f5a458768 100644
--- a/backend/src/server/routes/v1/github-app-router.ts
+++ b/backend/src/server/routes/v1/github-app-router.ts
@@ -15,6 +15,65 @@ const SanitizedGitHubAppSchema = z.object({
});
export const registerGitHubAppRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "POST",
+ url: "/manifest/initiate",
+ config: {
+ rateLimit: writeLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ schema: {
+ body: z.object({
+ name: z.string().trim().min(1).max(64),
+ instanceType: z.enum(["cloud", "server"]).default("cloud"),
+ githubOrg: z.string().trim().optional(),
+ githubHost: z.string().trim().optional(),
+ installState: z.string().trim().min(1)
+ }),
+ response: {
+ 200: z.object({
+ state: z.string(),
+ manifest: z.record(z.unknown()),
+ githubActionUrl: z.string()
+ })
+ }
+ },
+ handler: async (req) => {
+ const result = await server.services.gitHubApp.initiateManifestCreation({
+ orgPermission: req.permission,
+ name: req.body.name,
+ instanceType: req.body.instanceType,
+ githubOrg: req.body.githubOrg,
+ githubHost: req.body.githubHost,
+ installState: req.body.installState
+ });
+
+ return result;
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/manifest/callback",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ querystring: z.object({
+ code: z.string().trim().min(1),
+ state: z.string().trim().min(1)
+ })
+ },
+ handler: async (req, reply) => {
+ const { redirectUrl } = await server.services.gitHubApp.handleManifestCallback({
+ code: req.query.code,
+ state: req.query.state
+ });
+
+ return reply.redirect(redirectUrl);
+ }
+ });
+
server.route({
method: "POST",
url: "/manifest/exchange",
diff --git a/backend/src/services/github-app/github-app-service.ts b/backend/src/services/github-app/github-app-service.ts
index 72b361233a..e8f34233a0 100644
--- a/backend/src/services/github-app/github-app-service.ts
+++ b/backend/src/services/github-app/github-app-service.ts
@@ -1,4 +1,5 @@
import { ForbiddenError } from "@casl/ability";
+import jwt from "jsonwebtoken";
import { OrganizationActionScope } from "@app/db/schemas";
import { OrgPermissionActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
@@ -6,6 +7,7 @@ import { TPermissionServiceFactory } from "@app/ee/services/permission/permissio
import { getConfig } from "@app/lib/config/env";
import { request } from "@app/lib/config/request";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
@@ -14,6 +16,8 @@ import {
TDeleteGitHubAppDTO,
TExchangeGitHubManifestCodeDTO,
TGitHubAppManifestResponse,
+ TGitHubManifestStatePayload,
+ TInitiateGitHubManifestDTO,
TListGitHubAppsDTO,
TRegisterGitHubAppDTO,
TSanitizedGitHubApp
@@ -238,8 +242,162 @@ export const gitHubAppServiceFactory = ({
};
};
+ const initiateManifestCreation = async ({
+ name,
+ instanceType,
+ githubOrg,
+ githubHost,
+ installState,
+ orgPermission
+ }: TInitiateGitHubManifestDTO) => {
+ const { permission } = await permissionService.getOrgPermission({
+ actor: orgPermission.type,
+ actorId: orgPermission.id,
+ orgId: orgPermission.orgId,
+ actorAuthMethod: orgPermission.authMethod,
+ actorOrgId: orgPermission.orgId,
+ scope: OrganizationActionScope.ParentOrganization
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Create, OrgPermissionSubjects.Settings);
+
+ const existing = await gitHubAppDAL.findOne({ orgId: orgPermission.orgId, name });
+ if (existing) {
+ throw new BadRequestError({
+ message: `A GitHub App with name "${name}" already exists in this organization.`
+ });
+ }
+
+ const { AUTH_SECRET, SITE_URL } = getConfig();
+
+ if (!SITE_URL) {
+ throw new BadRequestError({
+ message: "SITE_URL is not configured. Please set it in your environment to use GitHub App manifest creation."
+ });
+ }
+
+ const stateToken = jwt.sign(
+ {
+ orgId: orgPermission.orgId,
+ actorId: orgPermission.id,
+ actorType: orgPermission.type,
+ authMethod: orgPermission.authMethod,
+ name,
+ instanceType,
+ githubOrg: githubOrg ?? "",
+ githubHost: githubHost ?? "",
+ installState
+ } satisfies TGitHubManifestStatePayload,
+ AUTH_SECRET,
+ { expiresIn: "10m" }
+ );
+
+ const callbackUrl = `${SITE_URL}/api/v1/github-apps/manifest/callback`;
+ const oauthCallbackUrl = `${SITE_URL}/organization/app-connections/github/oauth/callback`;
+
+ const manifest = {
+ name,
+ url: SITE_URL,
+ redirect_url: callbackUrl,
+ callback_urls: [oauthCallbackUrl],
+ description: "Infisical GitHub App Connection",
+ public: false,
+ request_oauth_on_install: true,
+ default_permissions: {
+ metadata: "read",
+ secrets: "write",
+ environments: "write",
+ actions: "read",
+ organization_secrets: "write"
+ },
+ default_events: [] as string[]
+ };
+
+ const resolvedHost = githubHost ? `https://${githubHost}` : "https://github.com";
+ const githubActionUrl = githubOrg
+ ? `${resolvedHost}/organizations/${encodeURIComponent(githubOrg)}/settings/apps/new`
+ : `${resolvedHost}/settings/apps/new`;
+
+ return { state: stateToken, manifest, githubActionUrl };
+ };
+
+ const handleManifestCallback = async ({ code, state }: { code: string; state: string }) => {
+ const { AUTH_SECRET, SITE_URL } = getConfig();
+
+ if (!SITE_URL) {
+ throw new BadRequestError({ message: "SITE_URL is not configured." });
+ }
+
+ let statePayload: TGitHubManifestStatePayload;
+ try {
+ statePayload = jwt.verify(state, AUTH_SECRET) as TGitHubManifestStatePayload;
+ } catch {
+ throw new BadRequestError({ message: "Invalid or expired GitHub manifest state. Please try again." });
+ }
+
+ const { orgId, actorId, actorType, authMethod, name, instanceType, githubHost, installState } = statePayload;
+
+ const { permission } = await permissionService.getOrgPermission({
+ actor: actorType as ActorType,
+ actorId,
+ orgId,
+ actorAuthMethod: authMethod as ActorAuthMethod,
+ actorOrgId: orgId,
+ scope: OrganizationActionScope.ParentOrganization
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Create, OrgPermissionSubjects.Settings);
+
+ let manifestResponse: TGitHubAppManifestResponse;
+ try {
+ const resolvedApiHost = githubHost ? `https://${githubHost}/api/v3` : "https://api.github.com";
+ const { data } = await request.post<TGitHubAppManifestResponse>(
+ `${resolvedApiHost}/app-manifests/${encodeURIComponent(code)}/conversions`,
+ {},
+ {
+ headers: {
+ Accept: "application/vnd.github+json",
+ "X-GitHub-Api-Version": "2022-11-28"
+ }
+ }
+ );
+ manifestResponse = data;
+ } catch {
+ throw new BadRequestError({
+ message:
+ "Failed to exchange GitHub App manifest code. The code may be expired or invalid. Please try registering the GitHub App again."
+ });
+ }
+
+ const { encryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.Organization,
+ orgId
+ });
+
+ const created = await gitHubAppDAL.create({
+ orgId,
+ name,
+ encryptedAppId: encryptor({ plainText: Buffer.from(String(manifestResponse.id)) }).cipherTextBlob,
+ encryptedClientId: encryptor({ plainText: Buffer.from(manifestResponse.client_id) }).cipherTextBlob,
+ encryptedClientSecret: encryptor({ plainText: Buffer.from(manifestResponse.client_secret) }).cipherTextBlob,
+ encryptedPrivateKey: encryptor({ plainText: Buffer.from(manifestResponse.pem) }).cipherTextBlob,
+ encryptedSlug: encryptor({ plainText: Buffer.from(manifestResponse.slug) }).cipherTextBlob
+ });
+
+ const callbackUrl = new URL(`${SITE_URL}/organizations/${orgId}/app-connections/github/manifest/callback`);
+ callbackUrl.searchParams.set("gitHubAppId", created.id ?? "");
+ callbackUrl.searchParams.set("slug", manifestResponse.slug);
+ callbackUrl.searchParams.set("installState", installState);
+ callbackUrl.searchParams.set("instanceType", instanceType);
+ callbackUrl.searchParams.set("host", githubHost);
+
+ return { redirectUrl: callbackUrl.toString() };
+ };
+
return {
exchangeManifestCode,
+ initiateManifestCreation,
+ handleManifestCallback,
listGitHubApps,
deleteGitHubApp,
registerGitHubApp
diff --git a/backend/src/services/github-app/github-app-types.ts b/backend/src/services/github-app/github-app-types.ts
index 3d13e10fdd..ce9f9d66f4 100644
--- a/backend/src/services/github-app/github-app-types.ts
+++ b/backend/src/services/github-app/github-app-types.ts
@@ -6,6 +6,27 @@ export type TExchangeGitHubManifestCodeDTO = {
orgPermission: OrgServiceActor;
};
+export type TInitiateGitHubManifestDTO = {
+ name: string;
+ instanceType: "cloud" | "server";
+ githubOrg?: string;
+ githubHost?: string;
+ installState: string;
+ orgPermission: OrgServiceActor;
+};
+
+export type TGitHubManifestStatePayload = {
+ orgId: string;
+ actorId: string;
+ actorType: string;
+ authMethod: string | null;
+ name: string;
+ instanceType: "cloud" | "server";
+ githubOrg: string;
+ githubHost: string;
+ installState: string;
+};
+
export type TListGitHubAppsDTO = {
orgPermission: OrgServiceActor;
};
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx
index 486c5a358f..651144892e 100644
--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx
@@ -1,5 +1,3 @@
-import crypto from "crypto";
-
import { useEffect, useState } from "react";
import { Controller, FormProvider, useForm } from "react-hook-form";
import { faGithub } from "@fortawesome/free-brands-svg-icons";
@@ -30,6 +28,7 @@ import {
OrgGatewayPermissionActions,
OrgPermissionSubjects
} from "@app/context/OrgPermissionContext/types";
+import { apiRequest } from "@app/config/request";
import {
APP_CONNECTION_MAP,
getAppConnectionMethodDetails,
@@ -119,32 +118,6 @@ const buildDedicatedAppSlug = (connectionName: string) => {
return `infisical-${slug}`;
};
-const buildGitHubManifest = ({
- appName,
- redirectUrl,
- oauthCallbackUrl
-}: {
- appName: string;
- redirectUrl: string;
- oauthCallbackUrl: string;
-}) => ({
- name: appName,
- url: window.location.origin,
- redirect_url: redirectUrl,
- callback_urls: [oauthCallbackUrl],
- description: "Infisical GitHub App Connection",
- public: false,
- request_oauth_on_install: true,
- default_permissions: {
- metadata: "read",
- secrets: "write",
- environments: "write",
- actions: "read",
- organization_secrets: "write"
- },
- default_events: [] as string[]
-});
-
type AppSourceCardProps = {
title: string;
description: string;
@@ -238,8 +211,13 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Pro
}
setIsRedirecting(true);
- const state = crypto.randomBytes(16).toString("hex");
- localStorage.setItem("latestCSRFToken", state);
+
+ // generate install state here so the OAuth callback can validate it
+ const installState = Array.from(crypto.getRandomValues(new Uint8Array(16)))
+ .map((b) => b.toString(16).padStart(2, "0"))
+ .join("");
+
+ localStorage.setItem("latestCSRFToken", installState);
localStorage.setItem(
"githubConnectionFormData",
JSON.stringify({
@@ -259,40 +237,26 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Pro
switch (formData.method) {
case GitHubConnectionMethod.App: {
if (appSource === "dedicated") {
- const manifestState = crypto.randomBytes(16).toString("hex");
- const redirectUrl = `${window.location.origin}/organization/app-connections/github/manifest/callback`;
- const oauthCallbackUrl = `${window.location.origin}/organization/app-connections/github/oauth/callback`;
-
- const manifest = buildGitHubManifest({
- appName: dedicatedAppSlug,
- redirectUrl,
- oauthCallbackUrl
+ const { data } = await apiRequest.post<{
+ state: string;
+ manifest: Record<string, unknown>;
+ githubActionUrl: string;
+ }>("/api/v1/github-apps/manifest/initiate", {
+ name: dedicatedAppSlug,
+ instanceType: formData.credentials?.instanceType ?? "cloud",
+ githubOrg: dedicatedAppOrg.trim() || undefined,
+ githubHost: formData.credentials?.host || undefined,
+ installState
});
- localStorage.setItem("githubManifestCSRFToken", manifestState);
- localStorage.setItem(
- "githubManifestFormData",
- JSON.stringify({
- connectionFormDataKey: "githubConnectionFormData",
- instanceType: formData.credentials?.instanceType ?? "cloud",
- host: formData.credentials?.host ?? "",
- name: dedicatedAppSlug
- })
- );
-
- const orgSlug = dedicatedAppOrg.trim();
- const baseUrl = orgSlug
- ? `${githubHost}/organizations/${encodeURIComponent(orgSlug)}/settings/apps/new`
- : `${githubHost}/settings/apps/new`;
-
const formEl = document.createElement("form");
formEl.method = "post";
- formEl.action = `${baseUrl}?state=${encodeURIComponent(manifestState)}`;
+ formEl.action = `${data.githubActionUrl}?state=${encodeURIComponent(data.state)}`;
const input = document.createElement("input");
input.type = "hidden";
input.name = "manifest";
- input.value = JSON.stringify(manifest);
+ input.value = JSON.stringify(data.manifest);
formEl.appendChild(input);
document.body.appendChild(formEl);
@@ -301,13 +265,13 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Pro
}
window.location.assign(
- `${githubHost}/${formData.credentials?.instanceType === "server" ? "github-apps" : "apps"}/${appClientSlug}/installations/new?state=${state}`
+ `${githubHost}/${formData.credentials?.instanceType === "server" ? "github-apps" : "apps"}/${appClientSlug}/installations/new?state=${installState}`
);
break;
}
case GitHubConnectionMethod.OAuth:
window.location.assign(
- `${githubHost}/login/oauth/authorize?client_id=${oauthClientId}&response_type=code&scope=repo,admin:org&redirect_uri=${window.location.origin}/organization/app-connections/github/oauth/callback&state=${state}`
+ `${githubHost}/login/oauth/authorize?client_id=${oauthClientId}&response_type=code&scope=repo,admin:org&redirect_uri=${window.location.origin}/organization/app-connections/github/oauth/callback&state=${installState}`
);
break;
default:
diff --git a/frontend/src/pages/organization/AppConnections/GitHubManifestCallbackPage/GitHubManifestCallbackPage.tsx b/frontend/src/pages/organization/AppConnections/GitHubManifestCallbackPage/GitHubManifestCallbackPage.tsx
index 11a796403e..2881ee10f7 100644
--- a/frontend/src/pages/organization/AppConnections/GitHubManifestCallbackPage/GitHubManifestCallbackPage.tsx
+++ b/frontend/src/pages/organization/AppConnections/GitHubManifestCallbackPage/GitHubManifestCallbackPage.tsx
@@ -1,132 +1,65 @@
import { useEffect, useRef } from "react";
-import { useNavigate, useSearch } from "@tanstack/react-router";
+import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
import { createNotification } from "@app/components/notifications";
import { ContentLoader } from "@app/components/v2";
-import { apiRequest } from "@app/config/request";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useOrganization } from "@app/context";
-const GITHUB_MANIFEST_CSRF_KEY = "githubManifestCSRFToken";
-const GITHUB_MANIFEST_FORM_KEY = "githubManifestFormData";
const GITHUB_CONNECTION_FORM_KEY = "githubConnectionFormData";
-type ManifestFormStorage = {
- connectionFormDataKey: string;
- instanceType: "cloud" | "server";
- host: string;
- name: string;
-};
-
-type ExchangeResponse = {
- gitHubApp: {
- id: string;
- orgId: string;
- name: string;
- appId: string;
- slug: string;
- createdAt: string;
- updatedAt: string;
- };
-};
-
export const GitHubManifestCallbackPage = () => {
const navigate = useNavigate();
- const { currentOrg } = useOrganization();
+ const { orgId } = useParams({ strict: false }) as { orgId: string };
const search = useSearch({
from: ROUTE_PATHS.Organization.AppConnections.GitHubManifestCallbackPage.id
});
const hasRunRef = useRef(false);
useEffect(() => {
- if (!currentOrg || hasRunRef.current) return;
+ if (hasRunRef.current) return;
hasRunRef.current = true;
- const { code, state } = search;
+ const { gitHubAppId, slug, installState, instanceType, host } = search;
const fallback = () =>
navigate({
to: "/organizations/$orgId/app-connections",
- params: { orgId: currentOrg.id }
+ params: { orgId }
});
- if (!code || !state) {
+ if (!gitHubAppId || !slug || !installState) {
+ createNotification({ type: "error", text: "Invalid GitHub manifest callback parameters." });
fallback();
return;
}
- const storedState = localStorage.getItem(GITHUB_MANIFEST_CSRF_KEY);
- const storedFormDataRaw = localStorage.getItem(GITHUB_MANIFEST_FORM_KEY);
-
- localStorage.removeItem(GITHUB_MANIFEST_CSRF_KEY);
- localStorage.removeItem(GITHUB_MANIFEST_FORM_KEY);
-
- if (!storedState || storedState !== state || !storedFormDataRaw) {
- createNotification({ type: "error", text: "Invalid GitHub manifest callback state." });
+ const connectionFormRaw = localStorage.getItem(GITHUB_CONNECTION_FORM_KEY);
+ if (!connectionFormRaw) {
+ createNotification({ type: "error", text: "Missing GitHub connection form state." });
fallback();
return;
}
- let manifestData: ManifestFormStorage;
try {
- manifestData = JSON.parse(storedFormDataRaw) as ManifestFormStorage;
+ const connectionForm = JSON.parse(connectionFormRaw) as {
+ credentials?: Record<string, unknown>;
+ };
+ connectionForm.credentials = {
+ ...(connectionForm.credentials ?? {}),
+ gitHubAppId
+ };
+ localStorage.setItem(GITHUB_CONNECTION_FORM_KEY, JSON.stringify(connectionForm));
} catch {
- createNotification({ type: "error", text: "Corrupt GitHub manifest callback state." });
- fallback();
- return;
- }
-
- const installToken = localStorage.getItem("latestCSRFToken");
- const connectionFormRaw = localStorage.getItem(
- manifestData.connectionFormDataKey || GITHUB_CONNECTION_FORM_KEY
- );
-
- if (!installToken || !connectionFormRaw) {
- createNotification({ type: "error", text: "Missing GitHub connection form state." });
+ createNotification({ type: "error", text: "Corrupt GitHub connection form state." });
fallback();
return;
}
- (async () => {
- try {
- const { data } = await apiRequest.post<ExchangeResponse>(
- "/api/v1/github-apps/manifest/exchange",
- { name: manifestData.name, code }
- );
-
- const connectionForm = JSON.parse(connectionFormRaw) as {
- credentials?: Record<string, unknown>;
- };
- connectionForm.credentials = {
- ...(connectionForm.credentials ?? {}),
- gitHubAppId: data.gitHubApp.id
- };
- localStorage.setItem(
- manifestData.connectionFormDataKey || GITHUB_CONNECTION_FORM_KEY,
- JSON.stringify(connectionForm)
- );
-
- const githubHost =
- manifestData.host && manifestData.host.length > 0
- ? `https://${manifestData.host}`
- : "https://github.com";
-
- const appPathSegment = manifestData.instanceType === "server" ? "github-apps" : "apps";
+ const githubHost = host && host.length > 0 ? `https://${host}` : "https://github.com";
+ const appPathSegment = instanceType === "server" ? "github-apps" : "apps";
- window.location.assign(
- `${githubHost}/${appPathSegment}/${data.gitHubApp.slug}/installations/new?state=${installToken}`
- );
- } catch (err) {
- const message =
- (err as { response?: { data?: { message?: string } }; message?: string })?.response?.data
- ?.message ||
- (err as { message?: string })?.message ||
- "Failed to register GitHub App. Please try again.";
- createNotification({ type: "error", text: message });
- fallback();
- }
- })();
- }, [currentOrg?.id]);
+ window.location.assign(`${githubHost}/${appPathSegment}/${slug}/installations/new?state=${installState}`);
+ }, []);
return (
<div className="flex h-full w-full items-center justify-center">
diff --git a/frontend/src/pages/organization/AppConnections/GitHubManifestCallbackPage/route.tsx b/frontend/src/pages/organization/AppConnections/GitHubManifestCallbackPage/route.tsx
index c0b61d1342..1fb4ce4086 100644
--- a/frontend/src/pages/organization/AppConnections/GitHubManifestCallbackPage/route.tsx
+++ b/frontend/src/pages/organization/AppConnections/GitHubManifestCallbackPage/route.tsx
@@ -1,20 +1,20 @@
-import { createFileRoute, stripSearchParams } from "@tanstack/react-router";
+import { createFileRoute } from "@tanstack/react-router";
import { zodValidator } from "@tanstack/zod-adapter";
import { z } from "zod";
import { GitHubManifestCallbackPage } from "./GitHubManifestCallbackPage";
const GitHubManifestCallbackQueryParamsSchema = z.object({
- code: z.coerce.string().catch(""),
- state: z.string().catch("")
+ gitHubAppId: z.string().catch(""),
+ slug: z.string().catch(""),
+ installState: z.string().catch(""),
+ instanceType: z.enum(["cloud", "server"]).catch("cloud"),
+ host: z.string().catch("")
});
export const Route = createFileRoute(
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections/github/manifest/callback"
)({
component: GitHubManifestCallbackPage,
- validateSearch: zodValidator(GitHubManifestCallbackQueryParamsSchema),
- search: {
- middlewares: [stripSearchParams({ state: "" })]
- }
+ validateSearch: zodValidator(GitHubManifestCallbackQueryParamsSchema)
});