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
Thiago Araujo da Silvaf115e118b919
diff --git a/backend/src/services/app-connection/github/github-connection-fns.ts b/backend/src/services/app-connection/github/github-connection-fns.tsindex b61d4aa415..f8a64c1618 100644--- a/backend/src/services/app-connection/github/github-connection-fns.ts+++ b/backend/src/services/app-connection/github/github-connection-fns.ts@@ -271,6 +271,22 @@ export const requestWithGitHubGateway = async <T>();};+export const signGitHubAppJwt = (appId: string, privateKey: string) => {+ const appPrivateKey = privateKey+ .split("\n")+ .map((line) => line.trim())+ .join("\n");++ const now = Math.floor(Date.now() / 1000);+ return crypto.jwt().sign({ iat: now, exp: now + 5 * 60, iss: appId }, appPrivateKey, { algorithm: "RS256" });+};++export const buildGitHubAppJwtHeaders = (appJwt: string) => ({+ Accept: "application/vnd.github+json",+ Authorization: `Bearer ${appJwt}`,+ "X-GitHub-Api-Version": "2022-11-28"+});+export const getGitHubAppAuthToken = async (appConnection: TGitHubConnection,gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,@@ -300,19 +316,7 @@ export const getGitHubAppAuthToken = async (assertPlatformGitHubHostAllowed(effectiveCredentials.host);- const appPrivateKey = privateKey- .split("\n")- .map((line) => line.trim())- .join("\n");-- const now = Math.floor(Date.now() / 1000);- const payload = {- iat: now,- exp: now + 5 * 60,- iss: appId- };-- const appJwt = crypto.jwt().sign(payload, appPrivateKey, { algorithm: "RS256" });+ const appJwt = signGitHubAppJwt(appId, privateKey);const apiBaseUrl = await getGitHubInstanceApiUrl({ credentials: effectiveCredentials });const { installationId } = appConnection.credentials;@@ -333,11 +337,7 @@ export const getGitHubAppAuthToken = async ({url: `https://${apiBaseUrl}/app/installations/${installationId}/access_tokens`,method: "POST",- headers: {- Accept: "application/vnd.github+json",- Authorization: `Bearer ${appJwt}`,- "X-GitHub-Api-Version": "2022-11-28"- }+ headers: buildGitHubAppJwtHeaders(appJwt)},gatewayConnectionDetails);@@ -392,11 +392,10 @@ export const makePaginatedGitHubRequest = async <T, R = T[]>(token = await getGitHubAppAuthToken(appConnection, gatewayService, gatewayV2Service, gatewayPoolService, deps);}- const baseUrl = `https://${await getGitHubInstanceApiUrl(appConnection)}${path}`;- const initialUrlObj = new URL(baseUrl);+ const apiBaseUrl = await getGitHubInstanceApiUrl(appConnection);+ const initialUrlObj = new URL(`https://${apiBaseUrl}${path}`);initialUrlObj.searchParams.set("per_page", "100");- const apiBaseUrl = await getGitHubInstanceApiUrl(appConnection);const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({gatewayId: appConnection.gatewayId,gatewayPoolId: appConnection.gatewayPoolIddiff --git a/backend/src/services/github-app/github-app-service.ts b/backend/src/services/github-app/github-app-service.tsindex 4176bcdde5..ca1f778544 100644--- a/backend/src/services/github-app/github-app-service.ts+++ b/backend/src/services/github-app/github-app-service.ts@@ -17,8 +17,10 @@ import { TAppConnectionDALFactory } from "@app/services/app-connection/app-conneimport { decryptAppConnectionCredentials } from "@app/services/app-connection/app-connection-fns";import {assertPlatformGitHubHostAllowed,+ buildGitHubAppJwtHeaders,getGitHubInstanceApiUrl,- resolveGitHubAppCredentials+ resolveGitHubAppCredentials,+ signGitHubAppJwt} from "@app/services/app-connection/github/github-connection-fns";import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";import { TKmsServiceFactory } from "@app/services/kms/kms-service";@@ -140,21 +142,8 @@ export const gitHubAppServiceFactory = ({credentials: { host: host ?? undefined, instanceType: instanceType ?? "cloud" }});- const appPrivateKey = privateKey- .split("\n")- .map((line) => line.trim())- .join("\n");-- const now = Math.floor(Date.now() / 1000);- const appJwt = crypto.jwt().sign({ iat: now, exp: now + 5 * 60, iss: appId }, appPrivateKey, {- algorithm: "RS256"- });-- const headers = {- Accept: "application/vnd.github+json",- Authorization: `Bearer ${appJwt}`,- "X-GitHub-Api-Version": "2022-11-28"- };+ const appJwt = signGitHubAppJwt(appId, privateKey);+ const headers = buildGitHubAppJwtHeaders(appJwt);const installationIds: number[] = [];let page = 1;@@ -518,26 +507,14 @@ export const gitHubAppServiceFactory = ({credentials: { host: effectiveHost, instanceType: effectiveInstanceType }});- const appPrivateKey = privateKey- .split("\n")- .map((line) => line.trim())- .join("\n");-- const now = Math.floor(Date.now() / 1000);- const appJwt = crypto.jwt().sign({ iat: now, exp: now + 5 * 60, iss: appId }, appPrivateKey, {- algorithm: "RS256"- });+ const appJwt = signGitHubAppJwt(appId, privateKey);try {// safeRequest validates + DNS-pins the target and disables redirects, so a public host// cannot redirect this request to an internal service (SSRF).const { data } = await safeRequest.get<{ id: number }[]>(`https://${apiBaseUrl}/app/installations`, {params: { per_page: 1 },- headers: {- Accept: "application/vnd.github+json",- Authorization: `Bearer ${appJwt}`,- "X-GitHub-Api-Version": "2022-11-28"- }+ headers: buildGitHubAppJwtHeaders(appJwt)});return { installed: data.length > 0, clientId };diff --git a/frontend/src/helpers/appConnections.ts b/frontend/src/helpers/appConnections.tsindex 2a94127c00..2314faf7d6 100644--- a/frontend/src/helpers/appConnections.ts+++ b/frontend/src/helpers/appConnections.ts@@ -344,6 +344,20 @@ export const AWS_REGIONS = [{ name: "AWS GovCloud (US-West)", slug: "us-gov-west-1" }];+export const CSRF_TOKEN_STORAGE_KEY = "latestCSRFToken";+export const GITHUB_CONNECTION_FORM_STORAGE_KEY = "githubConnectionFormData";++export const generateCsrfToken = () =>+ Array.from(crypto.getRandomValues(new Uint8Array(16)))+ .map((b) => b.toString(16).padStart(2, "0"))+ .join("");++export const consumeCsrfToken = (state: string) => {+ if (state !== localStorage.getItem(CSRF_TOKEN_STORAGE_KEY)) return false;+ localStorage.removeItem(CSRF_TOKEN_STORAGE_KEY);+ return true;+};+export const useGetAppConnectionOauthReturnUrl = () => {const {location: { pathname }diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsxindex 6f913ca504..b1699ac45b 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx@@ -28,7 +28,10 @@ import {} from "@app/context/OrgPermissionContext/types";import {APP_CONNECTION_MAP,+ CSRF_TOKEN_STORAGE_KEY,+ generateCsrfToken,getAppConnectionMethodDetails,+ GITHUB_CONNECTION_FORM_STORAGE_KEY,useGetAppConnectionOauthReturnUrl} from "@app/helpers/appConnections";import { isInfisicalCloud } from "@app/helpers/platform";@@ -95,8 +98,6 @@ const patSchema = rootSchema.extend({])});-const GITHUB_CONNECTION_FORM_KEY = "githubConnectionFormData";-type PatSchemaForm = z.infer<typeof patSchema>;const formSchema = z.discriminatedUnion("method", [appSchema, oauthSchema, patSchema]);@@ -164,7 +165,7 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: ProuseEffect(() => {if (isUpdate) return;try {- const raw = localStorage.getItem(GITHUB_CONNECTION_FORM_KEY);+ const raw = localStorage.getItem(GITHUB_CONNECTION_FORM_STORAGE_KEY);if (!raw) return;const stored = JSON.parse(raw) as {method?: GitHubConnectionMethod;@@ -194,7 +195,7 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Pro} catch {// ignore malformed state} finally {- localStorage.removeItem(GITHUB_CONNECTION_FORM_KEY);+ localStorage.removeItem(GITHUB_CONNECTION_FORM_STORAGE_KEY);}// run once on mount// eslint-disable-next-line react-hooks/exhaustive-deps@@ -226,19 +227,14 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Proconst buildGithubHost = (host?: string) =>host && host.length > 0 ? `https://${host}` : "https://github.com";- const generateInstallState = () =>- Array.from(crypto.getRandomValues(new Uint8Array(16)))- .map((b) => b.toString(16).padStart(2, "0"))- .join("");-const storeConnectionFormData = (formData: FormData,installState: string,gitHubAppId?: string | null) => {- localStorage.setItem("latestCSRFToken", installState);+ localStorage.setItem(CSRF_TOKEN_STORAGE_KEY, installState);localStorage.setItem(- GITHUB_CONNECTION_FORM_KEY,+ GITHUB_CONNECTION_FORM_STORAGE_KEY,JSON.stringify({...formData,credentials: {@@ -259,7 +255,7 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Proconst handleCreateApp = async ({ name, githubOrg }: { name: string; githubOrg: string }) => {const formData = form.getValues();setIsRedirecting(true);- const installState = generateInstallState();+ const installState = generateCsrfToken();storeConnectionFormData(formData, installState);try {@@ -305,7 +301,7 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: ProsetIsRedirecting(true);// generate install state here so the OAuth callback can validate it- const installState = generateInstallState();+ const installState = generateCsrfToken();const githubHost = buildGithubHost(formData.credentials?.host);switch (formData.method) {diff --git a/frontend/src/pages/organization/AppConnections/GitHubManifestCallbackPage/GitHubManifestCallbackPage.tsx b/frontend/src/pages/organization/AppConnections/GitHubManifestCallbackPage/GitHubManifestCallbackPage.tsxindex 9c1ba555f3..cd5f9ab764 100644--- a/frontend/src/pages/organization/AppConnections/GitHubManifestCallbackPage/GitHubManifestCallbackPage.tsx+++ b/frontend/src/pages/organization/AppConnections/GitHubManifestCallbackPage/GitHubManifestCallbackPage.tsx@@ -4,10 +4,9 @@ import { useNavigate, useParams, useSearch } from "@tanstack/react-router";import { createNotification } from "@app/components/notifications";import { ContentLoader } from "@app/components/v2";import { ROUTE_PATHS } from "@app/const/routes";+import { consumeCsrfToken, GITHUB_CONNECTION_FORM_STORAGE_KEY } from "@app/helpers/appConnections";import { AppConnection } from "@app/hooks/api/appConnections/enums";-const GITHUB_CONNECTION_FORM_KEY = "githubConnectionFormData";-export const GitHubManifestCallbackPage = () => {const navigate = useNavigate();const { orgId } = useParams({ strict: false }) as { orgId: string };@@ -39,17 +38,16 @@ export const GitHubManifestCallbackPage = () => {// round-tripped through the signed manifest token and echoed back here; it must match the CSRF// token stored when the user kicked off app creation. This blocks a crafted callback URL from// pre-seeding the connection form with an attacker-chosen app id.- if (installState !== localStorage.getItem("latestCSRFToken")) {+ if (!consumeCsrfToken(installState)) {createNotification({ type: "error", text: "Invalid GitHub manifest callback state." });navigate({ to: "/organizations/$orgId/app-connections", params: { orgId } });return;}- localStorage.removeItem("latestCSRFToken");// The GitHub App is already created at this point. Mark the in-progress connection form so it// resumes with the new app selected, then send the user back to it to finish the connection.try {- const connectionFormRaw = localStorage.getItem(GITHUB_CONNECTION_FORM_KEY);+ const connectionFormRaw = localStorage.getItem(GITHUB_CONNECTION_FORM_STORAGE_KEY);const connectionForm = connectionFormRaw? (JSON.parse(connectionFormRaw) as {credentials?: Record<string, unknown>;@@ -61,10 +59,10 @@ export const GitHubManifestCallbackPage = () => {gitHubAppId};connectionForm.resumeWithGitHubAppId = gitHubAppId;- localStorage.setItem(GITHUB_CONNECTION_FORM_KEY, JSON.stringify(connectionForm));+ localStorage.setItem(GITHUB_CONNECTION_FORM_STORAGE_KEY, JSON.stringify(connectionForm));} catch {// A corrupt form just means we can't restore the other fields; the app was still created.- localStorage.removeItem(GITHUB_CONNECTION_FORM_KEY);+ localStorage.removeItem(GITHUB_CONNECTION_FORM_STORAGE_KEY);}createNotification({diff --git a/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx b/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsxindex 8f24ade7d1..54c13d3e6e 100644--- a/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx+++ b/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx@@ -4,7 +4,11 @@ import { useNavigate, useParams, useSearch } from "@tanstack/react-router";import { createNotification } from "@app/components/notifications";import { ContentLoader } from "@app/components/v2";import { ROUTE_PATHS } from "@app/const/routes";-import { APP_CONNECTION_MAP } from "@app/helpers/appConnections";+import {+ APP_CONNECTION_MAP,+ consumeCsrfToken,+ GITHUB_CONNECTION_FORM_STORAGE_KEY+} from "@app/helpers/appConnections";import {AzureAppConfigurationConnectionMethod,AzureClientSecretsConnectionMethod,@@ -23,7 +27,7 @@ import { IntegrationsListPageTabs } from "@app/types/integrations";import { FormDataMap } from "./OauthCallbackPage.types";const formDataStorageFieldMap: Partial<Record<AppConnection, string>> = {- [AppConnection.GitHub]: "githubConnectionFormData",+ [AppConnection.GitHub]: GITHUB_CONNECTION_FORM_STORAGE_KEY,[AppConnection.GitHubRadar]: "githubRadarConnectionFormData",[AppConnection.GitLab]: "gitlabConnectionFormData",[AppConnection.AzureKeyVault]: "azureKeyVaultConnectionFormData",@@ -55,14 +59,13 @@ export const OAuthCallbackPage = () => {const appConnection = rawState.includes("<:>") ? rawState.split("<:>")[1] : rawAppConnection;const clearState = (app: AppConnection) => {- if (state !== localStorage.getItem("latestCSRFToken")) {+ if (!consumeCsrfToken(state)) {throw new Error("Invalid CSRF token");}const dataFieldName = formDataStorageFieldMap[app];localStorage.removeItem(dataFieldName!);- localStorage.removeItem("latestCSRFToken");};const getFormData = <T extends keyof FormDataMap>(app: T): FormDataMap[T] | null => {