Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
refactor duplicates
Thiago Araujo da Silva7ca78d54c9f1
diff --git a/backend/src/server/routes/v1/github-app-router.ts b/backend/src/server/routes/v1/github-app-router.tsindex 317b0fe61d..2d2e93d9c3 100644--- a/backend/src/server/routes/v1/github-app-router.ts+++ b/backend/src/server/routes/v1/github-app-router.ts@@ -3,19 +3,7 @@ import { z } from "zod";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode } from "@app/services/auth/auth-type";--const SanitizedGitHubAppSchema = z.object({- id: z.string().uuid().nullable(),- orgId: z.string().uuid(),- name: z.string(),- appId: z.string(),- slug: z.string(),- clientId: z.string().nullable(),- owner: z.string().nullable(),- connectionCount: z.number(),- createdAt: z.date().nullable(),- updatedAt: z.date().nullable()-});+import { SanitizedGitHubAppSchema } from "@app/services/github-app/github-app-types";export const registerGitHubAppRouter = async (server: FastifyZodProvider) => {server.route({diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.tsindex 2f19cb137a..a5b55ec194 100644--- a/backend/src/services/app-connection/app-connection-service.ts+++ b/backend/src/services/app-connection/app-connection-service.ts@@ -109,7 +109,11 @@ import { ValidateFlyioConnectionCredentialsSchema } from "./flyio";import { flyioConnectionService } from "./flyio/flyio-connection-service";import { ValidateGcpConnectionCredentialsSchema } from "./gcp";import { gcpConnectionService } from "./gcp/gcp-connection-service";-import { GitHubConnectionMethod, ValidateGitHubConnectionCredentialsSchema } from "./github";+import {+ GitHubConnectionMethod,+ releaseGitHubInstallationsTokenClaim,+ ValidateGitHubConnectionCredentialsSchema+} from "./github";import { githubConnectionService } from "./github/github-connection-service";import { ValidateGitHubRadarConnectionCredentialsSchema } from "./github-radar";import { githubRadarConnectionService } from "./github-radar/github-radar-connection-service";@@ -188,7 +192,7 @@ export type TAppConnectionServiceFactoryDep = {appConnectionCredentialRotationService: TAppConnectionCredentialRotationServiceFactory;identityUaDAL: Pick<TIdentityUaDALFactory, "findOne">;gitHubAppDAL: Pick<TGitHubAppDALFactory, "findOne" | "upsertConnectionLink">;- keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX">;+ keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX" | "deleteItem">;};export type TAppConnectionServiceFactory = ReturnType<typeof appConnectionServiceFactory>;@@ -635,6 +639,11 @@ export const appConnectionServiceFactory = ({configuration} as TAppConnection;} catch (err) {+ if (app === AppConnection.GitHub && method === GitHubConnectionMethod.App) {+ const installationsToken = (credentials as { installationsToken?: string } | undefined)?.installationsToken;+ if (installationsToken) await releaseGitHubInstallationsTokenClaim(installationsToken, keyStore);+ }+if (err instanceof DatabaseError && (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation) {throw new BadRequestError({ message: `An App Connection with the name "${params.name}" already exists` });}@@ -970,6 +979,11 @@ export const appConnectionServiceFactory = ({return await decryptAppConnection(updatedConnection, kmsService);} catch (err) {+ if (app === AppConnection.GitHub && method === GitHubConnectionMethod.App) {+ const installationsToken = (credentials as { installationsToken?: string } | undefined)?.installationsToken;+ if (installationsToken) await releaseGitHubInstallationsTokenClaim(installationsToken, keyStore);+ }+if (err instanceof DatabaseError && (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation) {throw new BadRequestError({ message: `An App Connection with the name "${params.name}" already exists` });}diff --git a/backend/src/services/app-connection/github/github-connection-fns.ts b/backend/src/services/app-connection/github/github-connection-fns.tsindex e598f4c9c0..94276e4f0b 100644--- a/backend/src/services/app-connection/github/github-connection-fns.ts+++ b/backend/src/services/app-connection/github/github-connection-fns.ts@@ -121,6 +121,21 @@ export const signGitHubAppInstallationsToken = (payload: TGitHubAppInstallationsreturn crypto.jwt().sign(payload, AUTH_SECRET, { expiresIn: GITHUB_APP_INSTALLATIONS_TOKEN_TTL });};+export const releaseGitHubInstallationsTokenClaim = async (+ installationsToken: string,+ keyStore: Pick<TKeyStoreFactory, "deleteItem">+) => {+ try {+ const { AUTH_SECRET } = getConfig();+ const payload = crypto.jwt().verify(installationsToken, AUTH_SECRET) as TGitHubAppInstallationsTokenPayload;+ if (payload.jti) {+ await keyStore.deleteItem(KeyStorePrefixes.UsedGitHubInstallationsToken(payload.jti));+ }+ } catch {+ // ignore — the claim will expire on its TTL if it can't be released here+ }+};+export const getGitHubConnectionListItem = () => {const { INF_APP_CONNECTION_GITHUB_OAUTH_CLIENT_ID, INF_APP_CONNECTION_GITHUB_APP_SLUG } = getConfig();@@ -655,6 +670,48 @@ export function isGithubErrorResponse(data: GithubTokenRespData): data is Githubreturn "error" in data;}+export type TGitHubUserInstallation = {+ id: number;+ app_id: number;+ account: {+ login: string;+ type: string;+ };+};++export const listGitHubUserInstallations = async (+ apiBaseUrl: string,+ accessToken: string,+ requestFn: (+ requestConfig: AxiosRequestConfig & { url: string }+ ) => Promise<AxiosResponse<{ installations: TGitHubUserInstallation[] }>>+): Promise<TGitHubUserInstallation[]> => {+ const installations: TGitHubUserInstallation[] = [];+ const MAX_PAGES = 100;+ for (let page = 1; page <= MAX_PAGES; page += 1) {+ // eslint-disable-next-line no-await-in-loop+ const { data } = await requestFn({+ url: `https://${apiBaseUrl}/user/installations`,+ method: "GET",+ params: { per_page: 100, page },+ headers: {+ Accept: "application/vnd.github+json",+ Authorization: `Bearer ${accessToken}`,+ "X-GitHub-Api-Version": "2022-11-28"+ }+ });++ const pageInstallations = data.installations ?? [];+ installations.push(...pageInstallations);++ if (pageInstallations.length < 100) {+ break;+ }+ }++ return installations;+};+export const validateGitHubConnectionCredentials = async (config: TGitHubConnectionConfig,gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,@@ -700,18 +757,6 @@ export const validateGitHubConnectionCredentials = async (});}- const ttlSeconds = Math.max(1, tokenPayload.exp - Math.floor(Date.now() / 1000));- const claimed = await deps.keyStore.setItemWithExpiryNX(- KeyStorePrefixes.UsedGitHubInstallationsToken(tokenPayload.jti),- ttlSeconds,- "1"- );- if (!claimed) {- throw new BadRequestError({- message: "This GitHub installation token has already been used. Please reconnect and try again."- });- }-if (tokenPayload.orgId !== config.orgId || (deps.actorId && tokenPayload.actorId !== deps.actorId)) {throw new ForbiddenRequestError({message: "GitHub installation token does not belong to this actor or organization."@@ -739,6 +784,18 @@ export const validateGitHubConnectionCredentials = async (assertPlatformGitHubHostAllowed(boundHost);+ const ttlSeconds = Math.max(1, tokenPayload.exp - Math.floor(Date.now() / 1000));+ const claimed = await deps.keyStore.setItemWithExpiryNX(+ KeyStorePrefixes.UsedGitHubInstallationsToken(tokenPayload.jti),+ ttlSeconds,+ "1"+ );+ if (!claimed) {+ throw new BadRequestError({+ message: "This GitHub installation token has already been used. Please reconnect and try again."+ });+ }+return {installationId: credentials.installationId,gitHubAppId: credentials.gitHubAppId ?? null,@@ -876,32 +933,16 @@ export const validateGitHubConnectionCredentials = async (throw new InternalServerError({ message: `Missing access token: ${tokenResp.data.error}` });}- const installationsResp = await requestWithGitHubGateway<{- installations: {- id: number;- account: {- login: string;- type: string;- id: number;- };- }[];- }>(- resolvedConfig,- gatewayService,- gatewayV2Service,- {- url: `https://${await getGitHubInstanceApiUrl(config)}/user/installations`,- headers: {- Accept: "application/json",- Authorization: `Bearer ${tokenResp.data.access_token}`,- "Accept-Encoding": "application/json"- }- },- gatewayConnectionDetails- );-// installations are scoped to this GitHub App since the token is a user-to-server token- const { installations } = installationsResp.data;+ const installations = await listGitHubUserInstallations(apiBaseUrl, tokenResp.data.access_token, (requestConfig) =>+ requestWithGitHubGateway<{ installations: TGitHubUserInstallation[] }>(+ resolvedConfig,+ gatewayService,+ gatewayV2Service,+ requestConfig,+ gatewayConnectionDetails+ )+ );// The installation is selected through GitHub's own install UI and returned to us as an explicit// installationId (required) — never auto-resolved from the user's accessible installations, so wediff --git a/backend/src/services/github-app/github-app-service.ts b/backend/src/services/github-app/github-app-service.tsindex a14d9bb523..74aa415e60 100644--- a/backend/src/services/github-app/github-app-service.ts+++ b/backend/src/services/github-app/github-app-service.ts@@ -1,6 +1,5 @@import { ForbiddenError } from "@casl/ability";import { AxiosError } from "axios";-import jwt from "jsonwebtoken";import { ActionProjectType, OrganizationActionScope } from "@app/db/schemas";import {@@ -26,6 +25,7 @@ import {getGitHubInstanceApiUrl,GithubTokenRespData,isGithubErrorResponse,+ listGitHubUserInstallations,resolveGitHubAppCredentials,signGitHubAppInstallationsToken,signGitHubAppJwt@@ -290,7 +290,7 @@ export const gitHubAppServiceFactory = ({});}- const stateToken = jwt.sign(+ const stateToken = crypto.jwt().sign({jti: crypto.nativeCrypto.randomUUID(),orgId: orgPermission.orgId,@@ -345,7 +345,7 @@ export const gitHubAppServiceFactory = ({let statePayload: TGitHubManifestStatePayload & { exp: number };try {- statePayload = jwt.verify(state, AUTH_SECRET) as TGitHubManifestStatePayload & { exp: number };+ statePayload = crypto.jwt().verify(state, AUTH_SECRET) as TGitHubManifestStatePayload & { exp: number };} catch {throw new BadRequestError({ message: "Invalid or expired GitHub manifest state. Please try again." });}@@ -396,9 +396,11 @@ export const gitHubAppServiceFactory = ({try {let manifestResponse: TGitHubAppManifestResponse;try {- const resolvedApiHost = githubHost ? `https://${githubHost}/api/v3` : "https://api.github.com";+ const apiBaseUrl = await getGitHubInstanceApiUrl({+ credentials: { host: githubHost || undefined, instanceType }+ });const { data } = await safeRequest.post<TGitHubAppManifestResponse>(- `${resolvedApiHost}/app-manifests/${encodeURIComponent(code)}/conversions`,+ `https://${apiBaseUrl}/app-manifests/${encodeURIComponent(code)}/conversions`,{},{headers: {@@ -571,34 +573,9 @@ export const gitHubAppServiceFactory = ({credentials: { host: effectiveHost, instanceType: effectiveInstanceType }});- type TUserInstallation = {- id: number;- app_id: number;- account: { login: string; type: string };- };-- const installations: TUserInstallation[] = [];- const MAX_PAGES = 100;- for (let page = 1; page <= MAX_PAGES; page++) {- const { data } = await safeRequest.get<{ installations: TUserInstallation[] }>(- `https://${apiBaseUrl}/user/installations`,- {- params: { per_page: 100, page },- headers: {- Accept: "application/vnd.github+json",- Authorization: `Bearer ${tokenData.access_token}`,- "X-GitHub-Api-Version": "2022-11-28"- }- }- );-- const pageInstallations = data.installations ?? [];- installations.push(...pageInstallations);-- if (pageInstallations.length < 100) {- break;- }- }+ const installations = await listGitHubUserInstallations(apiBaseUrl, tokenData.access_token, (requestConfig) =>+ safeRequest.request(requestConfig)+ );const appInstallations = installations.filter((installation) => String(installation.app_id) === appId);diff --git a/backend/src/services/github-app/github-app-types.ts b/backend/src/services/github-app/github-app-types.tsindex dff11443ce..b6bfa86463 100644--- a/backend/src/services/github-app/github-app-types.ts+++ b/backend/src/services/github-app/github-app-types.ts@@ -1,3 +1,5 @@+import { z } from "zod";+import { OrgServiceActor } from "@app/lib/types";export type TInitiateGitHubManifestDTO = {@@ -58,15 +60,17 @@ export type TGitHubAppManifestResponse = {} | null;};-export type TSanitizedGitHubApp = {- id: string | null;- orgId: string;- name: string;- appId: string;- slug: string;- clientId: string | null;- owner: string | null;- connectionCount: number;- createdAt: Date | null;- updatedAt: Date | null;-};+export const SanitizedGitHubAppSchema = z.object({+ id: z.string().uuid().nullable(),+ orgId: z.string().uuid(),+ name: z.string(),+ appId: z.string(),+ slug: z.string(),+ clientId: z.string().nullable(),+ owner: z.string().nullable(),+ connectionCount: z.number(),+ createdAt: z.date().nullable(),+ updatedAt: z.date().nullable()+});++export type TSanitizedGitHubApp = z.infer<typeof SanitizedGitHubAppSchema>;diff --git a/frontend/src/helpers/appConnections.ts b/frontend/src/helpers/appConnections.tsindex 2314faf7d6..227450d6fc 100644--- a/frontend/src/helpers/appConnections.ts+++ b/frontend/src/helpers/appConnections.ts@@ -347,6 +347,22 @@ export const AWS_REGIONS = [export const CSRF_TOKEN_STORAGE_KEY = "latestCSRFToken";export const GITHUB_CONNECTION_FORM_STORAGE_KEY = "githubConnectionFormData";+export const buildGitHubHostUrl = (host?: string | null) =>+ host && host.trim().length > 0 ? `https://${host.trim()}` : "https://github.com";++export const buildGitHubAppUrl = (+ slug: string,+ host?: string | null,+ instanceType?: "cloud" | "server"+) => `${buildGitHubHostUrl(host)}/${instanceType === "server" ? "github-apps" : "apps"}/${slug}`;++export const buildGitHubAppInstallUrl = (+ slug: string,+ state: string,+ host?: string | null,+ instanceType?: "cloud" | "server"+) => `${buildGitHubAppUrl(slug, host, instanceType)}/installations/new?state=${state}`;+export const generateCsrfToken = () =>Array.from(crypto.getRandomValues(new Uint8Array(16))).map((b) => b.toString(16).padStart(2, "0"))diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubAppSelector.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubAppSelector.tsxindex 306e4fa866..956e787e8c 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubAppSelector.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubAppSelector.tsx@@ -20,6 +20,7 @@ import {CommandList} from "@app/components/v3/generic/Command";import { Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3/generic/Tooltip";+import { buildGitHubAppUrl } from "@app/helpers/appConnections";import { TGitHubApp, useDeleteGitHubApp } from "@app/hooks/api/gitHubApps";const SHARED_KEY = "__shared__";@@ -29,13 +30,6 @@ const GITHUB_APP_NAME_PREFIX = "infisical-";const getAppKey = (app: TGitHubApp | null) => (app ? (app.id ?? SHARED_KEY) : null);-const buildAppUrl = (app: TGitHubApp, host?: string, instanceType?: "cloud" | "server") => {- const resolvedHost =- host && host.trim().length > 0 ? `https://${host.trim()}` : "https://github.com";- const segment = instanceType === "server" ? "github-apps" : "apps";- return `${resolvedHost}/${segment}/${app.slug}`;-};-type Props = {apps: TGitHubApp[];isLoading: boolean;@@ -188,7 +182,11 @@ export const GitHubAppSelector = ({className="rounded p-1 text-mineshaft-300 hover:bg-mineshaft-600 hover:text-mineshaft-100"onClick={(e) => {e.stopPropagation();- window.open(buildAppUrl(app, host, instanceType), "_blank", "noopener,noreferrer");+ window.open(+ buildGitHubAppUrl(app.slug, host, instanceType),+ "_blank",+ "noopener,noreferrer"+ );}}><FontAwesomeIcon icon={faArrowUpRightFromSquare} className="text-xs" />@@ -334,7 +332,7 @@ export const GitHubAppSelector = ({onClick={(e) => {e.stopPropagation();window.open(- buildAppUrl(sharedApp, host, instanceType),+ buildGitHubAppUrl(sharedApp.slug, host, instanceType),"_blank","noopener,noreferrer");diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsxindex 45b8ecb31a..fcbbbac276 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx@@ -28,6 +28,8 @@ import {} from "@app/context/OrgPermissionContext/types";import {APP_CONNECTION_MAP,+ buildGitHubAppInstallUrl,+ buildGitHubHostUrl,CSRF_TOKEN_STORAGE_KEY,generateCsrfToken,getAppConnectionMethodDetails,@@ -224,9 +226,6 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Pro? (gitHubApps.find((app) => (app.id ?? null) === existingGitHubAppId) ?? null): null;- const buildGithubHost = (host?: string) =>- host && host.length > 0 ? `https://${host}` : "https://github.com";-const storeConnectionFormData = (formData: FormData,installState: string,@@ -300,7 +299,7 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Pro// generate install state here so the OAuth callback can validate itconst installState = generateCsrfToken();- const githubHost = buildGithubHost(formData.credentials?.host);+ const githubHost = buildGitHubHostUrl(formData.credentials?.host);switch (formData.method) {case GitHubConnectionMethod.App: {@@ -317,7 +316,12 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Pro}window.location.assign(- `${githubHost}/${formData.credentials?.instanceType === "server" ? "github-apps" : "apps"}/${slug}/installations/new?state=${installState}`+ buildGitHubAppInstallUrl(+ slug ?? "",+ installState,+ formData.credentials?.host,+ formData.credentials?.instanceType+ ));break;}diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionRow.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionRow.tsxindex 02da15c966..b4991cff1e 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionRow.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionRow.tsx@@ -35,7 +35,11 @@ import { Badge } from "@app/components/v3";import { OrgPermissionSubjects, ProjectPermissionSub, useOrganization } from "@app/context";import { OrgPermissionAppConnectionActions } from "@app/context/OrgPermissionContext/types";import { ProjectPermissionAppConnectionActions } from "@app/context/ProjectPermissionContext/types";-import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";+import {+ APP_CONNECTION_MAP,+ buildGitHubAppUrl,+ getAppConnectionMethodDetails+} from "@app/helpers/appConnections";import { getProjectBaseURL } from "@app/helpers/project";import { useToggle } from "@app/hooks";import { GitHubConnectionMethod, TAppConnection } from "@app/hooks/api/appConnections";@@ -116,9 +120,11 @@ export const AppConnectionRow = ({: null;const gitHubAppUrl = linkedGitHubApp- ? `https://${gitHubAppCredentials?.host?.trim() || "github.com"}/${- gitHubAppCredentials?.instanceType === "server" ? "github-apps" : "apps"- }/${linkedGitHubApp.slug}`+ ? buildGitHubAppUrl(+ linkedGitHubApp.slug,+ gitHubAppCredentials?.host,+ gitHubAppCredentials?.instanceType+ ): null;return (diff --git a/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx b/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsxindex f4da0ff0d2..8c4176d017 100644--- a/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx+++ b/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx@@ -6,6 +6,7 @@ import { Button, ContentLoader } from "@app/components/v2";import { ROUTE_PATHS } from "@app/const/routes";import {APP_CONNECTION_MAP,+ buildGitHubAppInstallUrl,consumeCsrfToken,CSRF_TOKEN_STORAGE_KEY,generateCsrfToken,@@ -597,12 +598,13 @@ export const OAuthCallbackPage = () => {localStorage.setItem(CSRF_TOKEN_STORAGE_KEY, newState);localStorage.setItem(GITHUB_CONNECTION_FORM_STORAGE_KEY, JSON.stringify(formData));- const githubHost = formData.credentials?.host- ? `https://${formData.credentials.host}`- : "https://github.com";-window.location.assign(- `${githubHost}/${formData.credentials?.instanceType === "server" ? "github-apps" : "apps"}/${formData.appSlug}/installations/new?state=${newState}`+ buildGitHubAppInstallUrl(+ formData.appSlug,+ newState,+ formData.credentials?.host,+ formData.credentials?.instanceType+ ));};