deconflict merge

This commit is contained in:
Scott Wilson
2025-06-20 12:33:37 -07:00
137 changed files with 2735 additions and 183 deletions
@@ -26,7 +26,7 @@ export const TtlFormLabel = ({ label }: { label: string }) => (
<FontAwesomeIcon
icon={faQuestionCircle}
size="sm"
className="relative bottom-1 right-1"
className="relative bottom-px right-1"
/>
</Tooltip>
}
@@ -0,0 +1,76 @@
import { Controller, useFormContext, useWatch } from "react-hook-form";
import { SingleValue } from "react-select";
import { faCircleInfo } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { SecretSyncConnectionField } from "@app/components/secret-syncs/forms/SecretSyncConnectionField";
import { FilterableSelect, FormControl, Tooltip } from "@app/components/v2";
import { THerokuApp } from "@app/hooks/api/appConnections/heroku";
import { useHerokuConnectionListApps } from "@app/hooks/api/appConnections/heroku/queries";
import { SecretSync } from "@app/hooks/api/secretSyncs";
import { TSecretSyncForm } from "../schemas";
export const HerokuSyncFields = () => {
const { control, setValue } = useFormContext<
TSecretSyncForm & { destination: SecretSync.Heroku }
>();
const connectionId = useWatch({ name: "connection.id", control });
const { data: apps, isLoading: isAppsLoading } = useHerokuConnectionListApps(connectionId, {
enabled: Boolean(connectionId)
});
return (
<>
<SecretSyncConnectionField
onChange={() => {
setValue("destinationConfig.app", "");
setValue("destinationConfig.appName", "");
}}
/>
<Controller
name="destinationConfig.app"
control={control}
render={({ field: { value, onChange }, fieldState: { error } }) => (
<FormControl
isError={Boolean(error)}
errorText={error?.message}
label="App"
helperText={
<Tooltip
className="max-w-md"
content="Ensure the app exists in the connection's Heroku instance URL."
>
<div>
<span>Don&#39;t see the app you&#39;re looking for?</span>{" "}
<FontAwesomeIcon icon={faCircleInfo} className="text-mineshaft-400" />
</div>
</Tooltip>
}
>
<FilterableSelect
menuPlacement="top"
isLoading={isAppsLoading && Boolean(connectionId)}
isDisabled={!connectionId}
value={apps?.find((app) => app.id === value) ?? null}
onChange={(option) => {
onChange((option as SingleValue<THerokuApp>)?.id ?? "");
setValue(
"destinationConfig.appName",
(option as SingleValue<THerokuApp>)?.name ?? ""
);
}}
options={apps}
placeholder="Select an app..."
getOptionLabel={(option) => option.name}
getOptionValue={(option) => option.id}
/>
</FormControl>
)}
/>
</>
);
};
@@ -15,6 +15,7 @@ import { FlyioSyncFields } from "./FlyioSyncFields";
import { GcpSyncFields } from "./GcpSyncFields";
import { GitHubSyncFields } from "./GitHubSyncFields";
import { HCVaultSyncFields } from "./HCVaultSyncFields";
import { HerokuSyncFields } from "./HerokuSyncFields";
import { HumanitecSyncFields } from "./HumanitecSyncFields";
import { OCIVaultSyncFields } from "./OCIVaultSyncFields";
import { RenderSyncFields } from "./RenderSyncFields";
@@ -63,6 +64,8 @@ export const SecretSyncDestinationFields = () => {
return <OCIVaultSyncFields />;
case SecretSync.OnePass:
return <OnePassSyncFields />;
case SecretSync.Heroku:
return <HerokuSyncFields />;
case SecretSync.Render:
return <RenderSyncFields />;
case SecretSync.Flyio:
@@ -52,6 +52,7 @@ export const SecretSyncOptionsFields = ({ hideInitialSync }: Props) => {
case SecretSync.TeamCity:
case SecretSync.OnePass:
case SecretSync.OCIVault:
case SecretSync.Heroku:
case SecretSync.Render:
case SecretSync.Flyio:
AdditionalSyncOptionsFieldsComponent = null;
@@ -0,0 +1,18 @@
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";
export const HerokuSyncReviewFields = () => {
const { watch } = useFormContext<TSecretSyncForm & { destination: SecretSync.Heroku }>();
const appName = watch("destinationConfig.appName");
const appId = watch("destinationConfig.app");
return (
<>
<GenericFieldLabel label="App">{appName}</GenericFieldLabel>
<GenericFieldLabel label="App ID">{appId}</GenericFieldLabel>
</>
);
};
@@ -24,6 +24,7 @@ import { FlyioSyncReviewFields } from "./FlyioSyncReviewFields";
import { GcpSyncReviewFields } from "./GcpSyncReviewFields";
import { GitHubSyncReviewFields } from "./GitHubSyncReviewFields";
import { HCVaultSyncReviewFields } from "./HCVaultSyncReviewFields";
import { HerokuSyncReviewFields } from "./HerokuSyncReviewFields";
import { HumanitecSyncReviewFields } from "./HumanitecSyncReviewFields";
import { OCIVaultSyncReviewFields } from "./OCIVaultSyncReviewFields";
import { OnePassSyncReviewFields } from "./OnePassSyncReviewFields";
@@ -106,6 +107,9 @@ export const SecretSyncReviewFields = () => {
case SecretSync.OnePass:
DestinationFieldsComponent = <OnePassSyncReviewFields />;
break;
case SecretSync.Heroku:
DestinationFieldsComponent = <HerokuSyncReviewFields />;
break;
case SecretSync.Render:
DestinationFieldsComponent = <RenderSyncReviewFields />;
break;
@@ -0,0 +1,14 @@
import { z } from "zod";
import { BaseSecretSyncSchema } from "@app/components/secret-syncs/forms/schemas/base-secret-sync-schema";
import { SecretSync } from "@app/hooks/api/secretSyncs";
export const HerokuSyncDestinationSchema = BaseSecretSyncSchema().merge(
z.object({
destination: z.literal(SecretSync.Heroku),
destinationConfig: z.object({
app: z.string().trim().min(1, "App ID required"),
appName: z.string().trim().min(1, "App name required")
})
})
);
@@ -12,6 +12,7 @@ import { FlyioSyncDestinationSchema } from "./flyio-sync-destination-schema";
import { GcpSyncDestinationSchema } from "./gcp-sync-destination-schema";
import { GitHubSyncDestinationSchema } from "./github-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";
import { OCIVaultSyncDestinationSchema } from "./oci-vault-sync-destination-schema";
import { RenderSyncDestinationSchema } from "./render-sync-destination-schema";
@@ -38,6 +39,7 @@ const SecretSyncUnionSchema = z.discriminatedUnion("destination", [
TeamCitySyncDestinationSchema,
OCIVaultSyncDestinationSchema,
OnePassSyncDestinationSchema,
HerokuSyncDestinationSchema,
RenderSyncDestinationSchema,
FlyioSyncDestinationSchema
]);
@@ -16,7 +16,7 @@ export interface IsCliLoginSuccessful {
loginResponse?: {
email: string;
privateKey: string;
JWTToken: string;
JTWToken: string;
};
success: boolean;
}
@@ -131,7 +131,7 @@ const attemptLogin = async ({
loginResponse: {
email,
privateKey,
JWTToken: token
JTWToken: token
},
success: true
});
@@ -14,7 +14,7 @@ interface IsMfaLoginSuccessful {
success: boolean;
loginResponse: {
privateKey: string;
JWTToken: string;
JTWToken: string;
};
}
@@ -95,7 +95,7 @@ const attemptLoginMfa = async ({
success: true,
loginResponse: {
privateKey,
JWTToken: token
JTWToken: token
}
});
} catch (err) {
+5
View File
@@ -37,6 +37,7 @@ import {
VercelConnectionMethod,
WindmillConnectionMethod
} from "@app/hooks/api/appConnections/types";
import { HerokuConnectionMethod } from "@app/hooks/api/appConnections/types/heroku-connection";
import { OCIConnectionMethod } from "@app/hooks/api/appConnections/types/oci-connection";
import { RenderConnectionMethod } from "@app/hooks/api/appConnections/types/render-connection";
@@ -81,6 +82,7 @@ export const APP_CONNECTION_MAP: Record<
[AppConnection.TeamCity]: { name: "TeamCity", image: "TeamCity.png" },
[AppConnection.OCI]: { name: "OCI", image: "Oracle.png", enterprise: true },
[AppConnection.OnePass]: { name: "1Password", image: "1Password.png" },
[AppConnection.Heroku]: { name: "Heroku", image: "Heroku.png" },
[AppConnection.Render]: { name: "Render", image: "Render.png" },
[AppConnection.Flyio]: { name: "Fly.io", image: "Flyio.svg" }
};
@@ -95,6 +97,7 @@ export const getAppConnectionMethodDetails = (method: TAppConnection["method"])
case AzureClientSecretsConnectionMethod.OAuth:
case AzureDevOpsConnectionMethod.OAuth:
case GitHubConnectionMethod.OAuth:
case HerokuConnectionMethod.OAuth:
return { name: "OAuth", icon: faPassport };
case AwsConnectionMethod.AccessKey:
case OCIConnectionMethod.AccessKey:
@@ -129,6 +132,8 @@ export const getAppConnectionMethodDetails = (method: TAppConnection["method"])
return { name: "App Role", icon: faUser };
case LdapConnectionMethod.SimpleBind:
return { name: "Simple Bind", icon: faLink };
case HerokuConnectionMethod.AuthToken:
return { name: "Auth Token", icon: faKey };
case RenderConnectionMethod.ApiKey:
return { name: "API Key", icon: faKey };
default:
+5
View File
@@ -62,6 +62,10 @@ export const SECRET_SYNC_MAP: Record<SecretSync, { name: string; image: string }
name: "1Password",
image: "1Password.png"
},
[SecretSync.Heroku]: {
name: "Heroku",
image: "Heroku.png"
},
[SecretSync.Render]: {
name: "Render",
image: "Render.png"
@@ -90,6 +94,7 @@ export const SECRET_SYNC_CONNECTION_MAP: Record<SecretSync, AppConnection> = {
[SecretSync.TeamCity]: AppConnection.TeamCity,
[SecretSync.OCIVault]: AppConnection.OCI,
[SecretSync.OnePass]: AppConnection.OnePass,
[SecretSync.Heroku]: AppConnection.Heroku,
[SecretSync.Render]: AppConnection.Render,
[SecretSync.Flyio]: AppConnection.Flyio
};
@@ -35,7 +35,7 @@ export type Approver = {
id: string;
type: ApproverType;
sequence?: number;
approvals?: number;
approvalsRequired?: number;
};
export type Bypasser = {
@@ -23,6 +23,7 @@ export enum AppConnection {
TeamCity = "teamcity",
OCI = "oci",
OnePass = "1password",
Heroku = "heroku",
Render = "render",
Flyio = "flyio"
}
@@ -0,0 +1,2 @@
export * from "./queries";
export * from "./types";
@@ -0,0 +1,36 @@
import { useQuery, UseQueryOptions } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { appConnectionKeys } from "../queries";
import { THerokuApp } from "./types";
const herokuConnectionKeys = {
all: [...appConnectionKeys.all, "heroku"] as const,
listApps: (connectionId: string) => [...herokuConnectionKeys.all, "apps", connectionId] as const
};
export const useHerokuConnectionListApps = (
connectionId: string,
options?: Omit<
UseQueryOptions<
THerokuApp[],
unknown,
THerokuApp[],
ReturnType<typeof herokuConnectionKeys.listApps>
>,
"queryKey" | "queryFn"
>
) => {
return useQuery({
queryKey: herokuConnectionKeys.listApps(connectionId),
queryFn: async () => {
const { data } = await apiRequest.get<THerokuApp[]>(
`/api/v1/app-connections/heroku/${connectionId}/apps`
);
return data;
},
...options
});
};
@@ -0,0 +1,4 @@
export type THerokuApp = {
id: string;
name: string;
};
@@ -106,6 +106,11 @@ export type TOCIConnectionOption = TAppConnectionOptionBase & {
app: AppConnection.OCI;
};
export type THerokuConnectionOption = TAppConnectionOptionBase & {
app: AppConnection.Heroku;
oauthClientId?: string;
};
export type TOnePassConnectionOption = TAppConnectionOptionBase & {
app: AppConnection.OnePass;
};
@@ -141,6 +146,7 @@ export type TAppConnectionOption =
| TTeamCityConnectionOption
| TOCIConnectionOption
| TOnePassConnectionOption
| THerokuConnectionOption
| TRenderConnectionOption
| TFlyioConnectionOption;
@@ -169,6 +175,7 @@ export type TAppConnectionOptionMap = {
[AppConnection.TeamCity]: TTeamCityConnectionOption;
[AppConnection.OCI]: TOCIConnectionOption;
[AppConnection.OnePass]: TOnePassConnectionOption;
[AppConnection.Heroku]: THerokuConnectionOption;
[AppConnection.Render]: TRenderConnectionOption;
[AppConnection.Flyio]: TFlyioConnectionOption;
};
@@ -0,0 +1,22 @@
import { AppConnection } from "@app/hooks/api/appConnections/enums";
import { TRootAppConnection } from "@app/hooks/api/appConnections/types/root-connection";
export enum HerokuConnectionMethod {
AuthToken = "auth-token",
OAuth = "oauth"
}
export type THerokuConnection = TRootAppConnection & { app: AppConnection.Heroku } & (
| {
method: HerokuConnectionMethod.AuthToken;
credentials: {
authToken: string;
};
}
| {
method: HerokuConnectionMethod.OAuth;
credentials: {
code: string;
};
}
);
@@ -14,6 +14,7 @@ import { TGcpConnection } from "./gcp-connection";
import { TGitHubConnection } from "./github-connection";
import { TGitHubRadarConnection } from "./github-radar-connection";
import { THCVaultConnection } from "./hc-vault-connection";
import { THerokuConnection } from "./heroku-connection";
import { THumanitecConnection } from "./humanitec-connection";
import { TLdapConnection } from "./ldap-connection";
import { TMsSqlConnection } from "./mssql-connection";
@@ -41,6 +42,7 @@ export * from "./gcp-connection";
export * from "./github-connection";
export * from "./github-radar-connection";
export * from "./hc-vault-connection";
export * from "./heroku-connection";
export * from "./humanitec-connection";
export * from "./ldap-connection";
export * from "./mssql-connection";
@@ -79,6 +81,7 @@ export type TAppConnection =
| TTeamCityConnection
| TOCIConnection
| TOnePassConnection
| THerokuConnection
| TRenderConnection
| TFlyioConnection;
@@ -132,6 +135,7 @@ export type TAppConnectionMap = {
[AppConnection.TeamCity]: TTeamCityConnection;
[AppConnection.OCI]: TOCIConnection;
[AppConnection.OnePass]: TOnePassConnection;
[AppConnection.Heroku]: THerokuConnection;
[AppConnection.Render]: TRenderConnection;
[AppConnection.Flyio]: TFlyioConnection;
};
-1
View File
@@ -73,7 +73,6 @@ export const selectOrganization = async (data: {
}) => {
const { data: res } = await apiRequest.post<{
token: string;
refreshToken: string;
isMfaEnabled: boolean;
mfaMethod?: MfaMethod;
}>("/api/v3/auth/select-organization", data);
+15 -2
View File
@@ -12,9 +12,10 @@ export type TDynamicSecret = {
defaultTTL: string;
status?: DynamicSecretStatus;
statusDetails?: string;
maxTTL: string;
maxTTL?: string;
usernameTemplate?: string | null;
metadata?: { key: string; value: string }[];
tags?: { key: string; value: string }[];
};
export enum DynamicSecretProviders {
@@ -35,7 +36,8 @@ export enum DynamicSecretProviders {
SapAse = "sap-ase",
Kubernetes = "kubernetes",
Vertica = "vertica",
GcpIam = "gcp-iam"
GcpIam = "gcp-iam",
Github = "github"
}
export enum KubernetesDynamicSecretCredentialType {
@@ -89,6 +91,7 @@ export type TDynamicSecretProvider =
}
| {
type: DynamicSecretProviders.AwsIam;
tags?: { key: string; value: string }[];
inputs:
| {
method: DynamicSecretAwsIamAuth.AccessKey;
@@ -333,6 +336,14 @@ export type TDynamicSecretProvider =
inputs: {
serviceAccountEmail: string;
};
}
| {
type: DynamicSecretProviders.Github;
inputs: {
appId: number;
installationId: number;
privateKey: string;
};
};
export type TCreateDynamicSecretDTO = {
@@ -345,6 +356,7 @@ export type TCreateDynamicSecretDTO = {
name: string;
metadata?: { key: string; value: string }[];
usernameTemplate?: string;
tags?: { key: string; value: string }[];
};
export type TUpdateDynamicSecretDTO = {
@@ -359,6 +371,7 @@ export type TUpdateDynamicSecretDTO = {
maxTTL?: string | null;
inputs?: unknown;
usernameTemplate?: string | null;
tags?: { key: string; value: string }[];
};
};
@@ -16,6 +16,7 @@ export enum SecretSync {
TeamCity = "teamcity",
OCIVault = "oci-vault",
OnePass = "1password",
Heroku = "heroku",
Render = "render",
Flyio = "flyio"
}
@@ -0,0 +1,16 @@
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 type THerokuSync = TRootSecretSync & {
destination: SecretSync.Heroku;
destinationConfig: {
app: string;
appName: string;
};
connection: {
app: AppConnection.Heroku;
name: string;
id: string;
};
};
@@ -14,6 +14,7 @@ import { TFlyioSync } from "./flyio-sync";
import { TGcpSync } from "./gcp-sync";
import { TGitHubSync } from "./github-sync";
import { THCVaultSync } from "./hc-vault-sync";
import { THerokuSync } from "./heroku-sync";
import { THumanitecSync } from "./humanitec-sync";
import { TOCIVaultSync } from "./oci-vault-sync";
import { TTeamCitySync } from "./teamcity-sync";
@@ -46,6 +47,7 @@ export type TSecretSync =
| TTeamCitySync
| TOCIVaultSync
| TOnePassSync
| THerokuSync
| TRenderSync
| TFlyioSync;
@@ -76,9 +76,7 @@ export const PasswordStep = ({
// case: organization ID is present from the provider auth token -- select the org and use the new jwt token in the CLI, then navigate to the org
if (organizationId) {
const finishWithOrgWorkflow = async () => {
const { token, isMfaEnabled, mfaMethod, refreshToken } = await selectOrganization({
organizationId
});
const { token, isMfaEnabled, mfaMethod } = await selectOrganization({ organizationId });
if (isMfaEnabled) {
SecurityClient.setMfaToken(token);
@@ -96,11 +94,10 @@ export const PasswordStep = ({
const payload = {
privateKey,
email,
JWTToken: token,
refreshToken
JTWToken: token
};
await instance.post(cliUrl, payload).catch(() => {
// if error happens to communicate we set the token with an expiry in session storage
// if error happens to communicate we set the token with an expiry in sessino storage
// the cli-redirect page has logic to show this to user and ask them to paste it in terminal
sessionStorage.setItem(
SessionStorageKeys.CLI_TERMINAL_TOKEN,
@@ -190,7 +187,7 @@ export const PasswordStep = ({
// case: organization ID is present from the provider auth token -- select the org and use the new jwt token in the CLI, then navigate to the org
if (organizationId) {
const finishWithOrgWorkflow = async () => {
const { token, isMfaEnabled, mfaMethod, refreshToken } = await selectOrganization({
const { token, isMfaEnabled, mfaMethod } = await selectOrganization({
organizationId
});
@@ -209,11 +206,10 @@ export const PasswordStep = ({
const instance = axios.create();
const payload = {
...isCliLoginSuccessful.loginResponse,
JWTToken: token,
refreshToken
JTWToken: token
};
await instance.post(cliUrl, payload).catch(() => {
// if error happens to communicate we set the token with an expiry in session storage
// if error happens to communicate we set the token with an expiry in sessino storage
// the cli-redirect page has logic to show this to user and ask them to paste it in terminal
sessionStorage.setItem(
SessionStorageKeys.CLI_TERMINAL_TOKEN,
@@ -112,7 +112,7 @@ export const SelectOrganizationSection = () => {
return;
}
const { token, isMfaEnabled, mfaMethod, refreshToken } = await selectOrg
const { token, isMfaEnabled, mfaMethod } = await selectOrg
.mutateAsync({
organizationId: organization.id,
userAgent: callbackPort ? UserAgentType.CLI : undefined
@@ -149,16 +149,15 @@ export const SelectOrganizationSection = () => {
}
const payload = {
JWTToken: token,
JTWToken: token,
email: user?.email,
privateKey,
refreshToken
privateKey
} as IsCliLoginSuccessful["loginResponse"];
// send request to server endpoint
const instance = axios.create();
await instance.post(`http://127.0.0.1:${callbackPort}/`, payload).catch(() => {
// if error happens to communicate we set the token with an expiry in session storage
// if error happens to communicate we set the token with an expiry in sessino storage
// the cli-redirect page has logic to show this to user and ask them to paste it in terminal
sessionStorage.setItem(
SessionStorageKeys.CLI_TERMINAL_TOKEN,
@@ -23,6 +23,7 @@ import { GcpConnectionForm } from "./GcpConnectionForm";
import { GitHubConnectionForm } from "./GitHubConnectionForm";
import { GitHubRadarConnectionForm } from "./GitHubRadarConnectionForm";
import { HCVaultConnectionForm } from "./HCVaultConnectionForm";
import { HerokuConnectionForm } from "./HerokuAppConnectionForm";
import { HumanitecConnectionForm } from "./HumanitecConnectionForm";
import { LdapConnectionForm } from "./LdapConnectionForm";
import { MsSqlConnectionForm } from "./MsSqlConnectionForm";
@@ -121,6 +122,8 @@ const CreateForm = ({ app, onComplete }: CreateFormProps) => {
return <OCIConnectionForm onSubmit={onSubmit} />;
case AppConnection.OnePass:
return <OnePassConnectionForm onSubmit={onSubmit} />;
case AppConnection.Heroku:
return <HerokuConnectionForm onSubmit={onSubmit} />;
case AppConnection.Render:
return <RenderConnectionForm onSubmit={onSubmit} />;
case AppConnection.Flyio:
@@ -209,6 +212,8 @@ const UpdateForm = ({ appConnection, onComplete }: UpdateFormProps) => {
return <OCIConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;
case AppConnection.OnePass:
return <OnePassConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;
case AppConnection.Heroku:
return <HerokuConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;
case AppConnection.Render:
return <RenderConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;
case AppConnection.Flyio:
@@ -0,0 +1,253 @@
/* 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,
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 {
HerokuConnectionMethod,
THerokuConnection
} from "@app/hooks/api/appConnections/types/heroku-connection";
import {
genericAppConnectionFieldsSchema,
GenericAppConnectionsFields
} from "./GenericAppConnectionFields";
type Props = {
appConnection?: THerokuConnection;
onSubmit: (formData: FormData) => Promise<void>;
};
const formSchema = z.discriminatedUnion("method", [
genericAppConnectionFieldsSchema.extend({
app: z.literal(AppConnection.Heroku),
method: z.literal(HerokuConnectionMethod.AuthToken),
credentials: z.object({
authToken: z.string().min(1, "Auth token is required")
})
}),
genericAppConnectionFieldsSchema.extend({
app: z.literal(AppConnection.Heroku),
method: z.literal(HerokuConnectionMethod.OAuth),
credentials: z.object({
code: z.string().min(1, "Code is required")
})
})
]);
type FormData = z.infer<typeof formSchema>;
export const HerokuConnectionForm = ({ appConnection, onSubmit: formSubmit }: Props) => {
const isUpdate = Boolean(appConnection);
const [isRedirecting, setIsRedirecting] = useState(false);
const {
option: { oauthClientId },
isLoading
} = useGetAppConnectionOption(AppConnection.Heroku);
const form = useForm<FormData>({
resolver: zodResolver(formSchema),
defaultValues:
appConnection?.method === HerokuConnectionMethod.OAuth
? { ...appConnection, credentials: { code: "custom" } }
: (appConnection ??
({
app: AppConnection.Heroku,
method: HerokuConnectionMethod.AuthToken,
credentials: {
authToken: ""
}
} as FormData))
});
const {
handleSubmit,
control,
watch,
setValue,
formState: { isSubmitting, isDirty }
} = form;
const selectedMethod = watch("method");
const onSubmit = async (formData: FormData) => {
try {
switch (formData.method) {
case HerokuConnectionMethod.AuthToken:
await formSubmit(formData);
break;
case HerokuConnectionMethod.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(
"herokuConnectionFormData",
JSON.stringify({
...formData,
connectionId: appConnection?.id,
isUpdate
})
);
// Redirect to Heroku OAuth
const oauthUrl = new URL("https://id.heroku.com/oauth/authorize");
oauthUrl.searchParams.set("client_id", oauthClientId);
oauthUrl.searchParams.set("response_type", "code");
oauthUrl.searchParams.set("scope", "write-protected");
oauthUrl.searchParams.set("state", state);
window.location.assign(oauthUrl.toString());
break;
default:
throw new Error("Unhandled Heroku Connection method");
}
} catch (error) {
console.error("Error handling form submission:", error);
setIsRedirecting(false);
}
};
let isMissingConfig: boolean;
switch (selectedMethod) {
case HerokuConnectionMethod.OAuth:
isMissingConfig = !oauthClientId;
break;
case HerokuConnectionMethod.AuthToken:
isMissingConfig = false;
break;
default:
throw new Error(`Unhandled Heroku Connection method: ${selectedMethod}`);
}
const methodDetails = getAppConnectionMethodDetails(selectedMethod);
return (
<FormProvider {...form}>
<form onSubmit={handleSubmit(onSubmit)}>
{!isUpdate && <GenericAppConnectionsFields />}
<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.Heroku].name
}. This field cannot be changed after creation.`}
errorText={
!isLoading && isMissingConfig && selectedMethod === HerokuConnectionMethod.OAuth
? `Environment variables have not been configured. ${
isInfisicalCloud()
? "Please contact Infisical."
: `See Docs to configure Heroku ${methodDetails.name} Connections.`
}`
: error?.message
}
isError={Boolean(error?.message) || isMissingConfig}
label="Method"
>
<Select
isDisabled={isUpdate}
value={value}
onValueChange={(val) => {
console.log("val", val === HerokuConnectionMethod.OAuth);
onChange(val);
if (val === HerokuConnectionMethod.OAuth) {
setValue("credentials.code", "custom");
}
}}
className="w-full border border-mineshaft-500"
position="popper"
dropdownContainerClassName="max-w-none"
>
{Object.values(HerokuConnectionMethod).map((method) => {
return (
<SelectItem value={method} key={method}>
{getAppConnectionMethodDetails(method).name}{" "}
{method === HerokuConnectionMethod.AuthToken ? " (Recommended)" : ""}
</SelectItem>
);
})}
</Select>
</FormControl>
)}
/>
{selectedMethod === HerokuConnectionMethod.AuthToken && (
<Controller
name="credentials.authToken"
control={control}
render={({ field: { value, onChange }, fieldState: { error } }) => (
<FormControl
label="Auth Token"
errorText={error?.message}
isError={Boolean(error?.message)}
tooltipText="Your Heroku Auth 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 === HerokuConnectionMethod.OAuth) ||
isRedirecting
}
>
{isRedirecting && selectedMethod === HerokuConnectionMethod.OAuth
? "Redirecting to Heroku..."
: isUpdate
? "Reconnect to Heroku"
: "Connect to Heroku"}
</Button>
<ModalClose asChild>
<Button colorSchema="secondary" variant="plain">
Cancel
</Button>
</ModalClose>
</div>
</form>
</FormProvider>
);
};
@@ -0,0 +1,14 @@
import { THerokuSync } from "@app/hooks/api/secretSyncs/types/heroku-sync";
import { getSecretSyncDestinationColValues } from "../helpers";
import { SecretSyncTableCell } from "../SecretSyncTableCell";
type Props = {
secretSync: THerokuSync;
};
export const HerokuSyncDestinationCol = ({ secretSync }: Props) => {
const { primaryText, secondaryText } = getSecretSyncDestinationColValues(secretSync);
return <SecretSyncTableCell primaryText={primaryText} secondaryText={secondaryText} />;
};
@@ -12,6 +12,7 @@ import { FlyioSyncDestinationCol } from "./FlyioSyncDestinationCol";
import { GcpSyncDestinationCol } from "./GcpSyncDestinationCol";
import { GitHubSyncDestinationCol } from "./GitHubSyncDestinationCol";
import { HCVaultSyncDestinationCol } from "./HCVaultSyncDestinationCol";
import { HerokuSyncDestinationCol } from "./HerokuSyncDestinationCol";
import { HumanitecSyncDestinationCol } from "./HumanitecSyncDestinationCol";
import { OCIVaultSyncDestinationCol } from "./OCIVaultSyncDestinationCol";
import { RenderSyncDestinationCol } from "./RenderSyncDestinationCol";
@@ -60,6 +61,8 @@ export const SecretSyncDestinationCol = ({ secretSync }: Props) => {
return <OnePassSyncDestinationCol secretSync={secretSync} />;
case SecretSync.AzureDevOps:
return <AzureDevOpsSyncDestinationCol secretSync={secretSync} />;
case SecretSync.Heroku:
return <HerokuSyncDestinationCol secretSync={secretSync} />;
case SecretSync.Render:
return <RenderSyncDestinationCol secretSync={secretSync} />;
case SecretSync.Flyio:
@@ -116,6 +116,10 @@ export const getSecretSyncDestinationColValues = (secretSync: TSecretSync) => {
primaryText = destinationConfig.devopsProjectName;
secondaryText = destinationConfig.devopsProjectId;
break;
case SecretSync.Heroku:
primaryText = destinationConfig.appName;
secondaryText = destinationConfig.app;
break;
case SecretSync.Render:
primaryText = destinationConfig.serviceName ?? destinationConfig.serviceId;
secondaryText = "Service";
@@ -185,7 +185,7 @@ export const ReviewAccessRequestModal = ({
return acc;
}
const approvals = curr.approvals || policy.approvals;
const approvals = curr.approvalsRequired || policy.approvals;
const sequence = curr.sequence || 1;
acc.push(
@@ -152,34 +152,34 @@ const Form = ({
.map(({ id, type }) => ({ id, type: type as BypasserType.Group })) || [],
approvals: editValues?.approvals,
allowedSelfApprovals: editValues?.allowedSelfApprovals,
sequenceApprovers: editValues.approvers
?.sort((a, b) => (a?.sequence || 0) - (b?.sequence || 0))
.reduce(
(acc, curr) => {
if (acc.length && acc[acc.length - 1].sequence === curr.sequence) {
acc[acc.length - 1][curr.type]?.push(curr);
return acc;
}
const approvals = curr.approvals || editValues.approvals;
acc.push(
curr.type === ApproverType.User
? {
user: [curr],
group: [],
sequence: 1,
approvals
}
: { group: [curr], user: [], sequence: 1, approvals }
);
sequenceApprovers: editValues.approvers?.reduce(
(acc, curr) => {
if (acc.length && acc[acc.length - 1].sequence === curr.sequence) {
acc[acc.length - 1][curr.type]?.push(curr);
return acc;
},
[] as { user: Approver[]; group: Approver[]; sequence?: number; approvals: number }[]
)
}
const approvals = curr.approvalsRequired || editValues.approvals;
acc.push(
curr.type === ApproverType.User
? {
user: [curr],
group: [],
sequence: 1,
approvals
}
: { group: [curr], user: [], sequence: 1, approvals }
);
return acc;
},
[] as { user: Approver[]; group: Approver[]; sequence?: number; approvals: number }[]
)
} as TFormSchema)
: undefined,
defaultValues: {
sequenceApprovers: [{ approvals: 1 }]
}
defaultValues: !editValues
? {
sequenceApprovers: [{ approvals: 1 }]
}
: undefined
});
const sequenceApproversFieldArray = useFieldArray({
control,
@@ -61,11 +61,11 @@ export const ApprovalPolicyRow = ({
const sortedSteps = policy.approvers?.sort((a, b) => (a?.sequence || 0) - (b?.sequence || 0));
const entityInSameSequence = sortedSteps?.reduce(
(acc, curr) => {
if (acc.length && acc[acc.length - 1].sequence === curr.sequence) {
if (acc.length && acc[acc.length - 1].sequence === (curr.sequence || 1)) {
acc[acc.length - 1][curr.type]?.push(curr);
return acc;
}
const approvals = curr.approvals || policy.approvals;
const approvals = curr.approvalsRequired || policy.approvals;
acc.push(
curr.type === ApproverType.User
? { user: [curr], group: [], sequence: 1, approvals }
@@ -21,6 +21,8 @@ import {
} from "@app/hooks/api/dynamicSecret/types";
import { WorkspaceEnv } from "@app/hooks/api/types";
import { MetadataForm } from "../../DynamicSecretListView/MetadataForm";
const formSchema = z.object({
provider: z.discriminatedUnion("method", [
z.object({
@@ -32,7 +34,12 @@ const formSchema = z.object({
permissionBoundaryPolicyArn: z.string().trim().optional(),
policyDocument: z.string().trim().optional(),
userGroups: z.string().trim().optional(),
policyArns: z.string().trim().optional()
policyArns: z.string().trim().optional(),
tags: z
.array(
z.object({ key: z.string().trim().min(1).max(128), value: z.string().trim().min(1).max(256) })
)
.optional()
}),
z.object({
method: z.literal(DynamicSecretAwsIamAuth.AssumeRole),
@@ -42,7 +49,12 @@ const formSchema = z.object({
permissionBoundaryPolicyArn: z.string().trim().optional(),
policyDocument: z.string().trim().optional(),
userGroups: z.string().trim().optional(),
policyArns: z.string().trim().optional()
policyArns: z.string().trim().optional(),
tags: z
.array(
z.object({ key: z.string().trim().min(1).max(128), value: z.string().trim().min(1).max(256) })
)
.optional()
})
]),
defaultTTL: z.string().superRefine((val, ctx) => {
@@ -398,6 +410,7 @@ export const AwsIamInputForm = ({
</FormControl>
)}
/>
<MetadataForm control={control} name="provider.tags" title="Tags" isValueRequired />
{!isSingleEnvironmentMode && (
<Controller
control={control}
@@ -11,7 +11,7 @@ import {
SiSnowflake
} from "react-icons/si";
import { VscAzure } from "react-icons/vsc";
import { faAws, faGoogle } from "@fortawesome/free-brands-svg-icons";
import { faAws, faGithub, faGoogle } from "@fortawesome/free-brands-svg-icons";
import { faClock, faDatabase } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { AnimatePresence, motion } from "framer-motion";
@@ -26,6 +26,7 @@ import { AzureEntraIdInputForm } from "./AzureEntraIdInputForm";
import { CassandraInputForm } from "./CassandraInputForm";
import { ElasticSearchInputForm } from "./ElasticSearchInputForm";
import { GcpIamInputForm } from "./GcpIamInputForm";
import { GithubInputForm } from "./GithubInputForm";
import { KubernetesInputForm } from "./KubernetesInputForm";
import { LdapInputForm } from "./LdapInputForm";
import { MongoAtlasInputForm } from "./MongoAtlasInputForm";
@@ -143,6 +144,11 @@ const DYNAMIC_SECRET_LIST = [
icon: <FontAwesomeIcon icon={faGoogle} size="lg" />,
provider: DynamicSecretProviders.GcpIam,
title: "GCP IAM"
},
{
icon: <FontAwesomeIcon icon={faGithub} size="lg" />,
provider: DynamicSecretProviders.Github,
title: "GitHub"
}
];
@@ -548,6 +554,25 @@ export const CreateDynamicSecretForm = ({
/>
</motion.div>
)}
{wizardStep === WizardSteps.ProviderInputs &&
selectedProvider === DynamicSecretProviders.Github && (
<motion.div
key="dynamic-github-step"
transition={{ duration: 0.1 }}
initial={{ opacity: 0, translateX: 30 }}
animate={{ opacity: 1, translateX: 0 }}
exit={{ opacity: 0, translateX: -30 }}
>
<GithubInputForm
onCompleted={handleFormReset}
onCancel={handleFormReset}
projectSlug={projectSlug}
secretPath={secretPath}
environments={environments}
isSingleEnvironmentMode={isSingleEnvironmentMode}
/>
</motion.div>
)}
</AnimatePresence>
</ModalContent>
</Modal>
@@ -0,0 +1,234 @@
import { Controller, useForm } from "react-hook-form";
import { faQuestionCircle } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import {
Button,
FilterableSelect,
FormControl,
FormLabel,
Input,
SecretInput,
Tooltip
} from "@app/components/v2";
import { useCreateDynamicSecret } from "@app/hooks/api";
import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types";
import { WorkspaceEnv } from "@app/hooks/api/types";
const formSchema = z.object({
provider: z.object({
appId: z.coerce.number().min(1, "Required"),
installationId: z.coerce.number().min(1, "Required"),
privateKey: z
.string()
.trim()
.min(1, "Required")
.refine(
(val) =>
/^-----BEGIN(?:(?: RSA| PGP| ENCRYPTED)? PRIVATE KEY)-----\s*[\s\S]*?-----END(?:(?: RSA| PGP| ENCRYPTED)? PRIVATE KEY)-----$/.test(
val
),
"Invalid PEM format for private key"
)
}),
name: z.string().refine((val) => val.toLowerCase() === val, "Must be lowercase"),
environment: z.object({ name: z.string(), slug: z.string() })
});
type TForm = z.infer<typeof formSchema>;
type Props = {
onCompleted: () => void;
onCancel: () => void;
secretPath: string;
projectSlug: string;
environments: WorkspaceEnv[];
isSingleEnvironmentMode?: boolean;
};
export const GithubInputForm = ({
onCompleted,
onCancel,
environments,
secretPath,
projectSlug,
isSingleEnvironmentMode
}: Props) => {
const {
control,
formState: { isSubmitting },
handleSubmit
} = useForm<TForm>({
resolver: zodResolver(formSchema),
defaultValues: {
environment: isSingleEnvironmentMode && environments.length > 0 ? environments[0] : undefined
}
});
const createDynamicSecret = useCreateDynamicSecret();
const handleCreateDynamicSecret = async ({ name, provider, environment }: TForm) => {
if (createDynamicSecret.isPending) return;
try {
await createDynamicSecret.mutateAsync({
provider: {
type: DynamicSecretProviders.Github,
inputs: {
...provider
}
},
defaultTTL: "1h", // Github is limited to 1 hour tokens
name,
path: secretPath,
projectSlug,
environmentSlug: environment.slug
});
onCompleted();
} catch {
createNotification({
type: "error",
text: "Failed to create dynamic secret"
});
}
};
return (
<div>
<form onSubmit={handleSubmit(handleCreateDynamicSecret)} autoComplete="off">
<div>
<div className="flex items-center space-x-2">
<div className="flex-grow">
<Controller
control={control}
defaultValue=""
name="name"
render={({ field, fieldState: { error } }) => (
<FormControl
label="Secret Name"
isError={Boolean(error)}
errorText={error?.message}
>
<Input {...field} placeholder="dynamic-secret" />
</FormControl>
)}
/>
</div>
<div className="w-32">
<FormControl
label={
<FormLabel
label="Default TTL"
icon={
<Tooltip content="Github token TTL is fixed to 1 hour">
<FontAwesomeIcon
icon={faQuestionCircle}
size="sm"
className="relative bottom-px right-1"
/>
</Tooltip>
}
/>
}
>
<Input disabled value="1h" className="pointer-events-none opacity-50" />
</FormControl>
</div>
</div>
<div>
<div className="mb-4 mt-4 border-b border-mineshaft-500 pb-2 pl-1 font-medium text-mineshaft-200">
Configuration
</div>
<div className="flex flex-col">
<Controller
control={control}
name="provider.appId"
render={({ field, fieldState: { error } }) => (
<FormControl
label="App ID"
className="flex-grow"
isError={Boolean(error?.message)}
errorText={error?.message}
isRequired
>
<Input placeholder="0000000" {...field} />
</FormControl>
)}
/>
<Controller
control={control}
name="provider.installationId"
render={({ field, fieldState: { error } }) => (
<FormControl
label="Installation ID"
className="flex-grow"
isError={Boolean(error?.message)}
errorText={error?.message}
isRequired
>
<Input placeholder="00000000" {...field} />
</FormControl>
)}
/>
<Controller
control={control}
name="provider.privateKey"
render={({ field, fieldState: { error } }) => (
<FormControl
label="App Private Key PEM"
className="flex-grow"
isError={Boolean(error?.message)}
errorText={error?.message}
isRequired
>
<SecretInput
{...field}
containerClassName="text-gray-400 group-focus-within:!border-primary-400/50 border border-mineshaft-500 bg-mineshaft-900 px-2.5 py-1.5"
/>
</FormControl>
)}
/>
</div>
{!isSingleEnvironmentMode && (
<Controller
control={control}
name="environment"
render={({ field: { value, onChange }, fieldState: { error } }) => (
<FormControl
label="Environment"
isError={Boolean(error)}
errorText={error?.message}
>
<FilterableSelect
options={environments}
value={value}
onChange={onChange}
placeholder="Select the environment to create secret in..."
getOptionLabel={(option) => option.name}
getOptionValue={(option) => option.slug}
menuPlacement="top"
/>
</FormControl>
)}
/>
)}
</div>
</div>
<div className="mt-4 flex items-center space-x-4">
<Button type="submit" isLoading={isSubmitting}>
Submit
</Button>
<Button variant="outline_bg" onClick={onCancel}>
Cancel
</Button>
</div>
</form>
</div>
);
};
@@ -368,6 +368,22 @@ const renderOutputForm = (
);
}
if (provider === DynamicSecretProviders.Github) {
const { TOKEN } = data as {
TOKEN: string;
};
return (
<div>
<OutputDisplay
label="Token"
value={TOKEN}
helperText="Important: Copy these credentials now. You will not be able to see them again after you close the modal."
/>
</div>
);
}
return null;
};
@@ -608,6 +624,9 @@ export const CreateDynamicSecretLease = ({
return <Spinner className="mx-auto h-40 text-mineshaft-700" />;
}
// Github tokens are fixed to 1 hour
const fixedTtl = provider === DynamicSecretProviders.Github;
return (
<div>
<AnimatePresence>
@@ -629,8 +648,11 @@ export const CreateDynamicSecretLease = ({
label={<TtlFormLabel label="Default TTL" />}
isError={Boolean(error?.message)}
errorText={error?.message}
helperText={
fixedTtl ? `This provider has a fixed TTL of ${field.value}` : undefined
}
>
<Input {...field} />
<Input {...field} isDisabled={fixedTtl} />
</FormControl>
)}
/>
@@ -29,7 +29,7 @@ import {
import { ProjectPermissionDynamicSecretActions, ProjectPermissionSub } from "@app/context";
import { usePopUp } from "@app/hooks";
import { useGetDynamicSecretLeases, useRevokeDynamicSecretLease } from "@app/hooks/api";
import { TDynamicSecret } from "@app/hooks/api/dynamicSecret/types";
import { DynamicSecretProviders, TDynamicSecret } from "@app/hooks/api/dynamicSecret/types";
import { DynamicSecretLeaseStatus } from "@app/hooks/api/dynamicSecretLease/types";
import { RenewDynamicSecretLease } from "./RenewDynamicSecretLease";
@@ -44,6 +44,8 @@ type Props = {
onClose: () => void;
};
const DYNAMIC_SECRETS_WITHOUT_RENEWAL = [DynamicSecretProviders.Github];
export const DynamicSecretLease = ({
projectSlug,
dynamicSecretName,
@@ -94,6 +96,8 @@ export const DynamicSecretLease = ({
}
};
const canRenew = !DYNAMIC_SECRETS_WITHOUT_RENEWAL.includes(dynamicSecret.type);
return (
<div>
<TableContainer>
@@ -141,29 +145,31 @@ export const DynamicSecretLease = ({
</Td>
<Td>
<div className="flex items-center space-x-4">
<ProjectPermissionCan
I={ProjectPermissionDynamicSecretActions.Lease}
a={subject(ProjectPermissionSub.DynamicSecrets, {
environment,
secretPath,
metadata: dynamicSecret.metadata
})}
renderTooltip
allowedLabel="Renew"
>
{(isAllowed) => (
<IconButton
ariaLabel="edit-folder"
variant="plain"
size="sm"
className="p-0"
isDisabled={!isAllowed}
onClick={() => handlePopUpOpen("renewSecret", { leaseId: id })}
>
<FontAwesomeIcon icon={faRepeat} size="lg" />
</IconButton>
)}
</ProjectPermissionCan>
{canRenew && (
<ProjectPermissionCan
I={ProjectPermissionDynamicSecretActions.Lease}
a={subject(ProjectPermissionSub.DynamicSecrets, {
environment,
secretPath,
metadata: dynamicSecret.metadata
})}
renderTooltip
allowedLabel="Renew"
>
{(isAllowed) => (
<IconButton
ariaLabel="renew-lease"
variant="plain"
size="sm"
className="p-0"
isDisabled={!isAllowed}
onClick={() => handlePopUpOpen("renewSecret", { leaseId: id })}
>
<FontAwesomeIcon icon={faRepeat} size="lg" />
</IconButton>
)}
</ProjectPermissionCan>
)}
<ProjectPermissionCan
I={ProjectPermissionDynamicSecretActions.Lease}
a={subject(ProjectPermissionSub.DynamicSecrets, {
@@ -10,6 +10,8 @@ import { useUpdateDynamicSecret } from "@app/hooks/api";
import { DynamicSecretAwsIamAuth, TDynamicSecret } from "@app/hooks/api/dynamicSecret/types";
import { slugSchema } from "@app/lib/schemas";
import { MetadataForm } from "../MetadataForm";
const formSchema = z.object({
inputs: z.discriminatedUnion("method", [
z.object({
@@ -21,7 +23,10 @@ const formSchema = z.object({
permissionBoundaryPolicyArn: z.string().trim().optional(),
policyDocument: z.string().trim().optional(),
userGroups: z.string().trim().optional(),
policyArns: z.string().trim().optional()
policyArns: z.string().trim().optional(),
tags: z
.array(z.object({ key: z.string().trim().min(1), value: z.string().trim().min(1) }))
.optional(),
}),
z.object({
method: z.literal(DynamicSecretAwsIamAuth.AssumeRole),
@@ -31,7 +36,10 @@ const formSchema = z.object({
permissionBoundaryPolicyArn: z.string().trim().optional(),
policyDocument: z.string().trim().optional(),
userGroups: z.string().trim().optional(),
policyArns: z.string().trim().optional()
policyArns: z.string().trim().optional(),
tags: z
.array(z.object({ key: z.string().trim().min(1), value: z.string().trim().min(1) }))
.optional()
})
]),
defaultTTL: z.string().superRefine((val, ctx) => {
@@ -89,7 +97,7 @@ export const EditDynamicSecretAwsIamForm = ({
usernameTemplate: dynamicSecret?.usernameTemplate || "{{randomUsername}}",
inputs: {
...(dynamicSecret.inputs as TForm["inputs"])
}
},
}
});
const isAccessKeyMethod = watch("inputs.method") === DynamicSecretAwsIamAuth.AccessKey;
@@ -117,7 +125,8 @@ export const EditDynamicSecretAwsIamForm = ({
defaultTTL,
inputs,
newName: newName === dynamicSecret.name ? undefined : newName,
usernameTemplate: !usernameTemplate || isDefaultUsernameTemplate ? null : usernameTemplate
usernameTemplate:
!usernameTemplate || isDefaultUsernameTemplate ? null : usernameTemplate
}
});
onClose();
@@ -380,6 +389,7 @@ export const EditDynamicSecretAwsIamForm = ({
</FormControl>
)}
/>
<MetadataForm control={control} name="inputs.tags" title="Tags" isValueRequired />
</div>
</div>
<div className="mt-4 flex items-center space-x-4">
@@ -10,6 +10,7 @@ import { EditDynamicSecretAzureEntraIdForm } from "./EditDynamicSecretAzureEntra
import { EditDynamicSecretCassandraForm } from "./EditDynamicSecretCassandraForm";
import { EditDynamicSecretElasticSearchForm } from "./EditDynamicSecretElasticSearchForm";
import { EditDynamicSecretGcpIamForm } from "./EditDynamicSecretGcpIamForm";
import { EditDynamicSecretGithubForm } from "./EditDynamicSecretGithubForm";
import { EditDynamicSecretKubernetesForm } from "./EditDynamicSecretKubernetesForm";
import { EditDynamicSecretLdapForm } from "./EditDynamicSecretLdapForm";
import { EditDynamicSecretMongoAtlasForm } from "./EditDynamicSecretMongoAtlasForm";
@@ -366,6 +367,23 @@ export const EditDynamicSecretForm = ({
/>
</motion.div>
)}
{dynamicSecretDetails?.type === DynamicSecretProviders.Github && (
<motion.div
key="github-edit"
transition={{ duration: 0.1 }}
initial={{ opacity: 0, translateX: 30 }}
animate={{ opacity: 1, translateX: 0 }}
exit={{ opacity: 0, translateX: -30 }}
>
<EditDynamicSecretGithubForm
onClose={onClose}
projectSlug={projectSlug}
secretPath={secretPath}
dynamicSecret={dynamicSecretDetails}
environment={environment}
/>
</motion.div>
)}
</AnimatePresence>
);
};
@@ -0,0 +1,199 @@
import { Controller, useForm } from "react-hook-form";
import { faQuestionCircle } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, FormControl, FormLabel, Input, SecretInput, Tooltip } from "@app/components/v2";
import { useUpdateDynamicSecret } from "@app/hooks/api";
import { TDynamicSecret } from "@app/hooks/api/dynamicSecret/types";
const formSchema = z.object({
inputs: z.object({
appId: z.coerce.number().min(1, "Required"),
installationId: z.coerce.number().min(1, "Required"),
privateKey: z
.string()
.trim()
.min(1, "Required")
.refine(
(val) =>
/^-----BEGIN(?:(?: RSA| PGP| ENCRYPTED)? PRIVATE KEY)-----\s*[\s\S]*?-----END(?:(?: RSA| PGP| ENCRYPTED)? PRIVATE KEY)-----$/.test(
val
),
"Invalid PEM format for private key"
)
}),
newName: z.string().refine((val) => val.toLowerCase() === val, "Must be lowercase")
});
type TForm = z.infer<typeof formSchema>;
type Props = {
onClose: () => void;
dynamicSecret: TDynamicSecret & { inputs: unknown };
secretPath: string;
environment: string;
projectSlug: string;
};
export const EditDynamicSecretGithubForm = ({
onClose,
dynamicSecret,
secretPath,
environment,
projectSlug
}: Props) => {
const {
control,
formState: { isSubmitting },
handleSubmit
} = useForm<TForm>({
resolver: zodResolver(formSchema),
values: {
newName: dynamicSecret.name,
inputs: {
...(dynamicSecret.inputs as TForm["inputs"])
}
}
});
const updateDynamicSecret = useUpdateDynamicSecret();
const handleUpdateDynamicSecret = async ({ inputs, newName }: TForm) => {
if (updateDynamicSecret.isPending) return;
try {
await updateDynamicSecret.mutateAsync({
name: dynamicSecret.name,
path: secretPath,
projectSlug,
environmentSlug: environment,
data: {
inputs,
newName: newName === dynamicSecret.name ? undefined : newName
}
});
onClose();
createNotification({
type: "success",
text: "Successfully updated dynamic secret"
});
} catch {
createNotification({
type: "error",
text: "Failed to update dynamic secret"
});
}
};
return (
<div>
<form onSubmit={handleSubmit(handleUpdateDynamicSecret)} autoComplete="off">
<div>
<div className="flex items-center space-x-2">
<div className="flex-grow">
<Controller
control={control}
name="newName"
render={({ field, fieldState: { error } }) => (
<FormControl
label="Secret Name"
isError={Boolean(error)}
errorText={error?.message}
>
<Input {...field} placeholder="dynamic-secret" />
</FormControl>
)}
/>
</div>
<div className="w-32">
<FormControl
label={
<FormLabel
label="Default TTL"
icon={
<Tooltip content="Github token TTL is fixed to 1 hour">
<FontAwesomeIcon
icon={faQuestionCircle}
size="sm"
className="relative bottom-px right-1"
/>
</Tooltip>
}
/>
}
>
<Input disabled value="1h" className="pointer-events-none opacity-50" />
</FormControl>
</div>
</div>
<div>
<div className="mb-4 mt-4 border-b border-mineshaft-500 pb-2 pl-1 font-medium text-mineshaft-200">
Configuration
</div>
<div className="flex flex-col">
<Controller
control={control}
name="inputs.appId"
render={({ field, fieldState: { error } }) => (
<FormControl
label="App ID"
className="flex-grow"
isError={Boolean(error?.message)}
errorText={error?.message}
isRequired
>
<Input placeholder="0000000" {...field} />
</FormControl>
)}
/>
<Controller
control={control}
name="inputs.installationId"
render={({ field, fieldState: { error } }) => (
<FormControl
label="Installation ID"
className="flex-grow"
isError={Boolean(error?.message)}
errorText={error?.message}
isRequired
>
<Input placeholder="00000000" {...field} />
</FormControl>
)}
/>
<Controller
control={control}
name="inputs.privateKey"
render={({ field, fieldState: { error } }) => (
<FormControl
label="App Private Key PEM"
className="flex-grow"
isError={Boolean(error?.message)}
errorText={error?.message}
isRequired
>
<SecretInput
{...field}
containerClassName="text-gray-400 group-focus-within:!border-primary-400/50 border border-mineshaft-500 bg-mineshaft-900 px-2.5 py-1.5"
/>
</FormControl>
)}
/>
</div>
</div>
</div>
<div className="mt-4 flex items-center space-x-4">
<Button type="submit" isLoading={isSubmitting}>
Submit
</Button>
<Button variant="outline_bg" onClick={onClose}>
Cancel
</Button>
</div>
</form>
</div>
);
};
@@ -4,14 +4,24 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { FormControl, FormLabel, IconButton, Input } from "@app/components/v2";
export const MetadataForm = ({ control }: { control: Control<any> }) => {
export const MetadataForm = ({
control,
name = "metadata",
title = "Metadata",
isValueRequired = false
}: {
control: Control<any>;
name?: string;
title?: string;
isValueRequired?: boolean;
}) => {
const metadataFormFields = useFieldArray({
control,
name: "metadata"
name
});
return (
<FormControl label="Metadata">
<FormControl label={title}>
<div className="flex flex-col space-y-2">
{metadataFormFields.fields.map(({ id: metadataFieldId }, i) => (
<div key={metadataFieldId} className="flex items-end space-x-2">
@@ -19,7 +29,7 @@ export const MetadataForm = ({ control }: { control: Control<any> }) => {
{i === 0 && <span className="text-xs text-mineshaft-400">Key</span>}
<Controller
control={control}
name={`metadata.${i}.key`}
name={`${name}.${i}.key`}
render={({ field, fieldState: { error } }) => (
<FormControl
isError={Boolean(error?.message)}
@@ -33,11 +43,15 @@ export const MetadataForm = ({ control }: { control: Control<any> }) => {
</div>
<div className="flex-grow">
{i === 0 && (
<FormLabel label="Value" className="text-xs text-mineshaft-400" isOptional />
<FormLabel
label="Value"
className="text-xs text-mineshaft-400"
isOptional={!isValueRequired}
/>
)}
<Controller
control={control}
name={`metadata.${i}.value`}
name={`${name}.${i}.value`}
render={({ field, fieldState: { error } }) => (
<FormControl
isError={Boolean(error?.message)}
@@ -28,7 +28,7 @@ export const RenewDynamicSecretLease = ({
environment,
dynamicSecret
}: Props) => {
const maxTtlMs = ms(dynamicSecret.maxTTL);
const maxTtlMs = dynamicSecret.maxTTL ? ms(dynamicSecret.maxTTL) : undefined;
const formSchema = z.object({
ttl: z.string().superRefine((val, ctx) => {
@@ -39,7 +39,7 @@ export const RenewDynamicSecretLease = ({
code: z.ZodIssueCode.custom,
message: "TTL must be greater than 1 second"
});
if (valMs > maxTtlMs)
if (maxTtlMs && valMs > maxTtlMs)
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `TTL must be less than ${dynamicSecret.maxTTL}`
@@ -0,0 +1,19 @@
import { GenericFieldLabel } from "@app/components/secret-syncs";
import { THerokuSync } from "@app/hooks/api/secretSyncs/types/heroku-sync";
type Props = {
secretSync: THerokuSync;
};
export const HerokuSyncDestinationSection = ({ secretSync }: Props) => {
const {
destinationConfig: { app, appName }
} = secretSync;
return (
<>
<GenericFieldLabel label="App Name">{appName}</GenericFieldLabel>
<GenericFieldLabel label="App ID">{app}</GenericFieldLabel>
</>
);
};
@@ -23,6 +23,7 @@ import { FlyioSyncDestinationSection } from "./FlyioSyncDestinationSection";
import { GcpSyncDestinationSection } from "./GcpSyncDestinationSection";
import { GitHubSyncDestinationSection } from "./GitHubSyncDestinationSection";
import { HCVaultSyncDestinationSection } from "./HCVaultSyncDestinationSection";
import { HerokuSyncDestinationSection } from "./HerokuSyncDestinationSection";
import { HumanitecSyncDestinationSection } from "./HumanitecSyncDestinationSection";
import { OCIVaultSyncDestinationSection } from "./OCIVaultSyncDestinationSection";
import { RenderSyncDestinationSection } from "./RenderSyncDestinationSection";
@@ -96,6 +97,9 @@ export const SecretSyncDestinationSection = ({ secretSync, onEditDestination }:
case SecretSync.AzureDevOps:
DestinationComponents = <AzureDevOpsSyncDestinationSection secretSync={secretSync} />;
break;
case SecretSync.Heroku:
DestinationComponents = <HerokuSyncDestinationSection secretSync={secretSync} />;
break;
case SecretSync.Render:
DestinationComponents = <RenderSyncDestinationSection secretSync={secretSync} />;
break;
@@ -55,6 +55,7 @@ export const SecretSyncOptionsSection = ({ secretSync, onEditOptions }: Props) =
case SecretSync.TeamCity:
case SecretSync.OCIVault:
case SecretSync.OnePass:
case SecretSync.Heroku:
case SecretSync.Render:
case SecretSync.Flyio:
AdditionalSyncOptionsComponent = null;
@@ -3,43 +3,99 @@ 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 { HerokuConnectionMethod } from "@app/hooks/api/appConnections/types/heroku-connection";
export const HerokuOAuthCallbackPage = () => {
const navigate = useNavigate();
const { mutateAsync } = useAuthorizeIntegration();
const { mutateAsync: createAppConnection } = useCreateAppConnection();
const { mutateAsync: updateAppConnection } = useUpdateAppConnection();
const { code, state } = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.HerokuOauthCallbackPage.id
});
const { currentWorkspace } = useWorkspace();
useEffect(() => {
(async () => {
try {
// validate state
if (state !== localStorage.getItem("latestCSRFToken")) return;
localStorage.removeItem("latestCSRFToken");
const integrationAuth = await mutateAsync({
workspaceId: currentWorkspace.id,
code: code as string,
integration: "heroku"
});
// Validate CSRF state token
const storedState = localStorage.getItem("latestCSRFToken");
if (state !== storedState) {
console.error("CSRF token mismatch");
navigate({
to: "/organization/app-connections",
search: { error: "invalid_state" }
});
return;
}
// Clean up CSRF token
localStorage.removeItem("latestCSRFToken");
// Retrieve stored form data
const storedFormData = localStorage.getItem("herokuConnectionFormData");
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("herokuConnectionFormData");
// Prepare app connection data with OAuth credentials
const connectionData = {
...formData,
method: HerokuConnectionMethod.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/heroku/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 Heroku 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 Heroku...</p>
</div>
</div>
);
};