Skip to content

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

refactor to reuse common func

Thiago Araujo da Silvae6f5781a0ff6
diff --git a/backend/src/services/app-connection/github/github-connection-fns.ts b/backend/src/services/app-connection/github/github-connection-fns.ts
index e5b6b94ac5..bd8d779099 100644
--- a/backend/src/services/app-connection/github/github-connection-fns.ts
+++ b/backend/src/services/app-connection/github/github-connection-fns.ts
@@ -94,8 +94,18 @@ export const resolveGitHubAppCredentials = async (
!INF_APP_CONNECTION_GITHUB_APP_CLIENT_SECRET ||
!INF_APP_CONNECTION_GITHUB_APP_PRIVATE_KEY
) {
+ const missingEnvVars = Object.entries({
+ INF_APP_CONNECTION_GITHUB_APP_ID,
+ INF_APP_CONNECTION_GITHUB_APP_SLUG,
+ INF_APP_CONNECTION_GITHUB_APP_CLIENT_ID,
+ INF_APP_CONNECTION_GITHUB_APP_CLIENT_SECRET,
+ INF_APP_CONNECTION_GITHUB_APP_PRIVATE_KEY
+ })
+ .filter(([, value]) => !value)
+ .map(([key]) => key);
+
throw new InternalServerError({
- message: "GitHub App environment variables have not been configured"
+ message: `GitHub App environment variables have not been configured. Missing: ${missingEnvVars.join(", ")}`
});
}
@@ -729,6 +739,37 @@ export const listGitHubUserInstallations = async (
return installations;
};
+export const exchangeGitHubOAuthCode = async ({
+ host,
+ clientId,
+ clientSecret,
+ code,
+ requestFn
+}: {
+ host: string;
+ clientId: string;
+ clientSecret: string;
+ code: string;
+ requestFn: (requestConfig: AxiosRequestConfig & { url: string }) => Promise<AxiosResponse<GithubTokenRespData>>;
+}): Promise<AxiosResponse<GithubTokenRespData>> => {
+ const { SITE_URL } = getConfig();
+
+ return requestFn({
+ url: `https://${host}/login/oauth/access_token`,
+ method: "POST",
+ data: {
+ client_id: clientId,
+ client_secret: clientSecret,
+ code,
+ redirect_uri: `${SITE_URL}/organization/app-connections/github/oauth/callback`
+ },
+ headers: {
+ Accept: "application/json",
+ "Content-Type": "application/json"
+ }
+ });
+};
+
export const validateGitHubConnectionCredentials = async (
config: TGitHubConnectionConfig,
gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
@@ -865,8 +906,7 @@ export const validateGitHubConnectionCredentials = async (
}
}
- const { INF_APP_CONNECTION_GITHUB_OAUTH_CLIENT_ID, INF_APP_CONNECTION_GITHUB_OAUTH_CLIENT_SECRET, SITE_URL } =
- getConfig();
+ const { INF_APP_CONNECTION_GITHUB_OAUTH_CLIENT_ID, INF_APP_CONNECTION_GITHUB_OAUTH_CLIENT_SECRET } = getConfig();
let clientId: string | undefined;
let clientSecret: string | undefined;
@@ -898,27 +938,26 @@ export const validateGitHubConnectionCredentials = async (
? await getGitHubGatewayConnectionDetails(config.gatewayId, host, gatewayV2Service)
: undefined;
+ const oauthCode = credentials.code;
+ if (!oauthCode) {
+ throw new BadRequestError({ message: "GitHub authorization code required" });
+ }
+
try {
- tokenResp = await requestWithGitHubGateway<GithubTokenRespData>(
- resolvedConfig,
- gatewayService,
- gatewayV2Service,
- {
- url: `https://${host}/login/oauth/access_token`,
- method: "POST",
- data: {
- client_id: clientId,
- client_secret: clientSecret,
- code: credentials.code,
- redirect_uri: `${SITE_URL}/organization/app-connections/github/oauth/callback`
- },
- headers: {
- Accept: "application/json",
- "Content-Type": "application/json"
- }
- },
- oauthGatewayConnectionDetails
- );
+ tokenResp = await exchangeGitHubOAuthCode({
+ host,
+ clientId,
+ clientSecret,
+ code: oauthCode,
+ requestFn: (requestConfig) =>
+ requestWithGitHubGateway<GithubTokenRespData>(
+ resolvedConfig,
+ gatewayService,
+ gatewayV2Service,
+ requestConfig,
+ oauthGatewayConnectionDetails
+ )
+ });
if (isGithubErrorResponse(tokenResp?.data)) {
throw new BadRequestError({
diff --git a/backend/src/services/github-app/github-app-service.ts b/backend/src/services/github-app/github-app-service.ts
index a1a668889f..ba7c20337e 100644
--- a/backend/src/services/github-app/github-app-service.ts
+++ b/backend/src/services/github-app/github-app-service.ts
@@ -28,6 +28,7 @@ import { safeRequest } from "@app/lib/validator/safe-request";
import {
assertPlatformGitHubHostAllowed,
buildGitHubAppJwtHeaders,
+ exchangeGitHubOAuthCode,
getGitHubGatewayConnectionDetails,
getGitHubInstanceApiUrl,
GithubTokenRespData,
@@ -555,41 +556,46 @@ export const gitHubAppServiceFactory = ({
throw err;
}
- // The callback route is unauthenticated (GitHub redirects the browser here) — the actor is
- // carried in the signed state token. Manifest initiation is JWT-only, so the actor is a user.
- const actorUser = actorType === ActorType.USER ? await userDAL.findById(actorId) : null;
- await auditLogService.createAuditLog({
- ...auditLogInfo,
- orgId,
- ...(projectId ? { projectId } : {}),
- actor: actorUser
- ? {
- type: ActorType.USER,
- metadata: {
- userId: actorUser.id,
- email: actorUser.email,
- username: actorUser.username,
- ...(authMethod ? { authMethod } : {})
+ try {
+ const actorUser = actorType === ActorType.USER ? await userDAL.findById(actorId) : null;
+ await auditLogService.createAuditLog({
+ ...auditLogInfo,
+ orgId,
+ ...(projectId ? { projectId } : {}),
+ actor: actorUser
+ ? {
+ type: ActorType.USER,
+ metadata: {
+ userId: actorUser.id,
+ email: actorUser.email,
+ username: actorUser.username,
+ ...(authMethod ? { authMethod } : {})
+ }
}
+ : {
+ type: ActorType.UNKNOWN_USER,
+ metadata: {}
+ },
+ event: {
+ type: EventType.CREATE_GITHUB_APP,
+ metadata: {
+ gitHubAppId: created.id,
+ name: created.name,
+ appId: created.appId,
+ slug: created.slug,
+ owner: created.owner,
+ host: created.host,
+ instanceType,
+ projectId
}
- : {
- type: ActorType.UNKNOWN_USER,
- metadata: {}
- },
- event: {
- type: EventType.CREATE_GITHUB_APP,
- metadata: {
- gitHubAppId: created.id,
- name: created.name,
- appId: created.appId,
- slug: created.slug,
- owner: created.owner,
- host: created.host,
- instanceType,
- projectId
}
- }
- });
+ });
+ } catch (err) {
+ logger.error(
+ { err, orgId, gitHubAppId: created.id },
+ `Failed to write audit log for GitHub App manifest creation [orgId=${orgId}] [gitHubAppId=${created.id}]`
+ );
+ }
const callbackUrl = new URL(`${SITE_URL}/organizations/${orgId}/app-connections/github/manifest/callback`);
callbackUrl.searchParams.set("gitHubAppId", created.id ?? "");
@@ -719,23 +725,14 @@ export const gitHubAppServiceFactory = ({
let tokenData: GithubTokenRespData;
try {
- const { data } = await sendGitHubRequest<GithubTokenRespData>(
- {
- url: `https://${oauthHost}/login/oauth/access_token`,
- method: "POST",
- data: {
- client_id: clientId,
- client_secret: clientSecret,
- code,
- redirect_uri: `${SITE_URL}/organization/app-connections/github/oauth/callback`
- },
- headers: {
- Accept: "application/json",
- "Content-Type": "application/json"
- }
- },
- oauthGatewayConnectionDetails
- );
+ const { data } = await exchangeGitHubOAuthCode({
+ host: oauthHost,
+ clientId,
+ clientSecret,
+ code,
+ requestFn: (requestConfig) =>
+ sendGitHubRequest<GithubTokenRespData>(requestConfig, oauthGatewayConnectionDetails)
+ });
tokenData = data;
} catch (err) {
logger.error(err, `Failed to exchange GitHub OAuth code [gitHubAppId=${gitHubAppId ?? "shared"}]`);
diff --git a/frontend/src/helpers/appConnections.ts b/frontend/src/helpers/appConnections.ts
index 227450d6fc..4d3f9c5396 100644
--- a/frontend/src/helpers/appConnections.ts
+++ b/frontend/src/helpers/appConnections.ts
@@ -83,6 +83,7 @@ import { SupabaseConnectionMethod } from "@app/hooks/api/appConnections/types/su
import { TravisCIConnectionMethod } from "@app/hooks/api/appConnections/types/travis-ci-connection";
import { VenafiConnectionMethod } from "@app/hooks/api/appConnections/types/venafi-connection";
import { VenafiTppConnectionMethod } from "@app/hooks/api/appConnections/types/venafi-tpp-connection";
+import { IntegrationsListPageTabs } from "@app/types/integrations";
export const APP_CONNECTION_MAP: Record<
AppConnection,
@@ -381,3 +382,54 @@ export const useGetAppConnectionOauthReturnUrl = () => {
return pathname;
};
+
+export const getIntegrationsListTab = () => {
+ if (localStorage.getItem("pkiSyncFormData")) return IntegrationsListPageTabs.PkiSyncs;
+ if (localStorage.getItem("secretSyncFormData")) return IntegrationsListPageTabs.SecretSyncs;
+ return IntegrationsListPageTabs.AppConnections;
+};
+
+export const getConnectionFlowReturnNavigateOptions = ({
+ returnUrl,
+ projectId,
+ reopenFormApp
+}: {
+ returnUrl: string;
+ projectId?: string;
+ reopenFormApp?: AppConnection;
+}) => {
+ const search = {
+ ...(reopenFormApp ? { addConnectionApp: reopenFormApp } : {}),
+ ...(returnUrl.includes("integrations")
+ ? {
+ selectedTab: reopenFormApp
+ ? IntegrationsListPageTabs.AppConnections
+ : getIntegrationsListTab()
+ }
+ : {})
+ };
+
+ return {
+ to: returnUrl,
+ params: { projectId },
+ search: Object.keys(search).length > 0 ? search : undefined
+ };
+};
+
+export type TStoredConnectionFormData<T> =
+ | { status: "ok"; data: T }
+ | { status: "missing" }
+ | { status: "corrupt" };
+
+export const readConnectionFormData = <T>(storageKey: string): TStoredConnectionFormData<T> => {
+ const raw = localStorage.getItem(storageKey);
+
+ if (raw === null) return { status: "missing" };
+
+ try {
+ return { status: "ok", data: JSON.parse(raw) as T };
+ } catch {
+ localStorage.removeItem(storageKey);
+ return { status: "corrupt" };
+ }
+};
diff --git a/frontend/src/pages/organization/AppConnections/GitHubManifestCallbackPage/GitHubManifestCallbackPage.tsx b/frontend/src/pages/organization/AppConnections/GitHubManifestCallbackPage/GitHubManifestCallbackPage.tsx
index d22c65fc70..6dabbac1f5 100644
--- a/frontend/src/pages/organization/AppConnections/GitHubManifestCallbackPage/GitHubManifestCallbackPage.tsx
+++ b/frontend/src/pages/organization/AppConnections/GitHubManifestCallbackPage/GitHubManifestCallbackPage.tsx
@@ -4,9 +4,13 @@ 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 {
+ consumeCsrfToken,
+ getConnectionFlowReturnNavigateOptions,
+ GITHUB_CONNECTION_FORM_STORAGE_KEY,
+ readConnectionFormData
+} from "@app/helpers/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
-import { IntegrationsListPageTabs } from "@app/types/integrations";
export const GitHubManifestCallbackPage = () => {
const navigate = useNavigate();
@@ -22,33 +26,35 @@ export const GitHubManifestCallbackPage = () => {
const { gitHubAppId, slug, installState } = search;
- let connectionForm: {
+ type TStoredGitHubConnectionForm = {
credentials?: Record<string, unknown>;
resumeWithGitHubAppId?: string;
returnUrl?: string;
- } | null = {};
- try {
- const connectionFormRaw = localStorage.getItem(GITHUB_CONNECTION_FORM_STORAGE_KEY);
- connectionForm = connectionFormRaw ? JSON.parse(connectionFormRaw) : {};
- } catch {
- // A corrupt form just means we can't restore the other fields; the app was still created.
+ };
+
+ const storedForm = readConnectionFormData<TStoredGitHubConnectionForm>(
+ GITHUB_CONNECTION_FORM_STORAGE_KEY
+ );
+
+ let connectionForm: TStoredGitHubConnectionForm | null;
+ if (storedForm.status === "ok") {
+ connectionForm = storedForm.data;
+ } else if (storedForm.status === "missing") {
+ connectionForm = {};
+ } else {
connectionForm = null;
- localStorage.removeItem(GITHUB_CONNECTION_FORM_STORAGE_KEY);
}
const returnUrl = connectionForm?.returnUrl;
const navigateBack = (reopenForm: boolean) => {
if (returnUrl) {
- return navigate({
- to: returnUrl,
- search: {
- ...(reopenForm ? { addConnectionApp: AppConnection.GitHub } : {}),
- ...(returnUrl.includes("integrations")
- ? { selectedTab: IntegrationsListPageTabs.AppConnections }
- : {})
- }
- });
+ return navigate(
+ getConnectionFlowReturnNavigateOptions({
+ returnUrl,
+ reopenFormApp: reopenForm ? AppConnection.GitHub : undefined
+ })
+ );
}
return navigate({
to: "/organizations/$orgId/app-connections",
diff --git a/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx b/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx
index 4d81ff23d7..fcef9f5c9c 100644
--- a/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx
+++ b/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx
@@ -10,7 +10,10 @@ import {
consumeCsrfToken,
CSRF_TOKEN_STORAGE_KEY,
generateCsrfToken,
- GITHUB_CONNECTION_FORM_STORAGE_KEY
+ getConnectionFlowReturnNavigateOptions,
+ getIntegrationsListTab,
+ GITHUB_CONNECTION_FORM_STORAGE_KEY,
+ readConnectionFormData
} from "@app/helpers/appConnections";
import {
AzureAppConfigurationConnectionMethod,
@@ -26,7 +29,6 @@ import {
} from "@app/hooks/api/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
import { resolveGitHubAppInstallations, TGitHubAppInstallation } from "@app/hooks/api/gitHubApps";
-import { IntegrationsListPageTabs } from "@app/types/integrations";
import { FormDataMap } from "./OauthCallbackPage.types";
@@ -81,12 +83,6 @@ export const OAuthCallbackPage = () => {
localStorage.removeItem(dataFieldName!);
};
- const getIntegrationsTab = () => {
- if (localStorage.getItem("pkiSyncFormData")) return IntegrationsListPageTabs.PkiSyncs;
- if (localStorage.getItem("secretSyncFormData")) return IntegrationsListPageTabs.SecretSyncs;
- return IntegrationsListPageTabs.AppConnections;
- };
-
// Shared post-success step: notify and navigate back to where the connection flow started.
const finalizeConnection = async (data: {
returnUrl: string;
@@ -111,7 +107,7 @@ export const OAuthCallbackPage = () => {
connectionId: data.connection.id,
connectionName: data.connection.name,
...(data.returnUrl.includes("integrations")
- ? { selectedTab: getIntegrationsTab() }
+ ? { selectedTab: getIntegrationsListTab() }
: {})
}
});
@@ -120,9 +116,9 @@ export const OAuthCallbackPage = () => {
const getFormData = <T extends keyof FormDataMap>(app: T): FormDataMap[T] | null => {
const dataFieldName = formDataStorageFieldMap[app];
- const rawData = localStorage.getItem(dataFieldName!);
+ const result = readConnectionFormData<FormDataMap[T]>(dataFieldName!);
- if (rawData === null) {
+ if (result.status === "missing") {
createNotification({
type: "error",
text: `Your ${app ? APP_CONNECTION_MAP[app as AppConnection].name : ""} Connection session has expired or was already completed. Please restart the connection flow.`
@@ -131,12 +127,7 @@ export const OAuthCallbackPage = () => {
return null;
}
- try {
- return {
- ...JSON.parse(rawData),
- app
- } as FormDataMap[T];
- } catch {
+ if (result.status === "corrupt") {
createNotification({
type: "error",
text: `Invalid ${app || ""} form state, redirecting...`
@@ -144,6 +135,11 @@ export const OAuthCallbackPage = () => {
navigate({ to: "/" });
return null;
}
+
+ return {
+ ...result.data,
+ app
+ } as FormDataMap[T];
};
const handleGitLab = useCallback(async () => {
@@ -443,15 +439,7 @@ export const OAuthCallbackPage = () => {
(err as { response?: { data?: { message?: string } } })?.response?.data?.message ??
"Failed to resolve GitHub App installations"
});
- navigate({
- to: returnUrl,
- params: {
- projectId
- },
- search: returnUrl.includes("integrations")
- ? { selectedTab: getIntegrationsTab() }
- : undefined
- });
+ navigate(getConnectionFlowReturnNavigateOptions({ returnUrl, projectId }));
}
return null;
}
@@ -509,15 +497,7 @@ export const OAuthCallbackPage = () => {
(err as { response?: { data?: { message?: string } } })?.response?.data?.message ??
`Failed to ${connectionId ? "update" : "create"} GitHub Connection`
});
- navigate({
- to: returnUrl,
- params: {
- projectId
- },
- search: returnUrl.includes("integrations")
- ? { selectedTab: getIntegrationsTab() }
- : undefined
- });
+ navigate(getConnectionFlowReturnNavigateOptions({ returnUrl, projectId }));
return null;
}
@@ -584,15 +564,7 @@ export const OAuthCallbackPage = () => {
(err as { response?: { data?: { message?: string } } })?.response?.data?.message ??
`Failed to ${connectionId ? "update" : "create"} GitHub Connection`
});
- navigate({
- to: returnUrl,
- params: {
- projectId
- },
- search: returnUrl.includes("integrations")
- ? { selectedTab: getIntegrationsTab() }
- : undefined
- });
+ navigate(getConnectionFlowReturnNavigateOptions({ returnUrl, projectId }));
}
};
@@ -606,15 +578,12 @@ export const OAuthCallbackPage = () => {
type: "error",
text: "Unable to determine the GitHub App to install. Please restart the connection flow."
});
- navigate({
- to: formData.returnUrl,
- params: {
+ navigate(
+ getConnectionFlowReturnNavigateOptions({
+ returnUrl: formData.returnUrl,
projectId: formData.projectId
- },
- search: formData.returnUrl.includes("integrations")
- ? { selectedTab: getIntegrationsTab() }
- : undefined
- });
+ })
+ );
return;
}