Merge pull request #3835 from Infisical/feat/gitlabSecretSync

feat(secret-sync): Add gitlab secret sync
This commit is contained in:
carlosmonastyrski
2025-06-25 17:53:12 -03:00
committed by GitHub
108 changed files with 5318 additions and 62 deletions
@@ -0,0 +1,282 @@
import { Controller, useFormContext, useWatch } from "react-hook-form";
import { SingleValue } from "react-select";
import { faCircleInfo, faQuestionCircle } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { SecretSyncConnectionField } from "@app/components/secret-syncs/forms/SecretSyncConnectionField";
import {
FilterableSelect,
FormControl,
Input,
Select,
SelectItem,
Switch,
Tooltip
} from "@app/components/v2";
import {
TGitLabGroup,
TGitLabProject,
useGitlabConnectionListGroups,
useGitlabConnectionListProjects
} from "@app/hooks/api/appConnections/gitlab";
import { SecretSync } from "@app/hooks/api/secretSyncs";
import { GitLabSyncScope } from "@app/hooks/api/secretSyncs/types/gitlab-sync";
import { TSecretSyncForm } from "../schemas";
const SecretProtectionOption = ({
title,
isEnabled,
onChange,
id,
isDisabled = false,
tooltip
}: {
title: string;
isEnabled: boolean;
onChange: (checked: boolean) => void;
id: string;
isDisabled?: boolean;
tooltip?: string;
}) => {
return (
<Switch
className="bg-mineshaft-400/80 shadow-inner data-[state=checked]:bg-green/80"
id={id}
thumbClassName="bg-mineshaft-800"
onCheckedChange={onChange}
isChecked={isEnabled}
isDisabled={isDisabled}
containerClassName="w-full"
>
<p>
{title}{" "}
{tooltip && (
<Tooltip className="max-w-md" content={tooltip}>
<FontAwesomeIcon icon={faQuestionCircle} size="sm" className="ml-1" />
</Tooltip>
)}
</p>
</Switch>
);
};
export const GitLabSyncFields = () => {
const { control, setValue } = useFormContext<
TSecretSyncForm & { destination: SecretSync.GitLab }
>();
const connectionId = useWatch({ name: "connection.id", control });
const scope = useWatch({ name: "destinationConfig.scope", control });
const shouldMaskSecrets = useWatch({ name: "destinationConfig.shouldMaskSecrets", control });
const { data: groups, isLoading: isGroupsLoading } = useGitlabConnectionListGroups(connectionId, {
enabled: Boolean(connectionId) && scope === GitLabSyncScope.Group
});
const { data: projects, isLoading: isProjectsLoading } = useGitlabConnectionListProjects(
connectionId,
{
enabled: Boolean(connectionId)
}
);
return (
<div className="h-full overflow-auto">
<SecretSyncConnectionField
onChange={() => {
setValue("destinationConfig.projectId", "");
setValue("destinationConfig.projectName", "");
setValue("destinationConfig.groupId", "");
setValue("destinationConfig.groupName", "");
setValue("destinationConfig.scope", GitLabSyncScope.Project);
}}
/>
<Controller
name="destinationConfig.scope"
control={control}
defaultValue={GitLabSyncScope.Project}
render={({ field: { value, onChange }, fieldState: { error } }) => (
<FormControl errorText={error?.message} isError={Boolean(error?.message)} label="Scope">
<Select
value={value}
onValueChange={(val) => {
onChange(val);
setValue("destinationConfig.projectId", "");
setValue("destinationConfig.projectName", "");
setValue("destinationConfig.groupId", "");
setValue("destinationConfig.groupName", "");
}}
className="w-full border border-mineshaft-500 capitalize"
position="popper"
placeholder="Select a scope..."
dropdownContainerClassName="max-w-none"
>
{Object.values(GitLabSyncScope).map((projectScope) => (
<SelectItem className="capitalize" value={projectScope} key={projectScope}>
{projectScope.replace("-", " ")}
</SelectItem>
))}
</Select>
</FormControl>
)}
/>
{scope === GitLabSyncScope.Group && (
<Controller
name="destinationConfig.groupId"
control={control}
render={({ field: { value, onChange }, fieldState: { error } }) => (
<FormControl
isError={Boolean(error)}
errorText={error?.message}
label="Group"
helperText={
<Tooltip
className="max-w-md"
content="Ensure the group exists in the connection's GitLab instance URL."
>
<div>
<span>Don&#39;t see the group you&#39;re looking for?</span>{" "}
<FontAwesomeIcon icon={faCircleInfo} className="text-mineshaft-400" />
</div>
</Tooltip>
}
>
<FilterableSelect
menuPlacement="top"
isLoading={isGroupsLoading && Boolean(connectionId)}
isDisabled={!connectionId}
value={groups?.find((group) => group.id === value) ?? null}
onChange={(option) => {
onChange((option as SingleValue<TGitLabGroup>)?.id ?? "");
setValue(
"destinationConfig.groupName",
(option as SingleValue<TGitLabGroup>)?.name ?? ""
);
}}
options={groups}
placeholder="Select a group..."
getOptionLabel={(option) => option.name}
getOptionValue={(option) => option.id}
/>
</FormControl>
)}
/>
)}
{scope === GitLabSyncScope.Project && (
<Controller
name="destinationConfig.projectId"
control={control}
render={({ field: { value, onChange }, fieldState: { error } }) => (
<FormControl
isError={Boolean(error)}
errorText={error?.message}
label="GitLab Project"
helperText={
<Tooltip
className="max-w-md"
content="Ensure the project exists in the connection's GitLab instance URL and the connection has access to it."
>
<div>
<span>Don&#39;t see the project you&#39;re looking for?</span>{" "}
<FontAwesomeIcon icon={faCircleInfo} className="text-mineshaft-400" />
</div>
</Tooltip>
}
>
<FilterableSelect
menuPlacement="top"
isLoading={isProjectsLoading && Boolean(connectionId)}
isDisabled={!connectionId}
value={projects?.find((project) => project.id === value) ?? null}
onChange={(option) => {
onChange((option as SingleValue<TGitLabProject>)?.id ?? "");
setValue(
"destinationConfig.projectName",
(option as SingleValue<TGitLabProject>)?.name ?? ""
);
}}
options={projects}
placeholder="Select a project..."
getOptionLabel={(option) => option.name}
getOptionValue={(option) => option.id}
/>
</FormControl>
)}
/>
)}
<Controller
control={control}
defaultValue=""
name="destinationConfig.targetEnvironment"
render={({ field, fieldState: { error } }) => (
<FormControl
label="GitLab Environment Scope (Optional)"
isError={Boolean(error)}
errorText={error?.message}
>
<Input {...field} placeholder="*" />
</FormControl>
)}
/>
{/* Secret Protection Settings Section */}
<div className="mt-6">
<div className="space-y-4">
<Controller
control={control}
name="destinationConfig.shouldProtectSecrets"
render={({ field: { onChange, value } }) => (
<SecretProtectionOption
id="should-protect-secrets"
title="Mark secrets as Protected"
isEnabled={value || false}
onChange={onChange}
/>
)}
/>
<Controller
control={control}
name="destinationConfig.shouldMaskSecrets"
render={({ field: { onChange, value } }) => (
<SecretProtectionOption
id="should-mask-secrets"
title="Mark secrets as Masked"
tooltip="GitLab has limitations for masked variables: secrets must be at least 8 characters long and not match existing CI/CD variable names. Secrets not meeting these criteria won't be masked."
isEnabled={value || false}
onChange={(checked) => {
onChange(checked);
if (!checked) {
setValue("destinationConfig.shouldHideSecrets", false);
}
}}
/>
)}
/>
<Controller
control={control}
name="destinationConfig.shouldHideSecrets"
render={({ field: { onChange, value } }) => (
<div className="max-h-32 opacity-100 transition-all duration-300">
<SecretProtectionOption
id="should-hide-secrets"
title="Mark secrets as Hidden"
tooltip="Secrets can only be marked as hidden if they are also masked. If this is enabled, Infisical will not be able to unhide/unmask secrets from the sync destination if you disable the option later."
isEnabled={value || false}
onChange={onChange}
isDisabled={!shouldMaskSecrets}
/>
</div>
)}
/>
</div>
</div>
</div>
);
};
@@ -15,6 +15,7 @@ import { DatabricksSyncFields } from "./DatabricksSyncFields";
import { FlyioSyncFields } from "./FlyioSyncFields";
import { GcpSyncFields } from "./GcpSyncFields";
import { GitHubSyncFields } from "./GitHubSyncFields";
import { GitLabSyncFields } from "./GitLabSyncFields";
import { HCVaultSyncFields } from "./HCVaultSyncFields";
import { HerokuSyncFields } from "./HerokuSyncFields";
import { HumanitecSyncFields } from "./HumanitecSyncFields";
@@ -71,6 +72,8 @@ export const SecretSyncDestinationFields = () => {
return <RenderSyncFields />;
case SecretSync.Flyio:
return <FlyioSyncFields />;
case SecretSync.GitLab:
return <GitLabSyncFields />;
case SecretSync.CloudflarePages:
return <CloudflarePagesSyncFields />;
default:
@@ -55,6 +55,7 @@ export const SecretSyncOptionsFields = ({ hideInitialSync }: Props) => {
case SecretSync.Heroku:
case SecretSync.Render:
case SecretSync.Flyio:
case SecretSync.GitLab:
case SecretSync.CloudflarePages:
AdditionalSyncOptionsFieldsComponent = null;
break;
@@ -0,0 +1,37 @@
import { useFormContext } from "react-hook-form";
import { GenericFieldLabel } from "@app/components/secret-syncs";
import { TSecretSyncForm } from "@app/components/secret-syncs/forms/schemas";
import { SecretSync } from "@app/hooks/api/secretSyncs";
import { GitLabSyncScope } from "@app/hooks/api/secretSyncs/types/gitlab-sync";
export const GitLabSyncReviewFields = () => {
const { watch } = useFormContext<TSecretSyncForm & { destination: SecretSync.GitLab }>();
const projectName = watch("destinationConfig.projectName");
const targetEnvironment = watch("destinationConfig.targetEnvironment");
const groupName = watch("destinationConfig.groupName");
const scope = watch("destinationConfig.scope");
const shouldProtectSecrets = watch("destinationConfig.shouldProtectSecrets");
const shouldMaskSecrets = watch("destinationConfig.shouldMaskSecrets");
const shouldHideSecrets = watch("destinationConfig.shouldHideSecrets");
return (
<>
<GenericFieldLabel label="Scope">{scope}</GenericFieldLabel>
{scope === GitLabSyncScope.Project && (
<GenericFieldLabel label="Project Name">{projectName}</GenericFieldLabel>
)}
{scope === GitLabSyncScope.Group && (
<GenericFieldLabel label="Group Name">{groupName}</GenericFieldLabel>
)}
{targetEnvironment && (
<GenericFieldLabel label="Environment">{targetEnvironment}</GenericFieldLabel>
)}
<GenericFieldLabel label="Protect Secrets">
{shouldProtectSecrets ? "Yes" : "No"}
</GenericFieldLabel>
<GenericFieldLabel label="Mask Secrets">{shouldMaskSecrets ? "Yes" : "No"}</GenericFieldLabel>
<GenericFieldLabel label="Hide Secrets">{shouldHideSecrets ? "Yes" : "No"}</GenericFieldLabel>
</>
);
};
@@ -24,6 +24,7 @@ import { DatabricksSyncReviewFields } from "./DatabricksSyncReviewFields";
import { FlyioSyncReviewFields } from "./FlyioSyncReviewFields";
import { GcpSyncReviewFields } from "./GcpSyncReviewFields";
import { GitHubSyncReviewFields } from "./GitHubSyncReviewFields";
import { GitLabSyncReviewFields } from "./GitLabSyncReviewFields";
import { HCVaultSyncReviewFields } from "./HCVaultSyncReviewFields";
import { HerokuSyncReviewFields } from "./HerokuSyncReviewFields";
import { HumanitecSyncReviewFields } from "./HumanitecSyncReviewFields";
@@ -117,6 +118,9 @@ export const SecretSyncReviewFields = () => {
case SecretSync.Flyio:
DestinationFieldsComponent = <FlyioSyncReviewFields />;
break;
case SecretSync.GitLab:
DestinationFieldsComponent = <GitLabSyncReviewFields />;
break;
case SecretSync.CloudflarePages:
DestinationFieldsComponent = <CloudflarePagesSyncReviewFields />;
break;
@@ -0,0 +1,31 @@
import { z } from "zod";
import { BaseSecretSyncSchema } from "@app/components/secret-syncs/forms/schemas/base-secret-sync-schema";
import { SecretSync } from "@app/hooks/api/secretSyncs";
import { GitLabSyncScope } from "@app/hooks/api/secretSyncs/types/gitlab-sync";
export const GitlabSyncDestinationSchema = BaseSecretSyncSchema().merge(
z.object({
destination: z.literal(SecretSync.GitLab),
destinationConfig: z.discriminatedUnion("scope", [
z.object({
scope: z.literal(GitLabSyncScope.Project),
projectId: z.string().trim().min(1, "Project ID required"),
projectName: z.string().trim().min(1, "Project name required"),
targetEnvironment: z.string().optional(),
shouldProtectSecrets: z.boolean().optional().default(false),
shouldMaskSecrets: z.boolean().optional().default(false),
shouldHideSecrets: z.boolean().optional().default(false)
}),
z.object({
scope: z.literal(GitLabSyncScope.Group),
targetEnvironment: z.string().optional(),
groupId: z.string().trim().min(1, "Group ID required"),
groupName: z.string().trim().min(1, "Group name required"),
shouldProtectSecrets: z.boolean().optional().default(false),
shouldMaskSecrets: z.boolean().optional().default(false),
shouldHideSecrets: z.boolean().optional().default(false)
})
])
})
);
@@ -12,6 +12,7 @@ import { DatabricksSyncDestinationSchema } from "./databricks-sync-destination-s
import { FlyioSyncDestinationSchema } from "./flyio-sync-destination-schema";
import { GcpSyncDestinationSchema } from "./gcp-sync-destination-schema";
import { GitHubSyncDestinationSchema } from "./github-sync-destination-schema";
import { GitlabSyncDestinationSchema } from "./gitlab-sync-destination-schema";
import { HCVaultSyncDestinationSchema } from "./hc-vault-sync-destination-schema";
import { HerokuSyncDestinationSchema } from "./heroku-sync-destination-schema";
import { HumanitecSyncDestinationSchema } from "./humanitec-sync-destination-schema";
@@ -43,6 +44,7 @@ const SecretSyncUnionSchema = z.discriminatedUnion("destination", [
HerokuSyncDestinationSchema,
RenderSyncDestinationSchema,
FlyioSyncDestinationSchema,
GitlabSyncDestinationSchema,
CloudflarePagesSyncDestinationSchema
]);
+3
View File
@@ -24,6 +24,7 @@ import {
GcpConnectionMethod,
GitHubConnectionMethod,
GitHubRadarConnectionMethod,
GitLabConnectionMethod,
HCVaultConnectionMethod,
HumanitecConnectionMethod,
LdapConnectionMethod,
@@ -86,6 +87,7 @@ export const APP_CONNECTION_MAP: Record<
[AppConnection.Heroku]: { name: "Heroku", image: "Heroku.png" },
[AppConnection.Render]: { name: "Render", image: "Render.png" },
[AppConnection.Flyio]: { name: "Fly.io", image: "Flyio.svg" },
[AppConnection.Gitlab]: { name: "GitLab", image: "GitLab.png" },
[AppConnection.Cloudflare]: { name: "Cloudflare", image: "Cloudflare.png" }
};
@@ -100,6 +102,7 @@ export const getAppConnectionMethodDetails = (method: TAppConnection["method"])
case AzureDevOpsConnectionMethod.OAuth:
case GitHubConnectionMethod.OAuth:
case HerokuConnectionMethod.OAuth:
case GitLabConnectionMethod.OAuth:
return { name: "OAuth", icon: faPassport };
case AwsConnectionMethod.AccessKey:
case OCIConnectionMethod.AccessKey:
+5
View File
@@ -74,6 +74,10 @@ export const SECRET_SYNC_MAP: Record<SecretSync, { name: string; image: string }
name: "Fly.io",
image: "Flyio.svg"
},
[SecretSync.GitLab]: {
name: "GitLab",
image: "GitLab.png"
},
[SecretSync.CloudflarePages]: {
name: "Cloudflare Pages",
image: "Cloudflare.png"
@@ -101,6 +105,7 @@ export const SECRET_SYNC_CONNECTION_MAP: Record<SecretSync, AppConnection> = {
[SecretSync.Heroku]: AppConnection.Heroku,
[SecretSync.Render]: AppConnection.Render,
[SecretSync.Flyio]: AppConnection.Flyio,
[SecretSync.GitLab]: AppConnection.Gitlab,
[SecretSync.CloudflarePages]: AppConnection.Cloudflare
};
@@ -26,5 +26,6 @@ export enum AppConnection {
Heroku = "heroku",
Render = "render",
Flyio = "flyio",
Gitlab = "gitlab",
Cloudflare = "cloudflare"
}
@@ -0,0 +1,2 @@
export * from "./queries";
export * from "./types";
@@ -0,0 +1,64 @@
import { useQuery, UseQueryOptions } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { appConnectionKeys } from "../queries";
import { TGitLabGroup, TGitLabProject } from "./types";
const gitlabConnectionKeys = {
all: [...appConnectionKeys.all, "gitlab"] as const,
listProjects: (connectionId: string) =>
[...gitlabConnectionKeys.all, "projects", connectionId] as const,
listGroups: (connectionId: string) =>
[...gitlabConnectionKeys.all, "groups", connectionId] as const
};
export const useGitlabConnectionListProjects = (
connectionId: string,
options?: Omit<
UseQueryOptions<
TGitLabProject[],
unknown,
TGitLabProject[],
ReturnType<typeof gitlabConnectionKeys.listProjects>
>,
"queryKey" | "queryFn"
>
) => {
return useQuery({
queryKey: gitlabConnectionKeys.listProjects(connectionId),
queryFn: async () => {
const { data } = await apiRequest.get<TGitLabProject[]>(
`/api/v1/app-connections/gitlab/${connectionId}/projects`
);
return data;
},
...options
});
};
export const useGitlabConnectionListGroups = (
connectionId: string,
options?: Omit<
UseQueryOptions<
TGitLabGroup[],
unknown,
TGitLabGroup[],
ReturnType<typeof gitlabConnectionKeys.listGroups>
>,
"queryKey" | "queryFn"
>
) => {
return useQuery({
queryKey: gitlabConnectionKeys.listGroups(connectionId),
queryFn: async () => {
const { data } = await apiRequest.get<TGitLabGroup[]>(
`/api/v1/app-connections/gitlab/${connectionId}/groups`
);
return data;
},
...options
});
};
@@ -0,0 +1,14 @@
export type TGitLabProject = {
id: string;
name: string;
};
export type TGitLabGroup = {
id: string;
name: string;
};
export enum GitLabAccessTokenType {
Personal = "personal",
Project = "project"
}
@@ -123,6 +123,11 @@ export type TFlyioConnectionOption = TAppConnectionOptionBase & {
app: AppConnection.Flyio;
};
export type TGitlabConnectionOption = TAppConnectionOptionBase & {
app: AppConnection.Gitlab;
oauthClientId?: string;
};
export type TCloudflareConnectionOption = TAppConnectionOptionBase & {
app: AppConnection.Cloudflare;
};
@@ -153,6 +158,7 @@ export type TAppConnectionOption =
| THerokuConnectionOption
| TRenderConnectionOption
| TFlyioConnectionOption
| TGitlabConnectionOption
| TCloudflareConnectionOption;
export type TAppConnectionOptionMap = {
@@ -183,5 +189,6 @@ export type TAppConnectionOptionMap = {
[AppConnection.Heroku]: THerokuConnectionOption;
[AppConnection.Render]: TRenderConnectionOption;
[AppConnection.Flyio]: TFlyioConnectionOption;
[AppConnection.Gitlab]: TGitlabConnectionOption;
[AppConnection.Cloudflare]: TCloudflareConnectionOption;
};
@@ -0,0 +1,27 @@
import { AppConnection } from "@app/hooks/api/appConnections/enums";
import { TRootAppConnection } from "@app/hooks/api/appConnections/types/root-connection";
import { GitLabAccessTokenType } from "../gitlab";
export enum GitLabConnectionMethod {
AccessToken = "access-token",
OAuth = "oauth"
}
export type TGitLabConnection = TRootAppConnection & { app: AppConnection.Gitlab } & (
| {
method: GitLabConnectionMethod.AccessToken;
credentials: {
instanceUrl?: string;
accessToken: string;
accessTokenType: GitLabAccessTokenType;
};
}
| {
method: GitLabConnectionMethod.OAuth;
credentials: {
code: string;
instanceUrl?: string;
};
}
);
@@ -14,6 +14,7 @@ import { TFlyioConnection } from "./flyio-connection";
import { TGcpConnection } from "./gcp-connection";
import { TGitHubConnection } from "./github-connection";
import { TGitHubRadarConnection } from "./github-radar-connection";
import { TGitLabConnection } from "./gitlab-connection";
import { THCVaultConnection } from "./hc-vault-connection";
import { THerokuConnection } from "./heroku-connection";
import { THumanitecConnection } from "./humanitec-connection";
@@ -37,11 +38,13 @@ export * from "./azure-client-secrets-connection";
export * from "./azure-devops-connection";
export * from "./azure-key-vault-connection";
export * from "./camunda-connection";
export * from "./cloudflare-connection";
export * from "./databricks-connection";
export * from "./flyio-connection";
export * from "./gcp-connection";
export * from "./github-connection";
export * from "./github-radar-connection";
export * from "./gitlab-connection";
export * from "./hc-vault-connection";
export * from "./heroku-connection";
export * from "./humanitec-connection";
@@ -56,7 +59,6 @@ export * from "./teamcity-connection";
export * from "./terraform-cloud-connection";
export * from "./vercel-connection";
export * from "./windmill-connection";
export * from "./cloudflare-connection";
export type TAppConnection =
| TAwsConnection
@@ -86,6 +88,7 @@ export type TAppConnection =
| THerokuConnection
| TRenderConnection
| TFlyioConnection
| TGitLabConnection
| TCloudflareConnection;
export type TAvailableAppConnection = Pick<TAppConnection, "name" | "id">;
@@ -141,5 +144,6 @@ export type TAppConnectionMap = {
[AppConnection.Heroku]: THerokuConnection;
[AppConnection.Render]: TRenderConnection;
[AppConnection.Flyio]: TFlyioConnection;
[AppConnection.Gitlab]: TGitLabConnection;
[AppConnection.Cloudflare]: TCloudflareConnection;
};
@@ -19,6 +19,7 @@ export enum SecretSync {
Heroku = "heroku",
Render = "render",
Flyio = "flyio",
GitLab = "gitlab",
CloudflarePages = "cloudflare-pages"
}
@@ -0,0 +1,36 @@
import { AppConnection } from "@app/hooks/api/appConnections/enums";
import { SecretSync } from "@app/hooks/api/secretSyncs";
import { TRootSecretSync } from "@app/hooks/api/secretSyncs/types/root-sync";
export enum GitLabSyncScope {
Project = "project",
Group = "group"
}
export type TGitLabSync = TRootSecretSync & {
destination: SecretSync.GitLab;
destinationConfig:
| {
scope: GitLabSyncScope.Project;
projectId: string;
projectName: string;
targetEnvironment?: string;
shouldProtectSecrets?: boolean;
shouldMaskSecrets?: boolean;
shouldHideSecrets?: boolean;
}
| {
scope: GitLabSyncScope.Group;
groupId: string;
groupName: string;
targetEnvironment?: string;
shouldProtectSecrets?: boolean;
shouldMaskSecrets?: boolean;
shouldHideSecrets?: boolean;
};
connection: {
app: AppConnection.Gitlab;
name: string;
id: string;
};
};
@@ -14,6 +14,7 @@ import { TDatabricksSync } from "./databricks-sync";
import { TFlyioSync } from "./flyio-sync";
import { TGcpSync } from "./gcp-sync";
import { TGitHubSync } from "./github-sync";
import { TGitLabSync } from "./gitlab-sync";
import { THCVaultSync } from "./hc-vault-sync";
import { THerokuSync } from "./heroku-sync";
import { THumanitecSync } from "./humanitec-sync";
@@ -51,6 +52,7 @@ export type TSecretSync =
| THerokuSync
| TRenderSync
| TFlyioSync
| TGitLabSync
| TCloudflarePagesSync;
export type TListSecretSyncs = { secretSyncs: TSecretSync[] };
@@ -23,6 +23,7 @@ import { FlyioConnectionForm } from "./FlyioConnectionForm";
import { GcpConnectionForm } from "./GcpConnectionForm";
import { GitHubConnectionForm } from "./GitHubConnectionForm";
import { GitHubRadarConnectionForm } from "./GitHubRadarConnectionForm";
import { GitLabConnectionForm } from "./GitLabConnectionForm";
import { HCVaultConnectionForm } from "./HCVaultConnectionForm";
import { HerokuConnectionForm } from "./HerokuAppConnectionForm";
import { HumanitecConnectionForm } from "./HumanitecConnectionForm";
@@ -129,6 +130,8 @@ const CreateForm = ({ app, onComplete }: CreateFormProps) => {
return <RenderConnectionForm onSubmit={onSubmit} />;
case AppConnection.Flyio:
return <FlyioConnectionForm onSubmit={onSubmit} />;
case AppConnection.Gitlab:
return <GitLabConnectionForm onSubmit={onSubmit} />;
case AppConnection.Cloudflare:
return <CloudflareConnectionForm onSubmit={onSubmit} />;
default:
@@ -221,6 +224,8 @@ const UpdateForm = ({ appConnection, onComplete }: UpdateFormProps) => {
return <RenderConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;
case AppConnection.Flyio:
return <FlyioConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;
case AppConnection.Gitlab:
return <GitLabConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;
case AppConnection.Cloudflare:
return <CloudflareConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;
default:
@@ -0,0 +1,335 @@
/* eslint-disable no-case-declarations */
/* eslint-disable no-nested-ternary */
import crypto from "crypto";
import { useState } from "react";
import { Controller, FormProvider, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import {
Button,
FormControl,
Input,
ModalClose,
SecretInput,
Select,
SelectItem
} from "@app/components/v2";
import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";
import { isInfisicalCloud } from "@app/helpers/platform";
import { useGetAppConnectionOption } from "@app/hooks/api/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
import { GitLabAccessTokenType } from "@app/hooks/api/appConnections/gitlab";
import {
GitLabConnectionMethod,
TGitLabConnection
} from "@app/hooks/api/appConnections/types/gitlab-connection";
import {
genericAppConnectionFieldsSchema,
GenericAppConnectionsFields
} from "./GenericAppConnectionFields";
type Props = {
appConnection?: TGitLabConnection;
onSubmit: (formData: FormData) => Promise<void>;
};
const formSchema = z.discriminatedUnion("method", [
genericAppConnectionFieldsSchema.extend({
app: z.literal(AppConnection.Gitlab),
method: z.literal(GitLabConnectionMethod.AccessToken),
credentials: z.object({
accessToken: z.string().min(1, "Access token is required"),
accessTokenType: z.nativeEnum(GitLabAccessTokenType),
instanceUrl: z
.string()
.trim()
.transform((value) => value || undefined)
.refine((value) => (!value ? true : z.string().url().safeParse(value).success), {
message: "Invalid instance URL"
})
.optional()
})
}),
genericAppConnectionFieldsSchema.extend({
app: z.literal(AppConnection.Gitlab),
method: z.literal(GitLabConnectionMethod.OAuth),
credentials: z.object({
code: z.string().min(1, "Code is required"),
instanceUrl: z
.string()
.trim()
.transform((value) => value || undefined)
.refine((value) => (!value ? true : z.string().url().safeParse(value).success), {
message: "Invalid instance URL"
})
.optional()
})
})
]);
type FormData = z.infer<typeof formSchema>;
export const GitLabConnectionForm = ({ appConnection, onSubmit: formSubmit }: Props) => {
const isUpdate = Boolean(appConnection);
const [isRedirecting, setIsRedirecting] = useState(false);
const {
option: { oauthClientId },
isLoading
} = useGetAppConnectionOption(AppConnection.Gitlab);
const form = useForm<FormData>({
resolver: zodResolver(formSchema),
defaultValues:
appConnection?.method === GitLabConnectionMethod.OAuth
? { ...appConnection, credentials: { code: "custom" } }
: (appConnection ??
({
app: AppConnection.Gitlab,
method: GitLabConnectionMethod.AccessToken,
credentials: {
accessToken: "",
accessTokenType: GitLabAccessTokenType.Personal,
instanceUrl: ""
}
} as FormData))
});
const {
handleSubmit,
control,
watch,
setValue,
formState: { isSubmitting, isDirty }
} = form;
const selectedMethod = watch("method");
const gitLabURL = watch("credentials.instanceUrl");
const onSubmit = async (formData: FormData) => {
try {
switch (formData.method) {
case GitLabConnectionMethod.AccessToken:
await formSubmit(formData);
break;
case GitLabConnectionMethod.OAuth:
if (!oauthClientId) {
return;
}
setIsRedirecting(true);
// Generate CSRF token
const state = crypto.randomBytes(16).toString("hex");
// Store state and form data for callback
localStorage.setItem("latestCSRFToken", state);
localStorage.setItem(
"gitlabConnectionFormData",
JSON.stringify({
...formData,
connectionId: appConnection?.id,
isUpdate
})
);
// Redirect to Gitlab OAuth
const baseURL =
gitLabURL && (gitLabURL as string)?.trim() !== ""
? (gitLabURL as string)?.trim()
: "https://gitlab.com";
const oauthUrl = new URL(`${baseURL}/oauth/authorize`);
oauthUrl.searchParams.set("client_id", oauthClientId);
oauthUrl.searchParams.set(
"redirect_uri",
`${window.location.origin}/organization/app-connections/gitlab/oauth/callback`
);
oauthUrl.searchParams.set("response_type", "code");
oauthUrl.searchParams.set("state", state);
window.location.assign(oauthUrl.toString());
break;
default:
throw new Error("Unhandled GitLab Connection method");
}
} catch (error) {
console.error("Error handling form submission:", error);
setIsRedirecting(false);
}
};
let isMissingConfig: boolean;
switch (selectedMethod) {
case GitLabConnectionMethod.OAuth:
isMissingConfig = !oauthClientId;
break;
case GitLabConnectionMethod.AccessToken:
isMissingConfig = false;
break;
default:
throw new Error(`Unhandled GitLab Connection method: ${selectedMethod}`);
}
const methodDetails = getAppConnectionMethodDetails(selectedMethod);
return (
<FormProvider {...form}>
<form onSubmit={handleSubmit(onSubmit)}>
{!isUpdate && <GenericAppConnectionsFields />}
<Controller
name="credentials.instanceUrl"
control={control}
render={({ field: { value, onChange }, fieldState: { error } }) => (
<FormControl
label="Self-hosted URL (optional)"
errorText={error?.message}
isError={Boolean(error?.message)}
tooltipText="Will default to GitLab Cloud if not specified."
>
<Input
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder="https://gitlab.com"
/>
</FormControl>
)}
/>
<Controller
name="method"
control={control}
render={({ field: { value, onChange }, fieldState: { error } }) => (
<FormControl
tooltipText={`The method you would like to use to connect with ${
APP_CONNECTION_MAP[AppConnection.Gitlab].name
}. This field cannot be changed after creation.`}
errorText={
!isLoading && isMissingConfig && selectedMethod === GitLabConnectionMethod.OAuth
? `Environment variables have not been configured. ${
isInfisicalCloud()
? "Please contact Infisical."
: `See Docs to configure GitLab ${methodDetails.name} Connections.`
}`
: error?.message
}
isError={Boolean(error?.message) || isMissingConfig}
label="Method"
>
<Select
isDisabled={isUpdate}
value={value}
onValueChange={(val) => {
onChange(val);
if (val === GitLabConnectionMethod.OAuth) {
setValue("credentials.code", "custom");
}
}}
className="w-full border border-mineshaft-500"
position="popper"
dropdownContainerClassName="max-w-none"
>
{Object.values(GitLabConnectionMethod).map((method) => {
return (
<SelectItem value={method} key={method}>
{getAppConnectionMethodDetails(method).name}{" "}
{method === GitLabConnectionMethod.AccessToken ? " (Recommended)" : ""}
</SelectItem>
);
})}
</Select>
</FormControl>
)}
/>
{selectedMethod === GitLabConnectionMethod.AccessToken && (
<>
<Controller
name="credentials.accessTokenType"
control={control}
render={({ field: { value, onChange }, fieldState: { error } }) => (
<FormControl
errorText={error?.message}
isError={Boolean(error?.message)}
label="Access Token Type"
>
<Select
isDisabled={isUpdate}
value={value}
onValueChange={(val) => {
onChange(val);
if (val === GitLabConnectionMethod.OAuth) {
setValue("credentials.code", "custom");
}
}}
className="w-full border border-mineshaft-500"
position="popper"
dropdownContainerClassName="max-w-none"
>
{Object.values(GitLabAccessTokenType).map((method) => {
return (
<SelectItem value={method} key={method}>
{method.charAt(0).toUpperCase() + method.slice(1)} Access Token
</SelectItem>
);
})}
</Select>
</FormControl>
)}
/>
<Controller
name="credentials.accessToken"
control={control}
render={({ field: { value, onChange }, fieldState: { error } }) => (
<FormControl
label="Access Token"
errorText={error?.message}
isError={Boolean(error?.message)}
tooltipText="Your GitLab Access Token"
>
<SecretInput
containerClassName="text-gray-400 group-focus-within:!border-primary-400/50 border border-mineshaft-500 bg-mineshaft-900 px-2.5 py-1.5"
value={value}
onChange={(e) => onChange(e.target.value)}
/>
</FormControl>
)}
/>
</>
)}
<div className="mt-8 flex items-center">
<Button
className="mr-4"
size="sm"
type="submit"
colorSchema="secondary"
isLoading={isSubmitting || isRedirecting}
isDisabled={
isSubmitting ||
(!isUpdate && !isDirty) ||
(isMissingConfig && selectedMethod === GitLabConnectionMethod.OAuth) ||
isRedirecting
}
>
{isRedirecting && selectedMethod === GitLabConnectionMethod.OAuth
? "Redirecting to GitLab..."
: isUpdate
? "Reconnect to GitLab"
: "Connect to GitLab"}
</Button>
<ModalClose asChild>
<Button colorSchema="secondary" variant="plain">
Cancel
</Button>
</ModalClose>
</div>
</form>
</FormProvider>
);
};
@@ -11,12 +11,14 @@ import {
AzureDevOpsConnectionMethod,
AzureKeyVaultConnectionMethod,
GitHubConnectionMethod,
GitLabConnectionMethod,
TAzureAppConfigurationConnection,
TAzureClientSecretsConnection,
TAzureDevOpsConnection,
TAzureKeyVaultConnection,
TGitHubConnection,
TGitHubRadarConnection,
TGitLabConnection,
useCreateAppConnection,
useUpdateAppConnection
} from "@app/hooks/api/appConnections";
@@ -25,6 +27,7 @@ import { AppConnection } from "@app/hooks/api/appConnections/enums";
type BaseFormData = {
returnUrl?: string;
connectionId?: string;
isUpdate?: boolean;
};
type GithubFormData = BaseFormData & Pick<TGitHubConnection, "name" | "method" | "description">;
@@ -32,6 +35,8 @@ type GithubFormData = BaseFormData & Pick<TGitHubConnection, "name" | "method" |
type GithubRadarFormData = BaseFormData &
Pick<TGitHubRadarConnection, "name" | "method" | "description">;
type GitLabFormData = BaseFormData & Pick<TGitLabConnection, "name" | "method" | "description">;
type AzureKeyVaultFormData = BaseFormData &
Pick<TAzureKeyVaultConnection, "name" | "method" | "description"> &
Pick<TAzureKeyVaultConnection["credentials"], "tenantId">;
@@ -60,6 +65,7 @@ type AzureDevOpsFormData = BaseFormData &
type FormDataMap = {
[AppConnection.GitHub]: GithubFormData & { app: AppConnection.GitHub };
[AppConnection.GitHubRadar]: GithubRadarFormData & { app: AppConnection.GitHubRadar };
[AppConnection.Gitlab]: GitLabFormData & { app: AppConnection.Gitlab };
[AppConnection.AzureKeyVault]: AzureKeyVaultFormData & { app: AppConnection.AzureKeyVault };
[AppConnection.AzureAppConfiguration]: AzureAppConfigurationFormData & {
app: AppConnection.AzureAppConfiguration;
@@ -75,6 +81,7 @@ type FormDataMap = {
const formDataStorageFieldMap: Partial<Record<AppConnection, string>> = {
[AppConnection.GitHub]: "githubConnectionFormData",
[AppConnection.GitHubRadar]: "githubRadarConnectionFormData",
[AppConnection.Gitlab]: "gitlabConnectionFormData",
[AppConnection.AzureKeyVault]: "azureKeyVaultConnectionFormData",
[AppConnection.AzureAppConfiguration]: "azureAppConfigurationConnectionFormData",
[AppConnection.AzureClientSecrets]: "azureClientSecretsConnectionFormData",
@@ -133,6 +140,57 @@ export const OAuthCallbackPage = () => {
}
};
const handleGitlab = useCallback(async () => {
const formData = getFormData(AppConnection.Gitlab);
if (formData === null) return null;
clearState(AppConnection.Gitlab);
const { connectionId, name, description, returnUrl, isUpdate } = formData;
try {
if (isUpdate && connectionId) {
await updateAppConnection.mutateAsync({
app: AppConnection.Gitlab,
connectionId,
credentials: {
code: code as string
}
});
} else {
await createAppConnection.mutateAsync({
app: AppConnection.Gitlab,
name,
description,
method: GitLabConnectionMethod.OAuth,
credentials: {
code: code as string
}
});
}
navigate({
to: returnUrl ?? "/organization/app-connections"
});
return {
connectionId,
returnUrl,
appConnectionName: formData.app
};
} catch (err: any) {
createNotification({
title: `Failed to ${connectionId ? "update" : "add"} GitLab Connection`,
text: err?.message,
type: "error"
});
navigate({
to: returnUrl ?? "/organization/app-connections"
});
return null;
}
}, []);
const handleAzureKeyVault = useCallback(async () => {
const formData = getFormData(AppConnection.AzureKeyVault);
if (formData === null) return null;
@@ -463,6 +521,8 @@ export const OAuthCallbackPage = () => {
data = await handleGithub();
} else if (appConnection === AppConnection.GitHubRadar) {
data = await handleGithubRadar();
} else if (appConnection === AppConnection.Gitlab) {
data = await handleGitlab();
} else if (appConnection === AppConnection.AzureKeyVault) {
data = await handleAzureKeyVault();
} else if (appConnection === AppConnection.AzureAppConfiguration) {
@@ -0,0 +1,14 @@
import { TGitLabSync } from "@app/hooks/api/secretSyncs/types/gitlab-sync";
import { getSecretSyncDestinationColValues } from "../helpers";
import { SecretSyncTableCell } from "../SecretSyncTableCell";
type Props = {
secretSync: TGitLabSync;
};
export const GitLabSyncDestinationCol = ({ secretSync }: Props) => {
const { primaryText, secondaryText } = getSecretSyncDestinationColValues(secretSync);
return <SecretSyncTableCell primaryText={primaryText} secondaryText={secondaryText} />;
};
@@ -12,6 +12,7 @@ import { DatabricksSyncDestinationCol } from "./DatabricksSyncDestinationCol";
import { FlyioSyncDestinationCol } from "./FlyioSyncDestinationCol";
import { GcpSyncDestinationCol } from "./GcpSyncDestinationCol";
import { GitHubSyncDestinationCol } from "./GitHubSyncDestinationCol";
import { GitLabSyncDestinationCol } from "./GitLabSyncDestinationCol";
import { HCVaultSyncDestinationCol } from "./HCVaultSyncDestinationCol";
import { HerokuSyncDestinationCol } from "./HerokuSyncDestinationCol";
import { HumanitecSyncDestinationCol } from "./HumanitecSyncDestinationCol";
@@ -68,6 +69,8 @@ export const SecretSyncDestinationCol = ({ secretSync }: Props) => {
return <RenderSyncDestinationCol secretSync={secretSync} />;
case SecretSync.Flyio:
return <FlyioSyncDestinationCol secretSync={secretSync} />;
case SecretSync.GitLab:
return <GitLabSyncDestinationCol secretSync={secretSync} />;
case SecretSync.CloudflarePages:
return <CloudflarePagesSyncDestinationCol secretSync={secretSync} />;
default:
@@ -5,6 +5,7 @@ import {
GitHubSyncScope,
GitHubSyncVisibility
} from "@app/hooks/api/secretSyncs/types/github-sync";
import { GitLabSyncScope } from "@app/hooks/api/secretSyncs/types/gitlab-sync";
import { HumanitecSyncScope } from "@app/hooks/api/secretSyncs/types/humanitec-sync";
// This functional ensures parity across what is displayed in the destination column
@@ -128,6 +129,17 @@ export const getSecretSyncDestinationColValues = (secretSync: TSecretSync) => {
primaryText = destinationConfig.appId;
secondaryText = "App ID";
break;
case SecretSync.GitLab:
if (destinationConfig.scope === GitLabSyncScope.Project) {
primaryText = destinationConfig.projectName;
secondaryText = destinationConfig.projectId;
} else if (destinationConfig.scope === GitLabSyncScope.Group) {
primaryText = destinationConfig.groupName;
secondaryText = destinationConfig.groupId;
} else {
throw new Error(`Unhandled GitLab Scope Destination Col Values ${destination}`);
}
break;
case SecretSync.CloudflarePages:
primaryText = destinationConfig.projectName;
secondaryText = destinationConfig.environment;
@@ -0,0 +1,50 @@
import { GenericFieldLabel } from "@app/components/secret-syncs";
import { GitLabSyncScope, TGitLabSync } from "@app/hooks/api/secretSyncs/types/gitlab-sync";
type Props = {
secretSync: TGitLabSync;
};
export const GitLabSyncDestinationSection = ({ secretSync }: Props) => {
const {
destinationConfig: {
targetEnvironment,
shouldProtectSecrets,
shouldMaskSecrets,
shouldHideSecrets
}
} = secretSync;
return (
<>
{secretSync.destinationConfig.scope === GitLabSyncScope.Project && (
<>
<GenericFieldLabel label="Project Name">
{secretSync.destinationConfig.projectName}
</GenericFieldLabel>
<GenericFieldLabel label="Project ID">
{secretSync.destinationConfig.projectId}
</GenericFieldLabel>
</>
)}
{secretSync.destinationConfig.scope === GitLabSyncScope.Group && (
<>
<GenericFieldLabel label="Group Name">
{secretSync.destinationConfig.groupName}
</GenericFieldLabel>
<GenericFieldLabel label="Group ID">
{secretSync.destinationConfig.groupId}
</GenericFieldLabel>
</>
)}
{targetEnvironment && (
<GenericFieldLabel label="Environment">{targetEnvironment}</GenericFieldLabel>
)}
<GenericFieldLabel label="Protect Secrets">
{shouldProtectSecrets ? "Yes" : "No"}
</GenericFieldLabel>
<GenericFieldLabel label="Mask Secrets">{shouldMaskSecrets ? "Yes" : "No"}</GenericFieldLabel>
<GenericFieldLabel label="Hide Secrets">{shouldHideSecrets ? "Yes" : "No"}</GenericFieldLabel>
</>
);
};
@@ -23,6 +23,7 @@ import { DatabricksSyncDestinationSection } from "./DatabricksSyncDestinationSec
import { FlyioSyncDestinationSection } from "./FlyioSyncDestinationSection";
import { GcpSyncDestinationSection } from "./GcpSyncDestinationSection";
import { GitHubSyncDestinationSection } from "./GitHubSyncDestinationSection";
import { GitLabSyncDestinationSection } from "./GitLabSyncDestinationSection";
import { HCVaultSyncDestinationSection } from "./HCVaultSyncDestinationSection";
import { HerokuSyncDestinationSection } from "./HerokuSyncDestinationSection";
import { HumanitecSyncDestinationSection } from "./HumanitecSyncDestinationSection";
@@ -107,6 +108,9 @@ export const SecretSyncDestinationSection = ({ secretSync, onEditDestination }:
case SecretSync.Flyio:
DestinationComponents = <FlyioSyncDestinationSection secretSync={secretSync} />;
break;
case SecretSync.GitLab:
DestinationComponents = <GitLabSyncDestinationSection secretSync={secretSync} />;
break;
case SecretSync.CloudflarePages:
DestinationComponents = <CloudflarePagesSyncDestinationSection secretSync={secretSync} />;
break;
@@ -58,6 +58,7 @@ export const SecretSyncOptionsSection = ({ secretSync, onEditOptions }: Props) =
case SecretSync.Heroku:
case SecretSync.Render:
case SecretSync.Flyio:
case SecretSync.GitLab:
case SecretSync.CloudflarePages:
AdditionalSyncOptionsComponent = null;
break;
@@ -3,11 +3,13 @@ import { useNavigate, useSearch } from "@tanstack/react-router";
import { ROUTE_PATHS } from "@app/const/routes";
import { useWorkspace } from "@app/context";
import { useAuthorizeIntegration } from "@app/hooks/api";
import { useCreateAppConnection, useUpdateAppConnection } from "@app/hooks/api/appConnections";
import { GitLabConnectionMethod } from "@app/hooks/api/appConnections/types/gitlab-connection";
export const GitLabOAuthCallbackPage = () => {
const navigate = useNavigate();
const { mutateAsync } = useAuthorizeIntegration();
const { mutateAsync: createAppConnection } = useCreateAppConnection();
const { mutateAsync: updateAppConnection } = useUpdateAppConnection();
const { code, state } = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.GitlabOauthCallbackPage.id
@@ -17,37 +19,82 @@ export const GitLabOAuthCallbackPage = () => {
useEffect(() => {
(async () => {
try {
// validate state
const [csrfToken, url] = (state as string).split("|", 2);
// Validate CSRF state token
const [csrfToken] = (state as string).split("|", 2);
const storedState = localStorage.getItem("latestCSRFToken");
if (csrfToken !== storedState) {
console.error("CSRF token mismatch");
navigate({
to: "/organization/app-connections",
search: { error: "invalid_state" }
});
return;
}
if (csrfToken !== localStorage.getItem("latestCSRFToken")) return;
localStorage.removeItem("latestCSRFToken");
const integrationAuth = await mutateAsync({
workspaceId: currentWorkspace.id,
code: code as string,
integration: "gitlab",
...(url === ""
? {}
: {
url
})
});
const storedFormData = localStorage.getItem("gitlabConnectionFormData");
if (!storedFormData) {
console.error("No stored form data found");
navigate({
to: "/organization/app-connections",
search: { error: "missing_form_data" }
});
return;
}
const formData = JSON.parse(storedFormData);
localStorage.removeItem("gitlabConnectionFormData");
// Prepare app connection data with OAuth credentials
const connectionData = {
...formData,
method: GitLabConnectionMethod.OAuth,
credentials: {
code: code as string
}
};
let appConnection;
// Create or update app connection
if (formData.isUpdate && formData.connectionId) {
appConnection = await updateAppConnection({
connectionId: formData.connectionId,
...connectionData
});
} else {
appConnection = await createAppConnection({
workspaceId: currentWorkspace.id,
...connectionData
});
}
// Navigate to success page or app connections list
navigate({
to: "/secret-manager/$projectId/integrations/gitlab/create",
params: {
projectId: currentWorkspace.id
},
to: "/organization/app-connections",
search: {
integrationAuthId: integrationAuth.id
success: formData.isUpdate ? "connection_updated" : "connection_created",
connectionId: appConnection.id
}
});
} catch (err) {
console.error(err);
console.error("Error handling GitLab OAuth callback:", err);
navigate({
to: "/organization/app-connections",
search: { error: "connection_failed" }
});
}
})();
}, []);
}, [code, state, navigate, createAppConnection, updateAppConnection, currentWorkspace.id]);
return <div />;
return (
<div className="flex h-screen items-center justify-center">
<div className="text-center">
<div className="mx-auto mb-4 h-8 w-8 animate-spin rounded-full border-b-2 border-primary" />
<p className="text-gray-600">Connecting to GitLab...</p>
</div>
</div>
);
};