Merge branch 'ENG-3506' into ENG-3506-LDAP

This commit is contained in:
x032205
2025-08-27 05:10:49 -04:00
193 changed files with 7318 additions and 1356 deletions
@@ -1,4 +1,4 @@
import { faQuestionCircle } from "@fortawesome/free-solid-svg-icons";
import { faArrowUpRightFromSquare, faQuestionCircle } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { FormLabel, Tooltip } from "../v2";
@@ -10,15 +10,18 @@ export const TtlFormLabel = ({ label }: { label: string }) => (
label={label}
icon={
<Tooltip
className="max-w-lg"
content={
<span>
Examples: 30m, 1h, 3d, etc.{" "}
<a
href="https://github.com/vercel/ms?tab=readme-ov-file#examples"
target="_blank"
rel="noopener noreferrer"
className="text-primary-700"
className="text-primary-500 hover:text-mineshaft-100"
>
More
See More Examples{" "}
<FontAwesomeIcon size="xs" className="mt-0.5" icon={faArrowUpRightFromSquare} />
</a>
</span>
}
@@ -26,7 +29,7 @@ export const TtlFormLabel = ({ label }: { label: string }) => (
<FontAwesomeIcon
icon={faQuestionCircle}
size="sm"
className="relative bottom-px right-1"
className="relative right-1 mt-0.5 text-mineshaft-300"
/>
</Tooltip>
}
@@ -0,0 +1,29 @@
import { components, OptionProps } from "react-select";
import { faCheckCircle } from "@fortawesome/free-regular-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
export const RoleOption = ({
isSelected,
children,
...props
}: OptionProps<{ name: string; slug: string; description?: string | undefined }>) => {
return (
<components.Option isSelected={isSelected} {...props}>
<div className="flex flex-row items-center justify-between">
<div>
<p className="truncate">{children}</p>
{props.data.description ? (
<p className="truncate text-xs leading-4 text-mineshaft-400">
{props.data.description}
</p>
) : (
<p className="text-xs leading-4 text-mineshaft-400/50">No Description</p>
)}
</div>
{isSelected && (
<FontAwesomeIcon className="ml-2 text-primary" icon={faCheckCircle} size="sm" />
)}
</div>
</components.Option>
);
};
+1
View File
@@ -0,0 +1 @@
export * from "./RoleOption";
@@ -5,7 +5,9 @@ import { SecretSyncConnectionField } from "@app/components/secret-syncs/forms/Se
import { FilterableSelect, FormControl, Select, SelectItem } from "@app/components/v2";
import { RENDER_SYNC_SCOPES } from "@app/helpers/secretSyncs";
import {
TRenderEnvironmentGroup,
TRenderService,
useRenderConnectionListEnvironmentGroups,
useRenderConnectionListServices
} from "@app/hooks/api/appConnections/render";
import { SecretSync } from "@app/hooks/api/secretSyncs";
@@ -19,6 +21,7 @@ export const RenderSyncFields = () => {
>();
const connectionId = useWatch({ name: "connection.id", control });
const selectedScope = useWatch({ name: "destinationConfig.scope", control });
const { data: services = [], isPending: isServicesPending } = useRenderConnectionListServices(
connectionId,
@@ -27,11 +30,17 @@ export const RenderSyncFields = () => {
}
);
const { data: groups = [], isPending: isGroupsPending } =
useRenderConnectionListEnvironmentGroups(connectionId, {
enabled: Boolean(connectionId) && selectedScope === RenderSyncScope.EnvironmentGroup
});
return (
<>
<SecretSyncConnectionField
onChange={() => {
setValue("destinationConfig.serviceId", "");
setValue("destinationConfig.environmentGroupId", "");
setValue("destinationConfig.type", RenderSyncType.Env);
setValue("destinationConfig.scope", RenderSyncScope.Service);
}}
@@ -83,30 +92,67 @@ export const RenderSyncFields = () => {
</FormControl>
)}
/>
<Controller
name="destinationConfig.serviceId"
control={control}
render={({ field: { value, onChange }, fieldState: { error } }) => (
<FormControl errorText={error?.message} isError={Boolean(error?.message)} label="Service">
<FilterableSelect
isLoading={isServicesPending && Boolean(connectionId)}
isDisabled={!connectionId}
value={services ? (services.find((service) => service.id === value) ?? []) : []}
onChange={(option) => {
onChange((option as SingleValue<TRenderService>)?.id ?? null);
setValue(
"destinationConfig.serviceName",
(option as SingleValue<TRenderService>)?.name ?? ""
);
}}
options={services}
placeholder="Select a service..."
getOptionLabel={(option) => option.name}
getOptionValue={(option) => option.id.toString()}
/>
</FormControl>
)}
/>
{selectedScope === RenderSyncScope.Service && (
<Controller
name="destinationConfig.serviceId"
control={control}
render={({ field: { value, onChange }, fieldState: { error } }) => (
<FormControl
errorText={error?.message}
isError={Boolean(error?.message)}
label="Service"
>
<FilterableSelect
isLoading={isServicesPending && Boolean(connectionId)}
isDisabled={!connectionId}
value={services ? (services.find((service) => service.id === value) ?? []) : []}
onChange={(option) => {
onChange((option as SingleValue<TRenderService>)?.id ?? null);
setValue(
"destinationConfig.serviceName",
(option as SingleValue<TRenderService>)?.name ?? ""
);
}}
options={services}
placeholder="Select a service..."
getOptionLabel={(option) => option.name}
getOptionValue={(option) => option.id.toString()}
/>
</FormControl>
)}
/>
)}
{selectedScope === RenderSyncScope.EnvironmentGroup && (
<Controller
name="destinationConfig.environmentGroupId"
control={control}
render={({ field: { value, onChange }, fieldState: { error } }) => (
<FormControl
errorText={error?.message}
isError={Boolean(error?.message)}
label="Environment Group"
>
<FilterableSelect
isLoading={isGroupsPending && Boolean(connectionId)}
isDisabled={!connectionId}
value={groups ? (groups.find((g) => g.id === value) ?? []) : []}
onChange={(option) => {
onChange((option as SingleValue<TRenderEnvironmentGroup>)?.id ?? null);
setValue(
"destinationConfig.environmentGroupName",
(option as SingleValue<TRenderEnvironmentGroup>)?.name ?? ""
);
}}
options={groups}
placeholder="Select an environment group..."
getOptionLabel={(option) => option.name}
getOptionValue={(option) => option.id.toString()}
/>
</FormControl>
)}
/>
)}
</>
);
};
@@ -4,6 +4,7 @@ import { GenericFieldLabel } from "@app/components/secret-syncs";
import { TSecretSyncForm } from "@app/components/secret-syncs/forms/schemas";
import { Badge } from "@app/components/v2";
import { SecretSync } from "@app/hooks/api/secretSyncs";
import { RenderSyncScope } from "@app/hooks/api/secretSyncs/types/render-sync";
export const RenderSyncOptionsReviewFields = () => {
const { watch } = useFormContext<TSecretSyncForm & { destination: SecretSync.Render }>();
@@ -27,13 +28,20 @@ export const RenderSyncOptionsReviewFields = () => {
export const RenderSyncReviewFields = () => {
const { watch } = useFormContext<TSecretSyncForm & { destination: SecretSync.Render }>();
const serviceName = watch("destinationConfig.serviceName");
const scope = watch("destinationConfig.scope");
const config = watch("destinationConfig");
return (
<>
<GenericFieldLabel label="Scope">{scope}</GenericFieldLabel>
<GenericFieldLabel label="Service">{serviceName}</GenericFieldLabel>
<GenericFieldLabel label="Scope">{config.scope}</GenericFieldLabel>
{config.scope === RenderSyncScope.Service ? (
<GenericFieldLabel label="Service">
{config.serviceName ?? config.serviceId}
</GenericFieldLabel>
) : (
<GenericFieldLabel label="Service">
{config.environmentGroupName ?? config.environmentGroupId}
</GenericFieldLabel>
)}
</>
);
};
@@ -17,6 +17,12 @@ export const RenderSyncDestinationSchema = BaseSecretSyncSchema(
serviceId: z.string().trim().min(1, "Service is required"),
serviceName: z.string().trim().optional(),
type: z.nativeEnum(RenderSyncType)
}),
z.object({
scope: z.literal(RenderSyncScope.EnvironmentGroup),
environmentGroupId: z.string().trim().min(1, "Environment Group ID is required"),
environmentGroupName: z.string().trim().optional(),
type: z.nativeEnum(RenderSyncType)
})
])
})
@@ -143,6 +143,13 @@ export enum ProjectPermissionSecretScanningConfigActions {
Update = "update-configs"
}
export enum ProjectPermissionSecretEventActions {
SubscribeCreated = "subscribe-on-created",
SubscribeUpdated = "subscribe-on-updated",
SubscribeDeleted = "subscribe-on-deleted",
SubscribeImportMutations = "subscribe-on-import-mutations"
}
export enum PermissionConditionOperators {
$IN = "$in",
$ALL = "$all",
@@ -172,7 +179,8 @@ export type ConditionalProjectPermissionSubject =
| ProjectPermissionSub.CertificateTemplates
| ProjectPermissionSub.SecretFolders
| ProjectPermissionSub.SecretImports
| ProjectPermissionSub.SecretRotation;
| ProjectPermissionSub.SecretRotation
| ProjectPermissionSub.SecretEvents;
export const formatedConditionsOperatorNames: { [K in PermissionConditionOperators]: string } = {
[PermissionConditionOperators.$EQ]: "equal to",
@@ -250,7 +258,8 @@ export enum ProjectPermissionSub {
Commits = "commits",
SecretScanningDataSources = "secret-scanning-data-sources",
SecretScanningFindings = "secret-scanning-findings",
SecretScanningConfigs = "secret-scanning-configs"
SecretScanningConfigs = "secret-scanning-configs",
SecretEvents = "secret-events"
}
export type SecretSubjectFields = {
@@ -260,6 +269,14 @@ export type SecretSubjectFields = {
secretTags: string[];
};
export type SecretEventSubjectFields = {
environment: string;
secretPath: string;
secretName: string;
secretTags: string[];
action: string;
};
export type SecretFolderSubjectFields = {
environment: string;
secretPath: string;
@@ -403,6 +420,13 @@ export type ProjectPermissionSet =
ProjectPermissionSub.SecretScanningDataSources
]
| [ProjectPermissionSecretScanningFindingActions, ProjectPermissionSub.SecretScanningFindings]
| [ProjectPermissionSecretScanningConfigActions, ProjectPermissionSub.SecretScanningConfigs];
| [ProjectPermissionSecretScanningConfigActions, ProjectPermissionSub.SecretScanningConfigs]
| [
ProjectPermissionSecretEventActions,
(
| ProjectPermissionSub.SecretEvents
| (ForcedSubject<ProjectPermissionSub.SecretEvents> & SecretEventSubjectFields)
)
];
export type TProjectPermission = MongoAbility<ProjectPermissionSet>;
-23
View File
@@ -23,29 +23,6 @@ export const formatDateTime = ({
return format(date, dateFormat);
};
// Helper function to convert duration to seconds
export const durationToSeconds = (
value: number,
unit: "s" | "m" | "h" | "d" | "w" | "y"
): number => {
switch (unit) {
case "s":
return value;
case "m":
return value * 60;
case "h":
return value * 60 * 60;
case "d":
return value * 60 * 60 * 24;
case "w":
return value * 60 * 60 * 24 * 7;
case "y":
return value * 60 * 60 * 24 * 365;
default:
return 0;
}
};
// Helper function to convert seconds to value and unit
export const getObjectFromSeconds = (
totalSeconds: number,
-84
View File
@@ -1,84 +0,0 @@
import Aes256Gcm from "@app/components/utilities/cryptography/aes-256-gcm";
import { deriveArgonKey } from "@app/components/utilities/cryptography/crypto";
/**
* @param {Object} obj
* @param {Number} obj.encryptionVersion
* @param {String} obj.encryptedPrivateKey
* @param {String} obj.iv
* @param {String} obj.tag
* @param {String} obj.password
* @param {String} obj.salt
* @param {String} obj.protectedKey
* @param {String} obj.protectedKeyIV
* @param {String} obj.protectedKeyTag
*/
const decryptPrivateKeyHelper = async ({
encryptionVersion,
encryptedPrivateKey,
iv,
tag,
password,
salt,
protectedKey,
protectedKeyIV,
protectedKeyTag
}: {
encryptionVersion: number;
encryptedPrivateKey: string;
iv: string;
tag: string;
password: string;
salt: string;
protectedKey?: string;
protectedKeyIV?: string;
protectedKeyTag?: string;
}) => {
let privateKey;
try {
if (encryptionVersion === 1) {
privateKey = Aes256Gcm.decrypt({
ciphertext: encryptedPrivateKey,
iv,
tag,
secret: password
.slice(0, 32)
.padStart(32 + (password.slice(0, 32).length - new Blob([password]).size), "0")
});
} else if (encryptionVersion === 2 && protectedKey && protectedKeyIV && protectedKeyTag) {
const derivedKey = await deriveArgonKey({
password,
salt,
mem: 65536,
time: 3,
parallelism: 1,
hashLen: 32
});
if (!derivedKey) throw new Error("Failed to generate derived key");
const key = Aes256Gcm.decrypt({
ciphertext: protectedKey,
iv: protectedKeyIV,
tag: protectedKeyTag,
secret: Buffer.from(derivedKey.hash)
});
// decrypt back the private key
privateKey = Aes256Gcm.decrypt({
ciphertext: encryptedPrivateKey,
iv,
tag,
secret: Buffer.from(key, "hex")
});
} else {
throw new Error("Insufficient details to decrypt private key");
}
} catch {
throw new Error("Failed to decrypt private key");
}
return privateKey;
};
export { decryptPrivateKeyHelper };
+4
View File
@@ -212,5 +212,9 @@ export const RENDER_SYNC_SCOPES: Record<RenderSyncScope, { name: string; descrip
[RenderSyncScope.Service]: {
name: "Service",
description: "Infisical will sync secrets to the specified Render service."
},
[RenderSyncScope.EnvironmentGroup]: {
name: "EnvironmentGroup",
description: "Infisical will sync secrets to the specified Render environment group."
}
};
@@ -6,10 +6,12 @@ import { apiRequest } from "@app/config/request";
import { accessApprovalKeys } from "./queries";
import {
TAccessApproval,
TAccessApprovalRequest,
TCreateAccessPolicyDTO,
TCreateAccessRequestDTO,
TDeleteSecretPolicyDTO,
TUpdateAccessPolicyDTO
TUpdateAccessPolicyDTO,
TUpdateAccessRequestDTO
} from "./types";
export const useCreateAccessApprovalPolicy = () => {
@@ -134,6 +136,25 @@ export const useCreateAccessRequest = () => {
});
};
export const useUpdateAccessRequest = () => {
const queryClient = useQueryClient();
return useMutation<TAccessApprovalRequest, object, TUpdateAccessRequestDTO>({
mutationFn: async ({ requestId, ...payload }) => {
const { data } = await apiRequest.patch<{ approval: TAccessApprovalRequest }>(
`/api/v1/access-approvals/requests/${requestId}`,
payload
);
return data.approval;
},
onSuccess: (_, { projectSlug }) => {
queryClient.invalidateQueries({
queryKey: accessApprovalKeys.getAccessApprovalRequests(projectSlug)
});
}
});
};
export const useReviewAccessRequest = () => {
const queryClient = useQueryClient();
return useMutation<
@@ -24,7 +24,7 @@ export const accessApprovalKeys = {
envSlug?: string,
requestedBy?: string,
bypassReason?: string
) => [{ projectSlug, envSlug, requestedBy, bypassReason }, "access-approvals-requests"] as const,
) => ["access-approvals-requests", projectSlug, envSlug, requestedBy, bypassReason] as const,
getAccessApprovalRequestCount: (projectSlug: string, policyId?: string) =>
[{ projectSlug }, "access-approval-request-count", ...(policyId ? [policyId] : [])] as const
};
+14 -2
View File
@@ -36,6 +36,7 @@ export type Approver = {
type: ApproverType;
sequence?: number;
approvalsRequired?: number;
isOrgMembershipActive: boolean;
};
export type Bypasser = {
@@ -82,6 +83,7 @@ export type TAccessApprovalRequest = {
name: string;
approvals: number;
approvers: {
isOrgMembershipActive: boolean;
userId: string;
sequence?: number;
approvalsRequired?: number;
@@ -98,11 +100,14 @@ export type TAccessApprovalRequest = {
};
reviewers: {
isOrgMembershipActive: boolean;
userId: string;
status: string;
}[];
note?: string;
editNote?: string;
editedByUserId?: string;
};
export type TAccessApproval = {
@@ -146,6 +151,13 @@ export type TCreateAccessRequestDTO = {
note?: string;
} & Omit<TProjectUserPrivilege, "id" | "createdAt" | "updatedAt" | "slug" | "projectMembershipId">;
export type TUpdateAccessRequestDTO = {
requestId: string;
editNote: string;
temporaryRange: string;
projectSlug: string;
};
export type TGetAccessApprovalRequestsDTO = {
projectSlug: string;
policyId?: string;
@@ -168,7 +180,7 @@ export type TCreateAccessPolicyDTO = {
projectSlug: string;
name?: string;
environments: string[];
approvers?: Approver[];
approvers?: Omit<Approver, "isOrgMembershipActive">[];
bypassers?: Bypasser[];
approvals?: number;
secretPath: string;
@@ -181,7 +193,7 @@ export type TCreateAccessPolicyDTO = {
export type TUpdateAccessPolicyDTO = {
id: string;
name?: string;
approvers?: Approver[];
approvers?: Omit<Approver, "isOrgMembershipActive">[];
bypassers?: Bypasser[];
secretPath?: string;
environments?: string[];
-9
View File
@@ -74,15 +74,6 @@ export type TCreateAdminUserDTO = {
password: string;
firstName: string;
lastName?: string;
protectedKey: string;
protectedKeyTag: string;
protectedKeyIV: string;
encryptedPrivateKey: string;
encryptedPrivateKeyIV: string;
encryptedPrivateKeyTag: string;
publicKey: string;
verifier: string;
salt: string;
};
export type AdminGetOrganizationsFilters = {
@@ -3,12 +3,14 @@ import { useQuery, UseQueryOptions } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { appConnectionKeys } from "../queries";
import { TRenderService } from "./types";
import { TRenderEnvironmentGroup, TRenderService } from "./types";
const renderConnectionKeys = {
all: [...appConnectionKeys.all, "render"] as const,
listServices: (connectionId: string) =>
[...renderConnectionKeys.all, "services", connectionId] as const
[...renderConnectionKeys.all, "services", connectionId] as const,
listEnvironmentGroups: (connectionId: string) =>
[...renderConnectionKeys.all, "environment-groups", connectionId] as const
};
export const useRenderConnectionListServices = (
@@ -35,3 +37,28 @@ export const useRenderConnectionListServices = (
...options
});
};
export const useRenderConnectionListEnvironmentGroups = (
connectionId: string,
options?: Omit<
UseQueryOptions<
TRenderEnvironmentGroup[],
unknown,
TRenderEnvironmentGroup[],
ReturnType<typeof renderConnectionKeys.listEnvironmentGroups>
>,
"queryKey" | "queryFn"
>
) => {
return useQuery({
queryKey: renderConnectionKeys.listEnvironmentGroups(connectionId),
queryFn: async () => {
const { data } = await apiRequest.get<TRenderEnvironmentGroup[]>(
`/api/v1/app-connections/render/${connectionId}/environment-groups`
);
return data;
},
...options
});
};
@@ -2,3 +2,8 @@ export type TRenderService = {
id: string;
name: string;
};
export type TRenderEnvironmentGroup = {
id: string;
name: string;
};
@@ -43,12 +43,15 @@ export const useUpdateDynamicSecret = () => {
);
return data.dynamicSecret;
},
onSuccess: (_, { path, environmentSlug, projectSlug }) => {
onSuccess: (_, { path, environmentSlug, projectSlug, name }) => {
// TODO: optimize but currently don't pass projectId
queryClient.invalidateQueries({ queryKey: dashboardKeys.all() });
queryClient.invalidateQueries({
queryKey: dynamicSecretKeys.list({ path, projectSlug, environmentSlug })
});
queryClient.invalidateQueries({
queryKey: dynamicSecretKeys.details({ path, projectSlug, environmentSlug, name })
});
}
});
};
+34 -1
View File
@@ -37,7 +37,8 @@ export enum DynamicSecretProviders {
Kubernetes = "kubernetes",
Vertica = "vertica",
GcpIam = "gcp-iam",
Github = "github"
Github = "github",
Couchbase = "couchbase"
}
export enum KubernetesDynamicSecretCredentialType {
@@ -353,6 +354,38 @@ export type TDynamicSecretProvider =
installationId: number;
privateKey: string;
};
}
| {
type: DynamicSecretProviders.Couchbase;
inputs: {
url: string;
orgId: string;
projectId: string;
clusterId: string;
roles: string[];
buckets:
| string
| Array<{
name: string;
scopes?: Array<{
name: string;
collections?: string[];
}>;
}>;
passwordRequirements?: {
length: number;
required: {
lowercase: number;
uppercase: number;
digits: number;
symbols: number;
};
allowedSymbols?: string;
};
auth: {
apiKey: string;
};
};
};
export type TCreateDynamicSecretDTO = {
@@ -104,6 +104,7 @@ export const useUpdateOrg = () => {
mutationFn: ({
name,
authEnforced,
googleSsoAuthEnforced,
scimEnabled,
slug,
orgId,
@@ -125,6 +126,7 @@ export const useUpdateOrg = () => {
return apiRequest.patch(`/api/v1/organization/${orgId}`, {
name,
authEnforced,
googleSsoAuthEnforced,
scimEnabled,
slug,
defaultMembershipRoleSlug,
@@ -9,6 +9,7 @@ export type Organization = {
createAt: string;
updatedAt: string;
authEnforced: boolean;
googleSsoAuthEnforced: boolean;
bypassOrgAuthEnabled: boolean;
orgAuthMethod: string;
scimEnabled: boolean;
@@ -34,6 +35,7 @@ export type UpdateOrgDTO = {
orgId: string;
name?: string;
authEnforced?: boolean;
googleSsoAuthEnforced?: boolean;
scimEnabled?: boolean;
slug?: string;
defaultMembershipRoleSlug?: string;
@@ -20,6 +20,7 @@ export enum ApproverType {
}
export type Approver = {
isOrgMembershipActive: boolean;
id: string;
type: ApproverType;
};
@@ -49,7 +50,7 @@ export type TCreateSecretPolicyDTO = {
name?: string;
environments: string[];
secretPath: string;
approvers?: Approver[];
approvers?: Omit<Approver, "isOrgMembershipActive">[];
bypassers?: Bypasser[];
approvals?: number;
enforcementLevel: EnforcementLevel;
@@ -59,7 +60,7 @@ export type TCreateSecretPolicyDTO = {
export type TUpdateSecretPolicyDTO = {
id: string;
name?: string;
approvers?: Approver[];
approvers?: Omit<Approver, "isOrgMembershipActive">[];
bypassers?: Bypasser[];
secretPath?: string;
approvals?: number;
@@ -53,6 +53,7 @@ export type TSecretApprovalRequest = {
firstName: string;
lastName: string;
username: string;
isOrgMembershipActive: boolean;
}[];
workspace: string;
environment: string;
@@ -62,6 +63,7 @@ export type TSecretApprovalRequest = {
status: "open" | "close";
policy: Omit<TSecretApprovalPolicy, "approvers" | "bypassers"> & {
approvers: {
isOrgMembershipActive: boolean;
userId: string;
email: string;
firstName: string;
@@ -4,12 +4,19 @@ import { RootSyncOptions, TRootSecretSync } from "@app/hooks/api/secretSyncs/typ
export type TRenderSync = TRootSecretSync & {
destination: SecretSync.Render;
destinationConfig: {
scope: RenderSyncScope.Service;
type: RenderSyncType;
serviceId: string;
serviceName?: string;
};
destinationConfig:
| {
type: RenderSyncType;
scope: RenderSyncScope.Service;
serviceId: string;
serviceName?: string | undefined;
}
| {
type: RenderSyncType;
scope: RenderSyncScope.EnvironmentGroup;
environmentGroupId: string;
environmentGroupName?: string | undefined;
};
connection: {
app: AppConnection.Render;
@@ -23,7 +30,8 @@ export type TRenderSync = TRootSecretSync & {
};
export enum RenderSyncScope {
Service = "service"
Service = "service",
EnvironmentGroup = "environment-group"
}
export enum RenderSyncType {
@@ -48,6 +48,7 @@ export type SubscriptionPlan = {
externalKms: boolean;
pkiEst: boolean;
enforceMfa: boolean;
enforceGoogleSSO: boolean;
projectTemplates: boolean;
kmip: boolean;
secretScanning: boolean;
+4 -4
View File
@@ -26,16 +26,16 @@ export const useAddUserToWsNonE2EE = () => {
});
};
export const sendEmailVerificationCode = async (username: string) => {
export const sendEmailVerificationCode = async (token: string) => {
return apiRequest.post("/api/v2/users/me/emails/code", {
username
token
});
};
export const useSendEmailVerificationCode = () => {
return useMutation({
mutationFn: async (username: string) => {
await sendEmailVerificationCode(username);
mutationFn: async (token: string) => {
await sendEmailVerificationCode(token);
return {};
}
});
+1
View File
@@ -83,6 +83,7 @@ export type TProjectMembership = {
export type TWorkspaceUser = {
id: string;
user: {
isOrgMembershipActive: boolean;
email: string;
username: string;
firstName: string;
@@ -240,6 +240,13 @@ export const Navbar = () => {
return;
}
if (org.googleSsoAuthEnforced) {
await logout.mutateAsync();
window.open(`/api/v1/sso/redirect/google?org_slug=${org.slug}`);
window.close();
return;
}
handleOrgChange(org?.id);
}}
variant="plain"
-77
View File
@@ -1,77 +0,0 @@
import crypto from "crypto";
import jsrp from "jsrp";
import Aes256Gcm from "@app/components/utilities/cryptography/aes-256-gcm";
import { deriveArgonKey, generateKeyPair } from "@app/components/utilities/cryptography/crypto";
export const generateUserPassKey = async (
email: string,
password: string,
fipsEnabled: boolean
) => {
// eslint-disable-next-line new-cap
const client = new jsrp.client();
const { publicKey, privateKey } = await generateKeyPair(fipsEnabled);
await new Promise((resolve) => {
client.init({ username: email, password }, () => resolve(null));
});
const { salt, verifier } = await new Promise<{ salt: string; verifier: string }>(
(resolve, reject) => {
client.createVerifier((err, res) => {
if (err) return reject(err);
return resolve(res);
});
}
);
const derivedKey = await deriveArgonKey({
password,
salt,
mem: 65536,
time: 3,
parallelism: 1,
hashLen: 32
});
if (!derivedKey) throw new Error("Failed to derive key from password");
const key = crypto.randomBytes(32);
// create encrypted private key by encrypting the private
// key with the symmetric key [key]
const {
ciphertext: encryptedPrivateKey,
iv: encryptedPrivateKeyIV,
tag: encryptedPrivateKeyTag
} = Aes256Gcm.encrypt({
text: privateKey,
secret: key
});
// create the protected key by encrypting the symmetric key
// [key] with the derived key
const {
ciphertext: protectedKey,
iv: protectedKeyIV,
tag: protectedKeyTag
} = Aes256Gcm.encrypt({
text: key.toString("hex"),
secret: Buffer.from(derivedKey.hash)
});
return {
protectedKey,
protectedKeyTag,
protectedKeyIV,
encryptedPrivateKey,
encryptedPrivateKeyIV,
encryptedPrivateKeyTag,
publicKey,
verifier,
salt,
privateKey
};
};
@@ -12,7 +12,6 @@ import SecurityClient from "@app/components/utilities/SecurityClient";
import { Button, ContentLoader, FormControl, Input } from "@app/components/v2";
import { useServerConfig } from "@app/context";
import { useCreateAdminUser, useSelectOrganization } from "@app/hooks/api";
import { generateUserPassKey } from "@app/lib/crypto";
const formSchema = z
.object({
@@ -48,17 +47,11 @@ export const SignUpPage = () => {
// avoid multi submission
if (isSubmitting) return;
try {
const { privateKey, ...userPass } = await generateUserPassKey(
email,
password,
config.fipsEnabled
);
const res = await createAdminUser({
email,
password,
firstName,
lastName,
...userPass
lastName
});
SecurityClient.setToken(res.token);
@@ -82,25 +82,40 @@ export const SelectOrganizationSection = () => {
}
}
if (organization.authEnforced && !canBypassOrgAuth) {
if ((organization.authEnforced || organization.googleSsoAuthEnforced) && !canBypassOrgAuth) {
const authToken = jwtDecode(getAuthToken()) as { authMethod: AuthMethod };
// org has an org-level auth method enabled (e.g. SAML)
// -> logout + redirect to SAML SSO
await logout.mutateAsync();
let url = "";
if (organization.orgAuthMethod === AuthMethod.OIDC) {
url = `/api/v1/sso/oidc/login?orgSlug=${organization.slug}${
callbackPort ? `&callbackPort=${callbackPort}` : ""
}`;
} else {
} else if (organization.orgAuthMethod === AuthMethod.SAML) {
url = `/api/v1/sso/redirect/saml2/organizations/${organization.slug}`;
if (callbackPort) {
url += `?callback_port=${callbackPort}`;
}
} else if (
organization.googleSsoAuthEnforced &&
authToken.authMethod !== AuthMethod.GOOGLE
) {
url = `/api/v1/sso/redirect/google?org_slug=${organization.slug}`;
if (callbackPort) {
url += `&callback_port=${callbackPort}`;
}
}
window.location.href = url;
return;
// we are conditionally checking if the url is set because it may not be set if google SSO is enforced, but the user is already logged in with google SSO
// see line 103-106
if (url) {
await logout.mutateAsync();
window.location.href = url;
return;
}
}
const { token, isMfaEnabled, mfaMethod } = await selectOrg
@@ -114,7 +114,16 @@ export const EmailConfirmationStep = ({
const resendCode = async () => {
try {
await sendEmailVerificationCode(username);
const queryParams = new URLSearchParams(window.location.search);
const token = queryParams.get("token");
if (!token) {
createNotification({
text: "Failed to resend code, no token found",
type: "error"
});
return;
}
await sendEmailVerificationCode(token);
createNotification({
text: "Successfully resent code",
type: "success"
@@ -3,6 +3,7 @@ import { Controller, useFieldArray, useForm } from "react-hook-form";
import { faPlus, faQuestionCircle, faXmark } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod";
import ms from "ms";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
@@ -25,7 +26,7 @@ import {
OrgPermissionMachineIdentityAuthTemplateActions,
OrgPermissionSubjects
} from "@app/context/OrgPermissionContext/types";
import { durationToSeconds, getObjectFromSeconds } from "@app/helpers/datetime";
import { getObjectFromSeconds } from "@app/helpers/datetime";
import {
MachineIdentityAuthMethod,
useAddIdentityLdapAuth,
@@ -334,14 +335,9 @@ export const IdentityLdapAuthForm = ({
lockoutCounterResetUnit
} = formData;
const lockoutDurationSeconds = durationToSeconds(
Number(lockoutDurationValue),
lockoutDurationUnit
);
const lockoutCounterResetSeconds = durationToSeconds(
Number(lockoutCounterResetValue),
lockoutCounterResetUnit
);
const lockoutDurationSeconds = ms(`${lockoutDurationValue}${lockoutDurationUnit}`) / 1000;
const lockoutCounterResetSeconds =
ms(`${lockoutCounterResetValue}${lockoutCounterResetUnit}`) / 1000;
const basePayload = {
organizationId: orgId,
@@ -3,6 +3,7 @@ import { Controller, useFieldArray, useForm } from "react-hook-form";
import { faPlus, faXmark } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod";
import ms from "ms";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
@@ -17,7 +18,7 @@ import {
Tabs
} from "@app/components/v2";
import { useOrganization, useSubscription } from "@app/context";
import { durationToSeconds, getObjectFromSeconds } from "@app/helpers/datetime";
import { getObjectFromSeconds } from "@app/helpers/datetime";
import {
useAddIdentityUniversalAuth,
useGetIdentityUniversalAuth,
@@ -222,14 +223,9 @@ export const IdentityUniversalAuthForm = ({
try {
if (!identityId) return;
const lockoutDurationSeconds = durationToSeconds(
Number(lockoutDurationValue),
lockoutDurationUnit
);
const lockoutCounterResetSeconds = durationToSeconds(
Number(lockoutCounterResetValue),
lockoutCounterResetUnit
);
const lockoutDurationSeconds = ms(`${lockoutDurationValue}${lockoutDurationUnit}`) / 1000;
const lockoutCounterResetSeconds =
ms(`${lockoutCounterResetValue}${lockoutCounterResetUnit}`) / 1000;
if (data) {
// update universal auth configuration
@@ -1,7 +1,6 @@
import ms from "ms";
import { z } from "zod";
import { durationToSeconds } from "@app/helpers/datetime";
export function superRefineLockout(
data: {
lockoutDurationValue: string;
@@ -44,14 +43,9 @@ export function superRefineLockout(
}
if (!isAnyParseError) {
const lockoutDurationInSeconds = durationToSeconds(
parsedLockoutDuration,
lockoutDurationUnit
);
const lockoutCounterResetInSeconds = durationToSeconds(
parsedLockoutCounterReset,
lockoutCounterResetUnit
);
const lockoutDurationInSeconds = ms(`${parsedLockoutDuration}${lockoutDurationUnit}`) / 1000;
const lockoutCounterResetInSeconds =
ms(`${parsedLockoutCounterReset}${lockoutCounterResetUnit}`) / 1000;
if (lockoutDurationInSeconds > 86400 || lockoutDurationInSeconds < 30) {
ctx.addIssue({
@@ -4,6 +4,7 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { RoleOption } from "@app/components/roles";
import {
Button,
FilterableSelect,
@@ -45,7 +46,11 @@ const addMemberFormSchema = z.object({
)
.default([]),
projectRoleSlug: z.string().min(1).default(DEFAULT_ORG_AND_PROJECT_MEMBER_ROLE_SLUG),
organizationRole: z.object({ name: z.string(), slug: z.string() })
organizationRole: z.object({
name: z.string(),
slug: z.string(),
description: z.string().optional()
})
});
type TAddMemberForm = z.infer<typeof addMemberFormSchema>;
@@ -238,6 +243,7 @@ export const AddOrgMemberModal = ({
getOptionLabel={(option) => option.name}
value={value}
onChange={onChange}
components={{ Option: RoleOption }}
/>
</FormControl>
)}
@@ -36,7 +36,8 @@ type GithubFormData = BaseFormData &
type GithubRadarFormData = BaseFormData &
Pick<TGitHubRadarConnection, "name" | "method" | "description">;
type GitLabFormData = BaseFormData & Pick<TGitLabConnection, "name" | "method" | "description">;
type GitLabFormData = BaseFormData &
Pick<TGitLabConnection, "name" | "method" | "description" | "credentials">;
type AzureKeyVaultFormData = BaseFormData &
Pick<TAzureKeyVaultConnection, "name" | "method" | "description"> &
@@ -147,7 +148,7 @@ export const OAuthCallbackPage = () => {
clearState(AppConnection.GitLab);
const { connectionId, name, description, returnUrl, isUpdate } = formData;
const { connectionId, name, description, returnUrl, isUpdate, credentials } = formData;
try {
if (isUpdate && connectionId) {
@@ -155,7 +156,8 @@ export const OAuthCallbackPage = () => {
app: AppConnection.GitLab,
connectionId,
credentials: {
code: code as string
code: code as string,
instanceUrl: credentials.instanceUrl as string
}
});
} else {
@@ -165,7 +167,8 @@ export const OAuthCallbackPage = () => {
description,
method: GitLabConnectionMethod.OAuth,
credentials: {
code: code as string
code: code as string,
instanceUrl: credentials.instanceUrl as string
}
});
}
@@ -118,6 +118,7 @@ const Page = () => {
authMethod={popUp.viewAuthMethod.data?.authMethod}
lockedOut={popUp.viewAuthMethod.data?.lockedOut || false}
identityId={identityId}
onResetAllLockouts={popUp.viewAuthMethod.data?.refetchIdentity}
/>
</div>
);
@@ -2,7 +2,7 @@ import { faCog, faLock, faPlus } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { OrgPermissionCan } from "@app/components/permissions";
import { Button } from "@app/components/v2";
import { Button, Tooltip } from "@app/components/v2";
import { OrgPermissionIdentityActions, OrgPermissionSubjects } from "@app/context";
import { IdentityAuthMethod, identityAuthToNameMap, useGetIdentityById } from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp";
@@ -16,7 +16,7 @@ type Props = {
};
export const IdentityAuthenticationSection = ({ identityId, handlePopUpOpen }: Props) => {
const { data } = useGetIdentityById(identityId);
const { data, refetch } = useGetIdentityById(identityId);
return data ? (
<div className="mt-4 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
@@ -31,7 +31,8 @@ export const IdentityAuthenticationSection = ({ identityId, handlePopUpOpen }: P
onClick={() =>
handlePopUpOpen("viewAuthMethod", {
authMethod,
lockedOut: data.identity.activeLockoutAuthMethods.includes(authMethod)
lockedOut: data.identity.activeLockoutAuthMethods.includes(authMethod),
refetchIdentity: refetch
})
}
type="button"
@@ -40,7 +41,9 @@ export const IdentityAuthenticationSection = ({ identityId, handlePopUpOpen }: P
<span>{identityAuthToNameMap[authMethod]}</span>
<div className="flex gap-2">
{data.identity.activeLockoutAuthMethods.includes(authMethod) && (
<FontAwesomeIcon icon={faLock} size="xs" className="text-red-400/50" />
<Tooltip content="Auth method has active lockouts">
<FontAwesomeIcon icon={faLock} size="xs" className="text-red-400/50" />
</Tooltip>
)}
<FontAwesomeIcon icon={faCog} size="xs" className="text-mineshaft-400" />
</div>
@@ -13,7 +13,8 @@ export const LockoutFields = ({
clearLockoutsResult,
lockedOut,
identityId,
data
data,
onResetAllLockouts
}: {
clearLockoutsResult: UseMutationResult<number, object, { identityId: string }, unknown>;
lockedOut: boolean;
@@ -24,6 +25,7 @@ export const LockoutFields = ({
lockoutDurationSeconds: number;
lockoutCounterResetSeconds: number;
};
onResetAllLockouts: () => void;
}) => {
const { mutateAsync, isPending } = clearLockoutsResult;
@@ -37,6 +39,7 @@ export const LockoutFields = ({
type: "success"
});
setLockedOutState(false);
onResetAllLockouts();
} catch (error) {
console.error(error);
createNotification({
@@ -59,7 +62,7 @@ export const LockoutFields = ({
isLoading={isPending}
colorSchema="secondary"
>
Clear All Lockouts
Reset All Lockouts
</Button>
)}
</OrgPermissionCan>
@@ -41,6 +41,7 @@ type Props = {
isOpen: boolean;
onOpenChange: (isOpen: boolean) => void;
onDeleteAuthMethod: () => void;
onResetAllLockouts: () => void;
};
type TRevokeOptions = {
@@ -52,8 +53,12 @@ export const Content = ({
identityId,
authMethod,
lockedOut,
onDeleteAuthMethod
}: Pick<Props, "authMethod" | "lockedOut" | "identityId" | "onDeleteAuthMethod">) => {
onDeleteAuthMethod,
onResetAllLockouts
}: Pick<
Props,
"authMethod" | "lockedOut" | "identityId" | "onDeleteAuthMethod" | "onResetAllLockouts"
>) => {
const { currentOrg } = useOrganization();
const orgId = currentOrg?.id || "";
@@ -161,6 +166,7 @@ export const Content = ({
<Component
identityId={identityId}
onDelete={handleDelete}
onResetAllLockouts={onResetAllLockouts}
popUp={popUp}
handlePopUpOpen={handlePopUpOpen}
handlePopUpToggle={handlePopUpToggle}
@@ -188,7 +194,8 @@ export const ViewIdentityAuthModal = ({
onOpenChange,
authMethod,
identityId,
lockedOut
lockedOut,
onResetAllLockouts
}: Omit<Props, "onDeleteAuthMethod">) => {
if (!identityId || !authMethod) return null;
@@ -200,6 +207,7 @@ export const ViewIdentityAuthModal = ({
authMethod={authMethod}
lockedOut={lockedOut}
onDeleteAuthMethod={() => onOpenChange(false)}
onResetAllLockouts={() => onResetAllLockouts()}
/>
</ModalContent>
</Modal>
@@ -16,7 +16,8 @@ export const ViewIdentityLdapAuthContent = ({
handlePopUpOpen,
onDelete,
popUp,
lockedOut
lockedOut,
onResetAllLockouts
}: ViewAuthMethodProps) => {
const { data, isPending } = useGetIdentityLdapAuth(identityId);
const clearLockoutsResult = useClearIdentityLdapAuthLockouts();
@@ -106,6 +107,7 @@ export const ViewIdentityLdapAuthContent = ({
lockedOut={lockedOut}
clearLockoutsResult={clearLockoutsResult}
data={data}
onResetAllLockouts={onResetAllLockouts}
/>
</ViewIdentityContentWrapper>
);
@@ -22,7 +22,8 @@ export const ViewIdentityUniversalAuthContent = ({
handlePopUpOpen,
onDelete,
popUp,
lockedOut
lockedOut,
onResetAllLockouts
}: ViewAuthMethodProps) => {
const { data, isPending } = useGetIdentityUniversalAuth(identityId);
const { data: clientSecrets = [], isPending: clientSecretsPending } =
@@ -94,6 +95,7 @@ export const ViewIdentityUniversalAuthContent = ({
lockedOut={lockedOut}
clearLockoutsResult={clearLockoutsResult}
data={data}
onResetAllLockouts={onResetAllLockouts}
/>
<div className="col-span-2 my-3">
<div className="mb-3 border-b border-mineshaft-500 pb-2">
@@ -10,4 +10,5 @@ export type ViewAuthMethodProps = {
) => void;
popUp: UsePopUpState<["revokeAuthMethod", "upgradePlan", "identityAuthMethod"]>;
lockedOut: boolean;
onResetAllLockouts: () => void;
};
@@ -1,13 +1,14 @@
import { useEffect } from "react";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import ms from "ms";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { OrgPermissionCan } from "@app/components/permissions";
import { Button, FormControl, Input, Select, SelectItem } from "@app/components/v2";
import { OrgPermissionActions, OrgPermissionSubjects, useOrganization } from "@app/context";
import { durationToSeconds, getObjectFromSeconds } from "@app/helpers/datetime";
import { getObjectFromSeconds } from "@app/helpers/datetime";
import { useUpdateOrg } from "@app/hooks/api";
const MAX_SHARED_SECRET_LIFETIME_SECONDS = 30 * 24 * 60 * 60; // 30 days in seconds
@@ -25,7 +26,7 @@ const formSchema = z
.superRefine((data, ctx) => {
const { maxLifetimeValue, maxLifetimeUnit } = data;
const durationInSeconds = durationToSeconds(maxLifetimeValue, maxLifetimeUnit);
const durationInSeconds = ms(`${maxLifetimeValue}${maxLifetimeUnit}`) / 1000;
if (durationInSeconds > MAX_SHARED_SECRET_LIFETIME_SECONDS) {
ctx.addIssue({
@@ -90,10 +91,8 @@ export const OrgSecretShareLimitSection = () => {
const handleFormSubmit = async (formData: TForm) => {
try {
const maxSharedSecretLifetimeSeconds = durationToSeconds(
formData.maxLifetimeValue,
formData.maxLifetimeUnit
);
const maxSharedSecretLifetimeSeconds =
ms(`${formData.maxLifetimeValue}${formData.maxLifetimeUnit}`) / 1000;
await mutateAsync({
orgId: currentOrg.id,
@@ -1,5 +1,6 @@
import { faInfoCircle } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { twMerge } from "tailwind-merge";
import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";
import { createNotification } from "@app/components/notifications";
@@ -14,7 +15,21 @@ import {
import { useLogoutUser, useUpdateOrg } from "@app/hooks/api";
import { usePopUp } from "@app/hooks/usePopUp";
export const OrgGeneralAuthSection = () => {
enum EnforceAuthType {
SAML = "saml",
GOOGLE = "google",
OIDC = "oidc"
}
export const OrgGeneralAuthSection = ({
isSamlConfigured,
isOidcConfigured,
isGoogleConfigured
}: {
isSamlConfigured: boolean;
isOidcConfigured: boolean;
isGoogleConfigured: boolean;
}) => {
const { currentOrg } = useOrganization();
const { subscription } = useSubscription();
const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["upgradePlan"] as const);
@@ -23,27 +38,61 @@ export const OrgGeneralAuthSection = () => {
const logout = useLogoutUser();
const handleEnforceOrgAuthToggle = async (value: boolean) => {
const handleEnforceOrgAuthToggle = async (value: boolean, type: EnforceAuthType) => {
try {
if (!currentOrg?.id) return;
if (!subscription?.samlSSO) {
handlePopUpOpen("upgradePlan");
return;
if (type === EnforceAuthType.SAML) {
if (!subscription?.samlSSO) {
handlePopUpOpen("upgradePlan");
return;
}
await mutateAsync({
orgId: currentOrg?.id,
authEnforced: value
});
} else if (type === EnforceAuthType.GOOGLE) {
if (!subscription?.enforceGoogleSSO) {
handlePopUpOpen("upgradePlan");
return;
}
await mutateAsync({
orgId: currentOrg?.id,
googleSsoAuthEnforced: value
});
} else if (type === EnforceAuthType.OIDC) {
if (!subscription?.oidcSSO) {
handlePopUpOpen("upgradePlan");
return;
}
await mutateAsync({
orgId: currentOrg?.id,
authEnforced: value
});
} else {
createNotification({
text: `Invalid auth enforcement type ${type}`,
type: "error"
});
}
await mutateAsync({
orgId: currentOrg?.id,
authEnforced: value
});
createNotification({
text: `Successfully ${value ? "enforced" : "un-enforced"} org-level auth`,
text: `Successfully ${value ? "enabled" : "disabled"} org-level auth`,
type: "success"
});
if (value) {
await logout.mutateAsync();
window.open(`/api/v1/sso/redirect/saml2/organizations/${currentOrg.slug}`);
if (type === EnforceAuthType.SAML) {
window.open(`/api/v1/sso/redirect/saml2/organizations/${currentOrg.slug}`);
} else if (type === EnforceAuthType.GOOGLE) {
window.open(`/api/v1/sso/redirect/google?org_slug=${currentOrg.slug}`);
}
window.close();
}
} catch (err) {
@@ -78,45 +127,91 @@ export const OrgGeneralAuthSection = () => {
};
return (
<>
{/* <div className="py-4">
<div className="mb-2 flex justify-between">
<h3 className="text-md text-mineshaft-100">Allow users to send invites</h3>
<OrgPermissionCan I={OrgPermissionActions.Edit} a={OrgPermissionSubjects.Sso}>
{(isAllowed) => (
<Switch
id="allow-org-invites"
onCheckedChange={(value) => handleEnforceOrgAuthToggle(value)}
isChecked={currentOrg?.authEnforced ?? false}
isDisabled={!isAllowed}
/>
)}
</OrgPermissionCan>
</div>
<p className="text-sm text-mineshaft-300">Allow members to invite new users to this organization</p>
</div> */}
<div className="py-4">
<div className="mb-2 flex justify-between">
<div className="flex items-center gap-1">
<span className="text-md text-mineshaft-100">Enforce SAML SSO</span>
</div>
<OrgPermissionCan I={OrgPermissionActions.Edit} a={OrgPermissionSubjects.Sso}>
{(isAllowed) => (
<Switch
id="enforce-org-auth"
onCheckedChange={(value) => handleEnforceOrgAuthToggle(value)}
isChecked={currentOrg?.authEnforced ?? false}
isDisabled={!isAllowed}
/>
)}
</OrgPermissionCan>
</div>
<p className="text-sm text-mineshaft-300">
Enforce users to authenticate via SAML to access this organization
<div className="rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-6">
<div>
<p className="text-xl font-semibold text-gray-200">SSO Enforcement</p>
<p className="mb-2 mt-1 text-gray-400">
Manage strict enforcement of specific authentication methods for your organization.
</p>
</div>
{currentOrg?.authEnforced && (
<div className="py-4">
<div className="flex flex-col gap-2 py-4">
<div className={twMerge("mt-4", !isSamlConfigured && "hidden")}>
<div className="mb-2 flex justify-between">
<div className="flex items-center gap-1">
<span className="text-md text-mineshaft-100">Enforce SAML SSO</span>
</div>
<OrgPermissionCan I={OrgPermissionActions.Edit} a={OrgPermissionSubjects.Sso}>
{(isAllowed) => (
<Switch
id="enforce-saml-auth"
onCheckedChange={(value) =>
handleEnforceOrgAuthToggle(value, EnforceAuthType.SAML)
}
isChecked={currentOrg?.authEnforced ?? false}
isDisabled={!isAllowed || currentOrg?.googleSsoAuthEnforced}
/>
)}
</OrgPermissionCan>
</div>
<p className="text-sm text-mineshaft-300">
Enforce users to authenticate via SAML to access this organization.
<br />
When this is enabled your organization members will only be able to login with SAML.
</p>
</div>
<div className={twMerge("mt-4", !isOidcConfigured && "hidden")}>
<div className="mb-2 flex justify-between">
<div className="flex items-center gap-1">
<span className="text-md text-mineshaft-100">Enforce OIDC SSO</span>
</div>
<OrgPermissionCan I={OrgPermissionActions.Edit} a={OrgPermissionSubjects.Sso}>
{(isAllowed) => (
<Switch
id="enforce-oidc-auth"
isChecked={currentOrg?.authEnforced ?? false}
onCheckedChange={(value) =>
handleEnforceOrgAuthToggle(value, EnforceAuthType.OIDC)
}
isDisabled={!isAllowed}
/>
)}
</OrgPermissionCan>
</div>
<p className="text-sm text-mineshaft-300">
Enforce users to authenticate via OIDC to access this organization.
<br />
When this is enabled your organization members will only be able to login with OIDC.
</p>
</div>
<div className={twMerge("mt-2", !isGoogleConfigured && "hidden")}>
<div className="mb-2 flex justify-between">
<div className="flex items-center gap-1">
<span className="text-md text-mineshaft-100">Enforce Google SSO</span>
</div>
<OrgPermissionCan I={OrgPermissionActions.Edit} a={OrgPermissionSubjects.Sso}>
{(isAllowed) => (
<Switch
id="enforce-google-sso"
onCheckedChange={(value) =>
handleEnforceOrgAuthToggle(value, EnforceAuthType.GOOGLE)
}
isChecked={currentOrg?.googleSsoAuthEnforced ?? false}
isDisabled={!isAllowed || currentOrg?.authEnforced}
/>
)}
</OrgPermissionCan>
</div>
<p className="text-sm text-mineshaft-300">
Enforce users to authenticate via Google to access this organization.
<br />
When this is enabled your organization members will only be able to login with Google.
</p>
</div>
</div>
{(currentOrg?.authEnforced || currentOrg?.googleSsoAuthEnforced) && (
<div className="mt-4 py-4">
<div className="mb-2 flex justify-between">
<div className="flex items-center gap-1">
<span className="text-md text-mineshaft-100">Enable Admin SSO Bypass</span>
@@ -125,8 +220,8 @@ export const OrgGeneralAuthSection = () => {
content={
<div>
<span>
When this is enabled, we strongly recommend enforcing MFA at the organization
level.
When enabling admin SSO bypass, we highly recommend enabling MFA enforcement
at the organization-level for security reasons.
</span>
<p className="mt-4">
In case of a lockout, admins can use the{" "}
@@ -182,6 +277,6 @@ export const OrgGeneralAuthSection = () => {
onOpenChange={(isOpen) => handlePopUpToggle("upgradePlan", isOpen)}
text="You can enforce SAML SSO if you switch to Infisical's Pro plan."
/>
</>
</div>
);
};
@@ -95,43 +95,25 @@ export const OrgLDAPSection = (): JSX.Element => {
};
return (
<div className="mb-4 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-6">
<div className="mb-4">
<div className="py-4">
<div className="mb-2 flex items-center justify-between">
<h2 className="text-md text-mineshaft-100">LDAP</h2>
<div className="flex">
<OrgPermissionCan I={OrgPermissionActions.Create} a={OrgPermissionSubjects.Ldap}>
{(isAllowed) => (
<Button onClick={addLDAPBtnClick} colorSchema="secondary" isDisabled={!isAllowed}>
Manage
</Button>
)}
</OrgPermissionCan>
<div className="mb-4 flex items-center justify-between">
<div>
<p className="text-xl font-semibold text-gray-200">LDAP</p>
<p className="mb-2 text-gray-400">Manage LDAP authentication configuration</p>
</div>
</div>
<p className="text-sm text-mineshaft-300">Manage LDAP authentication configuration</p>
</div>
<div className="py-4">
<div className="mb-2 flex items-center justify-between">
<h2 className="text-md text-mineshaft-100">LDAP Group Mappings</h2>
<OrgPermissionCan I={OrgPermissionActions.Create} a={OrgPermissionSubjects.Ldap}>
{(isAllowed) => (
<Button
onClick={openLDAPGroupMapModal}
colorSchema="secondary"
isDisabled={!isAllowed}
>
<Button onClick={addLDAPBtnClick} colorSchema="secondary" isDisabled={!isAllowed}>
Manage
</Button>
)}
</OrgPermissionCan>
</div>
<p className="text-sm text-mineshaft-300">
Manage how LDAP groups are mapped to internal groups in Infisical
</p>
</div>
{data && (
<div className="py-4">
<div className="pt-4">
<div className="mb-2 flex items-center justify-between">
<h2 className="text-md text-mineshaft-100">Enable LDAP</h2>
<OrgPermissionCan I={OrgPermissionActions.Edit} a={OrgPermissionSubjects.Ldap}>
@@ -152,6 +134,27 @@ export const OrgLDAPSection = (): JSX.Element => {
</p>
</div>
)}
<div className="py-4">
<div className="mb-2 flex items-center justify-between">
<h2 className="text-md text-mineshaft-100">LDAP Group Mappings</h2>
<OrgPermissionCan I={OrgPermissionActions.Create} a={OrgPermissionSubjects.Ldap}>
{(isAllowed) => (
<Button
onClick={openLDAPGroupMapModal}
colorSchema="secondary"
isDisabled={!isAllowed}
>
Configure
</Button>
)}
</OrgPermissionCan>
</div>
<p className="text-sm text-mineshaft-300">
Manage how LDAP groups are mapped to internal groups in Infisical
</p>
</div>
<LDAPModal
popUp={popUp}
handlePopUpClose={handlePopUpClose}
@@ -11,7 +11,7 @@ import {
useOrganization,
useSubscription
} from "@app/context";
import { useGetOIDCConfig, useLogoutUser, useUpdateOrg } from "@app/hooks/api";
import { useGetOIDCConfig } from "@app/hooks/api";
import { useUpdateOIDCConfig } from "@app/hooks/api/oidcConfig/mutations";
import { usePopUp } from "@app/hooks/usePopUp";
@@ -23,9 +23,7 @@ export const OrgOIDCSection = (): JSX.Element => {
const { data, isPending } = useGetOIDCConfig(currentOrg?.id ?? "");
const { mutateAsync } = useUpdateOIDCConfig();
const { mutateAsync: updateOrg } = useUpdateOrg();
const logout = useLogoutUser();
const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
"addOIDC",
"upgradePlan"
@@ -54,56 +52,6 @@ export const OrgOIDCSection = (): JSX.Element => {
}
};
const handleEnforceOrgAuthToggle = async (value: boolean) => {
try {
if (!currentOrg?.id) return;
if (!subscription?.oidcSSO) {
handlePopUpOpen("upgradePlan");
return;
}
await updateOrg({
orgId: currentOrg?.id,
authEnforced: value
});
createNotification({
text: `Successfully ${value ? "enforced" : "un-enforced"} org-level auth`,
type: "success"
});
if (value) {
await logout.mutateAsync();
window.open(`/api/v1/sso/oidc/login?orgSlug=${currentOrg.slug}`);
window.close();
}
} catch (err) {
console.error(err);
}
};
const handleEnableBypassOrgAuthToggle = async (value: boolean) => {
try {
if (!currentOrg?.id) return;
if (!subscription?.oidcSSO) {
handlePopUpOpen("upgradePlan");
return;
}
await updateOrg({
orgId: currentOrg?.id,
bypassOrgAuthEnabled: value
});
createNotification({
text: `Successfully ${value ? "enabled" : "disabled"} admin bypassing of org-level auth`,
type: "success"
});
} catch (err) {
console.error(err);
}
};
const handleOIDCGroupManagement = async (value: boolean) => {
try {
if (!currentOrg?.id) return;
@@ -136,25 +84,22 @@ export const OrgOIDCSection = (): JSX.Element => {
};
return (
<div className="mb-4 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-6">
<div className="py-4">
<div className="mb-2 flex items-center justify-between">
<h2 className="text-md text-mineshaft-100">OIDC</h2>
{!isPending && (
<OrgPermissionCan I={OrgPermissionActions.Create} a={OrgPermissionSubjects.Sso}>
{(isAllowed) => (
<Button
onClick={addOidcButtonClick}
colorSchema="secondary"
isDisabled={!isAllowed}
>
Manage
</Button>
)}
</OrgPermissionCan>
)}
<div className="mb-4 rounded-lg border-mineshaft-600 bg-mineshaft-900">
<div className="mb-4 flex items-center justify-between">
<div>
<p className="text-xl font-semibold text-gray-200">OIDC</p>
<p className="mb-2 text-gray-400">Manage OIDC authentication configuration</p>
</div>
<p className="text-sm text-mineshaft-300">Manage OIDC authentication configuration</p>
{!isPending && (
<OrgPermissionCan I={OrgPermissionActions.Create} a={OrgPermissionSubjects.Sso}>
{(isAllowed) => (
<Button onClick={addOidcButtonClick} colorSchema="secondary" isDisabled={!isAllowed}>
Manage
</Button>
)}
</OrgPermissionCan>
)}
</div>
{data && (
<div className="py-4">
@@ -178,88 +123,6 @@ export const OrgOIDCSection = (): JSX.Element => {
</p>
</div>
)}
<div className="py-4">
<div className="mb-2 flex justify-between">
<div className="flex items-center gap-1">
<span className="text-md text-mineshaft-100">Enforce OIDC SSO</span>
</div>
<OrgPermissionCan I={OrgPermissionActions.Edit} a={OrgPermissionSubjects.Sso}>
{(isAllowed) => (
<Switch
id="enforce-org-auth"
isChecked={currentOrg?.authEnforced ?? false}
onCheckedChange={(value) => handleEnforceOrgAuthToggle(value)}
isDisabled={!isAllowed}
/>
)}
</OrgPermissionCan>
</div>
<p className="text-sm text-mineshaft-300">
<span>Enforce users to authenticate via OIDC to access this organization.</span>
</p>
</div>
{currentOrg?.authEnforced && (
<div className="py-4">
<div className="mb-2 flex justify-between">
<div className="flex items-center gap-1">
<span className="text-md text-mineshaft-100">Enable Admin SSO Bypass</span>
<Tooltip
className="max-w-lg"
content={
<div>
<span>
When this is enabled, we strongly recommend enforcing MFA at the organization
level.
</span>
<p className="mt-4">
In case of a lockout, admins can use the{" "}
<a
target="_blank"
className="underline underline-offset-2 hover:text-mineshaft-300"
href="https://infisical.com/docs/documentation/platform/sso/overview#admin-login-portal"
rel="noreferrer"
>
Admin Login Portal
</a>{" "}
at{" "}
<a
target="_blank"
rel="noopener noreferrer"
className="underline underline-offset-2 hover:text-mineshaft-300"
href={`${window.location.origin}/login/admin`}
>
{window.location.origin}/login/admin
</a>
</p>
</div>
}
>
<FontAwesomeIcon
icon={faInfoCircle}
size="sm"
className="mt-0.5 inline-block text-mineshaft-400"
/>
</Tooltip>
</div>
<OrgPermissionCan I={OrgPermissionActions.Edit} a={OrgPermissionSubjects.Sso}>
{(isAllowed) => (
<Switch
id="allow-admin-bypass"
isChecked={currentOrg?.bypassOrgAuthEnabled ?? false}
onCheckedChange={(value) => handleEnableBypassOrgAuthToggle(value)}
isDisabled={!isAllowed}
/>
)}
</OrgPermissionCan>
</div>
<p className="text-sm text-mineshaft-300">
<span>
Allow organization admins to bypass OIDC enforcement when SSO is unavailable,
misconfigured, or inaccessible.
</span>
</p>
</div>
)}
<div className="py-4">
<div className="mb-2 flex justify-between">
<div className="text-md flex items-center text-mineshaft-100">
@@ -79,25 +79,24 @@ export const OrgSSOSection = (): JSX.Element => {
};
return (
<>
<hr className="border-mineshaft-600" />
<div className="py-4">
<div className="mb-2 flex items-center justify-between">
<h2 className="text-md text-mineshaft-100">SAML</h2>
{!isPending && (
<OrgPermissionCan I={OrgPermissionActions.Create} a={OrgPermissionSubjects.Sso}>
{(isAllowed) => (
<Button onClick={addSSOBtnClick} colorSchema="secondary" isDisabled={!isAllowed}>
Manage
</Button>
)}
</OrgPermissionCan>
)}
<div className="space-y-4">
<div className="mb-4 flex items-center justify-between">
<div>
<p className="text-xl font-semibold text-gray-200">SAML</p>
<p className="mb-2 text-gray-400">Manage SAML authentication configuration</p>
</div>
<p className="text-sm text-mineshaft-300">Manage SAML authentication configuration</p>
{!isPending && (
<OrgPermissionCan I={OrgPermissionActions.Create} a={OrgPermissionSubjects.Sso}>
{(isAllowed) => (
<Button onClick={addSSOBtnClick} colorSchema="secondary" isDisabled={!isAllowed}>
Manage
</Button>
)}
</OrgPermissionCan>
)}
</div>
<div className="py-4">
<div className="mb-2 flex items-center justify-between">
<div>
<div className="mb-2 flex items-center justify-between pt-4">
<h2 className="text-md text-mineshaft-100">Enable SAML</h2>
{!isPending && (
<OrgPermissionCan I={OrgPermissionActions.Edit} a={OrgPermissionSubjects.Sso}>
@@ -126,6 +125,6 @@ export const OrgSSOSection = (): JSX.Element => {
onOpenChange={(isOpen) => handlePopUpToggle("upgradePlan", isOpen)}
text="You can use SAML SSO if you switch to Infisical's Pro plan."
/>
</>
</div>
);
};
@@ -49,13 +49,19 @@ export const OrgSsoTab = withPermission(
);
const areConfigsLoading = isLoadingOidcConfig || isLoadingSamlConfig || isLoadingLdapConfig;
const shouldDisplaySection = (method: LoginMethod) =>
!enabledLoginMethods || enabledLoginMethods.includes(method);
const shouldDisplaySection = (method: LoginMethod[] | LoginMethod) => {
if (Array.isArray(method)) {
return method.some((m) => !enabledLoginMethods || enabledLoginMethods.includes(m));
}
const isOidcConfigured = oidcConfig && (oidcConfig.discoveryURL || oidcConfig.issuer);
return !enabledLoginMethods || enabledLoginMethods.includes(method);
};
const isOidcConfigured = Boolean(oidcConfig && (oidcConfig.discoveryURL || oidcConfig.issuer));
const isSamlConfigured =
samlConfig && (samlConfig.entryPoint || samlConfig.issuer || samlConfig.cert);
const isLdapConfigured = ldapConfig && ldapConfig.url;
const isGoogleConfigured = shouldDisplaySection(LoginMethod.GOOGLE);
const shouldShowCreateIdentityProviderView =
!isOidcConfigured && !isSamlConfigured && !isLdapConfigured;
@@ -65,11 +71,14 @@ export const OrgSsoTab = withPermission(
shouldDisplaySection(LoginMethod.OIDC) ||
shouldDisplaySection(LoginMethod.LDAP) ? (
<>
<div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-6">
<p className="text-xl font-semibold text-gray-200">Connect an Identity Provider</p>
<p className="mb-2 mt-1 text-gray-400">
Connect your identity provider to simplify user management
</p>
<div className="mb-4 space-y-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-6">
<div>
<p className="text-xl font-semibold text-gray-200">Connect an Identity Provider</p>
<p className="mb-2 mt-1 text-gray-400">
Connect your identity provider to simplify user management with options like SAML,
OIDC, and LDAP.
</p>
</div>
{shouldDisplaySection(LoginMethod.SAML) && (
<div
className={twMerge(
@@ -169,20 +178,27 @@ export const OrgSsoTab = withPermission(
return (
<>
{shouldShowCreateIdentityProviderView ? (
createIdentityProviderView
) : (
<>
{isSamlConfigured && shouldDisplaySection(LoginMethod.SAML) && (
<div className="mb-4 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-6">
<OrgGeneralAuthSection />
<OrgSSOSection />
<div className="space-y-4">
{shouldDisplaySection([LoginMethod.SAML, LoginMethod.GOOGLE]) && (
<OrgGeneralAuthSection
isSamlConfigured={isSamlConfigured}
isOidcConfigured={isOidcConfigured}
isGoogleConfigured={isGoogleConfigured}
/>
)}
{shouldShowCreateIdentityProviderView ? (
createIdentityProviderView
) : (
<div className="mb-4 space-y-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-6">
<div>
{isSamlConfigured && shouldDisplaySection(LoginMethod.SAML) && <OrgSSOSection />}
{isOidcConfigured && shouldDisplaySection(LoginMethod.OIDC) && <OrgOIDCSection />}
{isLdapConfigured && shouldDisplaySection(LoginMethod.LDAP) && <OrgLDAPSection />}
</div>
)}
{isOidcConfigured && shouldDisplaySection(LoginMethod.OIDC) && <OrgOIDCSection />}
{isLdapConfigured && shouldDisplaySection(LoginMethod.LDAP) && <OrgLDAPSection />}
</>
)}
</div>
)}
</div>
<UpgradePlanModal
isOpen={popUp.upgradePlan.isOpen}
onOpenChange={(isOpen) => handlePopUpToggle("upgradePlan", isOpen)}
@@ -6,6 +6,7 @@ import { useNavigate, useSearch } from "@tanstack/react-router";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { RoleOption } from "@app/components/roles";
import {
Alert,
AlertDescription,
@@ -320,6 +321,7 @@ export const AddMemberModal = ({ popUp, handlePopUpToggle }: Props) => {
>
<FilterableSelect
options={roles}
components={{ Option: RoleOption }}
placeholder="Select roles..."
value={value}
onChange={onChange}
@@ -21,6 +21,7 @@ import {
ProjectPermissionPkiSubscriberActions,
ProjectPermissionPkiTemplateActions,
ProjectPermissionSecretActions,
ProjectPermissionSecretEventActions,
ProjectPermissionSecretRotationActions,
ProjectPermissionSecretScanningConfigActions,
ProjectPermissionSecretScanningDataSourceActions,
@@ -188,6 +189,13 @@ const PkiTemplatePolicyActionSchema = z.object({
[ProjectPermissionPkiTemplateActions.ListCerts]: z.boolean().optional()
});
const SecretEventsPolicyActionSchema = z.object({
[ProjectPermissionSecretEventActions.SubscribeCreated]: z.boolean().optional(),
[ProjectPermissionSecretEventActions.SubscribeUpdated]: z.boolean().optional(),
[ProjectPermissionSecretEventActions.SubscribeDeleted]: z.boolean().optional(),
[ProjectPermissionSecretEventActions.SubscribeImportMutations]: z.boolean().optional()
});
const SecretRollbackPolicyActionSchema = z.object({
read: z.boolean().optional(),
create: z.boolean().optional()
@@ -356,7 +364,12 @@ export const projectRoleFormSchema = z.object({
[ProjectPermissionSub.SecretScanningFindings]:
SecretScanningFindingPolicyActionSchema.array().default([]),
[ProjectPermissionSub.SecretScanningConfigs]:
SecretScanningConfigPolicyActionSchema.array().default([])
SecretScanningConfigPolicyActionSchema.array().default([]),
[ProjectPermissionSub.SecretEvents]: SecretEventsPolicyActionSchema.extend({
conditions: ConditionSchema
})
.array()
.default([])
})
.partial()
.optional()
@@ -374,7 +387,8 @@ type TConditionalFields =
| ProjectPermissionSub.SshHosts
| ProjectPermissionSub.SecretRotation
| ProjectPermissionSub.Identity
| ProjectPermissionSub.SecretSyncs;
| ProjectPermissionSub.SecretSyncs
| ProjectPermissionSub.SecretEvents;
export const isConditionalSubjects = (
subject: ProjectPermissionSub
@@ -388,7 +402,8 @@ export const isConditionalSubjects = (
subject === ProjectPermissionSub.SecretRotation ||
subject === ProjectPermissionSub.PkiSubscribers ||
subject === ProjectPermissionSub.CertificateTemplates ||
subject === ProjectPermissionSub.SecretSyncs;
subject === ProjectPermissionSub.SecretSyncs ||
subject === ProjectPermissionSub.SecretEvents;
const convertCaslConditionToFormOperator = (caslConditions: TPermissionCondition) => {
const formConditions: z.infer<typeof ConditionSchema> = [];
@@ -494,7 +509,8 @@ export const rolePermission2Form = (permissions: TProjectPermission[] = []) => {
ProjectPermissionSub.SshCertificateAuthorities,
ProjectPermissionSub.SshCertificates,
ProjectPermissionSub.SshHostGroups,
ProjectPermissionSub.SecretSyncs
ProjectPermissionSub.SecretSyncs,
ProjectPermissionSub.SecretEvents
].includes(subject)
) {
// from above statement we are sure it won't be undefined
@@ -607,6 +623,32 @@ export const rolePermission2Form = (permissions: TProjectPermission[] = []) => {
return;
}
if (subject === ProjectPermissionSub.SecretEvents) {
const canSubscribeCreate = action.includes(
ProjectPermissionSecretEventActions.SubscribeCreated
);
const canSubscribeUpdate = action.includes(
ProjectPermissionSecretEventActions.SubscribeUpdated
);
const canSubscribeDelete = action.includes(
ProjectPermissionSecretEventActions.SubscribeDeleted
);
const canSubscribeImportMutations = action.includes(
ProjectPermissionSecretEventActions.SubscribeImportMutations
);
// from above statement we are sure it won't be undefined
formVal[subject]!.push({
"subscribe-on-created": canSubscribeCreate,
"subscribe-on-deleted": canSubscribeDelete,
"subscribe-on-updated": canSubscribeUpdate,
"subscribe-on-import-mutations": canSubscribeImportMutations,
conditions: conditions ? convertCaslConditionToFormOperator(conditions) : []
});
return;
}
// for other subjects
const canRead = action.includes(ProjectPermissionActions.Read);
const canEdit = action.includes(ProjectPermissionActions.Edit);
@@ -1114,8 +1156,7 @@ export const PROJECT_PERMISSION_OBJECT: TProjectPermissionObject = {
{ label: "Read Value", value: ProjectPermissionSecretActions.ReadValue },
{ label: "Modify", value: ProjectPermissionSecretActions.Edit },
{ label: "Remove", value: ProjectPermissionSecretActions.Delete },
{ label: "Create", value: ProjectPermissionSecretActions.Create },
{ label: "Subscribe", value: ProjectPermissionSecretActions.Subscribe }
{ label: "Create", value: ProjectPermissionSecretActions.Create }
]
},
[ProjectPermissionSub.SecretFolders]: {
@@ -1535,6 +1576,27 @@ export const PROJECT_PERMISSION_OBJECT: TProjectPermissionObject = {
value: ProjectPermissionSecretScanningConfigActions.Update
}
]
},
[ProjectPermissionSub.SecretEvents]: {
title: "Secret Events",
actions: [
{
label: "Subscribe on Created",
value: ProjectPermissionSecretEventActions.SubscribeCreated
},
{
label: "Subscribe on Deleted",
value: ProjectPermissionSecretEventActions.SubscribeDeleted
},
{
label: "Subscribe on Updated",
value: ProjectPermissionSecretEventActions.SubscribeUpdated
},
{
label: "Subscribe on Import Mutations",
value: ProjectPermissionSecretEventActions.SubscribeImportMutations
}
]
}
};
@@ -1564,7 +1626,8 @@ const SecretsManagerPermissionSubjects = (enabled = false) => ({
[ProjectPermissionSub.SecretRollback]: enabled,
[ProjectPermissionSub.SecretRotation]: enabled,
[ProjectPermissionSub.ServiceTokens]: enabled,
[ProjectPermissionSub.Commits]: enabled
[ProjectPermissionSub.Commits]: enabled,
[ProjectPermissionSub.SecretEvents]: enabled
});
const KmsPermissionSubjects = (enabled = false) => ({
@@ -32,6 +32,7 @@ import {
rolePermission2Form,
TFormSchema
} from "./ProjectRoleModifySection.utils";
import { SecretEventPermissionConditions } from "./SecretEventPermissionConditions";
import { SecretPermissionConditions } from "./SecretPermissionConditions";
import { SecretSyncPermissionConditions } from "./SecretSyncPermissionConditions";
import { SshHostPermissionConditions } from "./SshHostPermissionConditions";
@@ -72,6 +73,10 @@ export const renderConditionalComponents = (
return <SecretSyncPermissionConditions isDisabled={isDisabled} />;
}
if (subject === ProjectPermissionSub.SecretEvents) {
return <SecretEventPermissionConditions isDisabled={isDisabled} />;
}
return <GeneralPermissionConditions isDisabled={isDisabled} type={subject} />;
}
@@ -0,0 +1,22 @@
import { ProjectPermissionSub } from "@app/context/ProjectPermissionContext/types";
import { ConditionsFields } from "./ConditionsFields";
type Props = {
position?: number;
isDisabled?: boolean;
};
export const SecretEventPermissionConditions = ({ position = 0, isDisabled }: Props) => {
return (
<ConditionsFields
isDisabled={isDisabled}
subject={ProjectPermissionSub.SecretEvents}
position={position}
selectOptions={[
{ value: "environment", label: "Environment Slug" },
{ value: "secretPath", label: "Secret Path" }
]}
/>
);
};
@@ -17,8 +17,7 @@ export const SecretPermissionConditions = ({ position = 0, isDisabled }: Props)
{ value: "environment", label: "Environment Slug" },
{ value: "secretPath", label: "Secret Path" },
{ value: "secretName", label: "Secret Name" },
{ value: "secretTags", label: "Secret Tags" },
{ value: "eventType", label: "Event Type" }
{ value: "secretTags", label: "Secret Tags" }
]}
/>
);
@@ -24,7 +24,7 @@ export const IntegrationAuditLogsSection = ({ integration }: Props) => {
<div className="mb-4 flex items-center justify-between border-b border-mineshaft-400 pb-4">
<p className="text-lg font-semibold text-gray-200">Integration Logs</p>
<p className="text-xs text-gray-400">
Displaying audit logs from the last {auditLogsRetentionDays} days
Displaying audit logs from the last {Math.min(auditLogsRetentionDays, 60)} days
</p>
</div>
<LogsSection
@@ -32,7 +32,9 @@ export const IntegrationAuditLogsSection = ({ integration }: Props) => {
showFilters={false}
presets={{
eventMetadata: { integrationId: integration.id },
startDate: new Date(new Date().setDate(new Date().getDate() - auditLogsRetentionDays)),
startDate: new Date(
new Date().setDate(new Date().getDate() - Math.min(auditLogsRetentionDays, 60))
),
eventType: INTEGRATION_EVENTS
}}
/>
@@ -1,5 +1,8 @@
import { useRenderConnectionListServices } from "@app/hooks/api/appConnections/render";
import { TRenderSync } from "@app/hooks/api/secretSyncs/types/render-sync";
import {
useRenderConnectionListEnvironmentGroups,
useRenderConnectionListServices
} from "@app/hooks/api/appConnections/render";
import { RenderSyncScope, TRenderSync } from "@app/hooks/api/secretSyncs/types/render-sync";
import { getSecretSyncDestinationColValues } from "../helpers";
import { SecretSyncTableCell } from "../SecretSyncTableCell";
@@ -9,21 +12,59 @@ type Props = {
};
export const RenderSyncDestinationCol = ({ secretSync }: Props) => {
const isServiceScope = secretSync.destinationConfig.scope === RenderSyncScope.Service;
const { data: services = [], isPending } = useRenderConnectionListServices(
secretSync.connectionId
secretSync.connectionId,
{
enabled: isServiceScope
}
);
const { primaryText, secondaryText } = getSecretSyncDestinationColValues({
...secretSync,
destinationConfig: {
...secretSync.destinationConfig,
serviceName: services.find((s) => s.id === secretSync.destinationConfig.serviceId)?.name
const { data: groups = [], isPending: isGroupsPending } =
useRenderConnectionListEnvironmentGroups(secretSync.connectionId, { enabled: !isServiceScope });
switch (secretSync.destinationConfig.scope) {
case RenderSyncScope.Service: {
const id = secretSync.destinationConfig.serviceId;
const { primaryText, secondaryText } = getSecretSyncDestinationColValues({
...secretSync,
destinationConfig: {
...secretSync.destinationConfig,
serviceName: services.find((s) => s.id === id)?.name
}
});
if (isPending) {
return (
<SecretSyncTableCell primaryText="Loading service info..." secondaryText="Service" />
);
}
return <SecretSyncTableCell primaryText={primaryText} secondaryText={secondaryText} />;
}
});
case RenderSyncScope.EnvironmentGroup: {
const id = secretSync.destinationConfig.environmentGroupId;
const { primaryText, secondaryText } = getSecretSyncDestinationColValues({
...secretSync,
destinationConfig: {
...secretSync.destinationConfig,
environmentGroupName: groups.find((s) => s.id === id)?.name
}
});
if (isPending) {
return <SecretSyncTableCell primaryText="Loading service info..." secondaryText="Service" />;
if (isGroupsPending) {
return (
<SecretSyncTableCell
primaryText="Loading environment group info..."
secondaryText="Environment Group"
/>
);
}
return <SecretSyncTableCell primaryText={primaryText} secondaryText={secondaryText} />;
}
default:
throw new Error("Unknown render sync destination scope");
}
return <SecretSyncTableCell primaryText={primaryText} secondaryText={secondaryText} />;
};
@@ -8,6 +8,7 @@ import {
} 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";
import { RenderSyncScope } from "@app/hooks/api/secretSyncs/types/render-sync";
// This functional ensures parity across what is displayed in the destination column
// and the values used when search filtering
@@ -125,8 +126,15 @@ export const getSecretSyncDestinationColValues = (secretSync: TSecretSync) => {
secondaryText = destinationConfig.app;
break;
case SecretSync.Render:
primaryText = destinationConfig.serviceName ?? destinationConfig.serviceId;
secondaryText = "Service";
if (destinationConfig.scope === RenderSyncScope.Service) {
primaryText = destinationConfig.serviceName ?? destinationConfig.serviceId;
secondaryText = "Service";
} else {
primaryText =
destinationConfig.environmentGroupName ?? destinationConfig.environmentGroupId;
secondaryText = "Environment Group";
}
break;
case SecretSync.Flyio:
primaryText = destinationConfig.appId;
@@ -10,6 +10,7 @@ import {
ProjectPermissionActions,
ProjectPermissionSub,
useProjectPermission,
useSubscription,
useWorkspace
} from "@app/context";
import { ProjectPermissionSecretActions } from "@app/context/ProjectPermissionContext/types";
@@ -51,6 +52,7 @@ export const SelectionPanel = ({
usedBySecretSyncs = []
}: Props) => {
const { permission } = useProjectPermission();
const { subscription } = useSubscription();
const { handlePopUpOpen, handlePopUpToggle, handlePopUpClose, popUp } = usePopUp([
"bulkDeleteEntries",
@@ -101,6 +103,16 @@ export const SelectionPanel = ({
return "Do you want to delete the selected folders across environments?";
};
const getDeleteModalSubTitle = () => {
if (selectedFolderCount > 0) {
if (subscription?.pitRecovery) {
return "All selected folders and their contents will be removed. You can reverse this action by rolling back to a previous commit.";
}
return "All selected folders and their contents will be removed. Rolling back to a previous commit isn't available on your current plan. Upgrade to enable this feature.";
}
return undefined;
};
const handleBulkDelete = async () => {
let processedEntries = 0;
@@ -279,6 +291,7 @@ export const SelectionPanel = ({
isOpen={popUp.bulkDeleteEntries.isOpen}
deleteKey="delete"
title={getDeleteModalTitle()}
subTitle={getDeleteModalSubTitle()}
onChange={(isOpen) => handlePopUpToggle("bulkDeleteEntries", isOpen)}
onDeleteApproved={handleBulkDelete}
formContent={
@@ -592,6 +592,16 @@ export const AccessApprovalRequest = ({
setSelectedRequest(null);
refetchRequests();
}}
onUpdate={(request) => {
// scott: this isn't ideal but our current use of state makes this complicated...
// we shouldn't be using state like this...
handleSelectRequest({
...selectedRequest,
isTemporary: request.isTemporary,
temporaryRange: request.temporaryRange,
reviewers: []
});
}}
canBypass={generateRequestDetails(selectedRequest).canBypass}
/>
)}
@@ -0,0 +1,185 @@
import { Controller, useForm } from "react-hook-form";
import { faWarning } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod";
import { useQueryClient } from "@tanstack/react-query";
import ms from "ms";
import { z } from "zod";
import { TtlFormLabel } from "@app/components/features";
import { createNotification } from "@app/components/notifications";
import {
Button,
FormControl,
Input,
Modal,
ModalClose,
ModalContent,
TextArea
} from "@app/components/v2";
import { useUpdateAccessRequest } from "@app/hooks/api/accessApproval/mutation";
import { accessApprovalKeys } from "@app/hooks/api/accessApproval/queries";
import { TAccessApprovalRequest } from "@app/hooks/api/accessApproval/types";
type ContentProps = {
accessRequest: TAccessApprovalRequest;
onComplete: (request: TAccessApprovalRequest) => void;
projectSlug: string;
};
const EditSchema = z.object({
temporaryRange: z
.string()
.nonempty("Required")
.transform((val, ctx) => {
const parsedMs = ms(val);
if (typeof parsedMs !== "number" || parsedMs <= 0) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
"Invalid time period format or value. Must be a positive duration (e.g., '1h', '30m', '2d')."
});
return z.NEVER;
}
return val;
}),
editNote: z.string().nonempty("Required")
});
type FormData = z.infer<typeof EditSchema>;
const Content = ({ accessRequest, onComplete, projectSlug }: ContentProps) => {
const update = useUpdateAccessRequest();
const queryClient = useQueryClient();
const {
handleSubmit,
control,
formState: { isSubmitting }
} = useForm({
resolver: zodResolver(EditSchema),
defaultValues: {
temporaryRange: accessRequest.temporaryRange ?? "1h",
editNote: ""
}
});
const onSubmit = async (form: FormData) => {
try {
const request = await update.mutateAsync({
requestId: accessRequest.id,
projectSlug,
...form
});
await queryClient.refetchQueries({
queryKey: accessApprovalKeys.getAccessApprovalPolicies(projectSlug)
});
createNotification({
type: "success",
text: "Access request updated successfully."
});
onComplete(request);
} catch (e) {
console.error(e);
createNotification({
type: "error",
text: "Failed to update access request"
});
}
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div className="mb-4 flex w-full items-start rounded-md border border-yellow/50 bg-yellow/30 px-4 py-2 text-sm text-yellow-200">
<FontAwesomeIcon icon={faWarning} className="mr-2.5 mt-1 text-base text-yellow" />
Updating this access request will restart the review process and require all approvers to
re-approve it.
</div>
<Controller
control={control}
defaultValue="1h"
name="temporaryRange"
render={({ field, fieldState: { error } }) => (
<FormControl
label={<TtlFormLabel label="Access Duration" />}
isError={Boolean(error?.message)}
errorText={error?.message}
helperText={`Must be less than current access duration: ${accessRequest.isTemporary ? accessRequest.temporaryRange : "Permanent"}`}
>
<Input {...field} />
</FormControl>
)}
/>
<Controller
control={control}
name="editNote"
render={({ field, fieldState: { error } }) => (
<FormControl
label="Reason for Editing"
isError={Boolean(error?.message)}
errorText={error?.message}
>
<TextArea
className="!resize-none"
rows={4}
{...field}
placeholder="Provide a reason for updating this request..."
/>
</FormControl>
)}
/>
<div className="mt-4 flex gap-x-2">
<Button
type="submit"
variant="outline_bg"
isLoading={isSubmitting}
isDisabled={isSubmitting}
>
Update Request
</Button>
<ModalClose asChild>
<Button variant="plain" colorSchema="secondary">
Cancel
</Button>
</ModalClose>
</div>
</form>
);
};
type Props = {
isOpen: boolean;
onOpenChange: (isOpen: boolean) => void;
accessRequest?: TAccessApprovalRequest;
onComplete: (request: TAccessApprovalRequest) => void;
projectSlug: string;
};
export const EditAccessRequestModal = ({
isOpen,
onOpenChange,
accessRequest,
onComplete,
projectSlug
}: Props) => {
if (!accessRequest) return null;
return (
<Modal isOpen={isOpen} onOpenChange={onOpenChange}>
<ModalContent
title="Edit Access Request"
subTitle="Modify this access request for re-approval."
>
<Content
projectSlug={projectSlug}
accessRequest={accessRequest}
onComplete={(request) => {
onComplete(request);
onOpenChange(false);
}}
/>
</ModalContent>
</Modal>
);
};
@@ -2,8 +2,11 @@ import { ReactNode, useCallback, useMemo, useState } from "react";
import {
faBan,
faCheck,
faEdit,
faHourglass,
faTriangleExclamation
faTriangleExclamation,
faUser,
faUserSlash
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import ms from "ms";
@@ -15,6 +18,7 @@ import {
Checkbox,
FormControl,
GenericFieldLabel,
IconButton,
Input,
Modal,
ModalContent,
@@ -22,6 +26,7 @@ import {
} from "@app/components/v2";
import { Badge } from "@app/components/v2/Badge";
import { ProjectPermissionActions, useUser, useWorkspace } from "@app/context";
import { usePopUp } from "@app/hooks";
import { useListWorkspaceGroups, useReviewAccessRequest } from "@app/hooks/api";
import {
Approver,
@@ -32,8 +37,9 @@ import {
import { EnforcementLevel } from "@app/hooks/api/policies/enums";
import { ApprovalStatus, TWorkspaceUser } from "@app/hooks/api/types";
import { groupBy } from "@app/lib/fn/array";
import { EditAccessRequestModal } from "@app/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/EditAccessRequestModal";
const getReviewedStatusSymbol = (status?: ApprovalStatus) => {
const getReviewedStatusSymbol = (status?: ApprovalStatus, isOrgMembershipActive?: boolean) => {
if (status === ApprovalStatus.APPROVED)
return (
<Badge variant="success" className="flex h-4 items-center justify-center">
@@ -46,6 +52,17 @@ const getReviewedStatusSymbol = (status?: ApprovalStatus) => {
<FontAwesomeIcon icon={faBan} size="xs" />
</Badge>
);
if (!isOrgMembershipActive) {
return (
// Can't do a tooltip here because nested tooltips doesn't work properly as of yet.
// TODO(daniel): Fix nested tooltips in the future.
<Badge className="flex h-4 items-center justify-center bg-mineshaft-400/50 text-bunker-300">
<FontAwesomeIcon size="xs" icon={faUserSlash} />
</Badge>
);
}
return (
<Badge variant="primary" className="flex h-4 items-center justify-center">
<FontAwesomeIcon icon={faHourglass} size="xs" />
@@ -62,7 +79,8 @@ export const ReviewAccessRequestModal = ({
selectedEnvSlug,
canBypass,
policies = [],
members = []
members = [],
onUpdate
}: {
isOpen: boolean;
onOpenChange: (isOpen: boolean) => void;
@@ -78,14 +96,18 @@ export const ReviewAccessRequestModal = ({
canBypass: boolean;
policies: TAccessApprovalPolicy[];
members: TWorkspaceUser[];
onUpdate: (request: TAccessApprovalRequest) => void;
}) => {
const [isLoading, setIsLoading] = useState<"approved" | "rejected" | null>(null);
const [bypassApproval, setBypassApproval] = useState(false);
const [bypassReason, setBypassReason] = useState("");
const { currentWorkspace } = useWorkspace();
const { data: groupMemberships = [] } = useListWorkspaceGroups(currentWorkspace?.id || "");
const { user } = useUser();
const { popUp, handlePopUpToggle, handlePopUpOpen } = usePopUp(["editRequest"] as const);
const isSoftEnforcement = request.policy.enforcementLevel === EnforcementLevel.Soft;
const accessDetails = {
@@ -121,16 +143,9 @@ export const ReviewAccessRequestModal = ({
if (!accessDetails.temporaryAccess.isTemporary || !accessDetails.temporaryAccess.temporaryRange)
return "Permanent";
// convert the range to human readable format
ms(ms(accessDetails.temporaryAccess.temporaryRange), { long: true });
return (
<Badge>
{`Valid for ${ms(ms(accessDetails.temporaryAccess.temporaryRange), {
long: true
})} after approval`}
</Badge>
);
return `Valid for ${ms(ms(accessDetails.temporaryAccess.temporaryRange), {
long: true
})} after approval`;
};
const reviewAccessRequest = useReviewAccessRequest();
@@ -191,6 +206,7 @@ export const ReviewAccessRequestModal = ({
(acc, curr) => {
if (acc.length && acc[acc.length - 1].sequence === curr.sequence) {
acc[acc.length - 1][curr.type]?.push(curr);
return acc;
}
@@ -202,6 +218,7 @@ export const ReviewAccessRequestModal = ({
? { user: [curr], group: [], sequence, approvals }
: { group: [curr], user: [], sequence, approvals }
);
return acc;
},
[] as {
@@ -215,7 +232,10 @@ export const ReviewAccessRequestModal = ({
const approvers = approversBySequence?.map((approverChain) => {
const reviewers = request.policy.approvers
.filter((el) => (el.sequence || 1) === approverChain.sequence)
.map((el) => ({ ...el, status: reviewesGroupById?.[el.userId]?.[0]?.status }));
.map((el) => ({
...el,
status: reviewesGroupById?.[el.userId]?.[0]?.status
}));
const hasApproved =
reviewers.filter((el) => el.status === "approved").length >=
(approverChain?.approvals || 1);
@@ -286,7 +306,33 @@ export const ReviewAccessRequestModal = ({
<GenericFieldLabel truncate label="Secret Path">
{accessDetails.secretPath}
</GenericFieldLabel>
<GenericFieldLabel label="Access Type">{getAccessLabel()}</GenericFieldLabel>
<GenericFieldLabel label="Access Duration">
<div className="flex h-min gap-1">
{getAccessLabel()}
{request.isApprover && request.status === ApprovalStatus.PENDING && (
<>
<EditAccessRequestModal
isOpen={popUp.editRequest.isOpen}
onOpenChange={(open) => handlePopUpToggle("editRequest", open)}
accessRequest={request}
onComplete={onUpdate}
projectSlug={projectSlug}
/>
<Tooltip content="Edit Access Duration">
<IconButton
onClick={() => handlePopUpOpen("editRequest")}
variant="plain"
size="xs"
tabIndex={-1}
ariaLabel="Edit access duration"
>
<FontAwesomeIcon icon={faEdit} />
</IconButton>
</Tooltip>
</>
)}
</div>
</GenericFieldLabel>
<GenericFieldLabel label="Permission">{requestedAccess}</GenericFieldLabel>
{request.note && (
<GenericFieldLabel className="col-span-full" label="Note">
@@ -383,12 +429,39 @@ export const ReviewAccessRequestModal = ({
</div>
)}
<div className="grid flex-1 grid-cols-5 border-b border-mineshaft-600 p-4">
<GenericFieldLabel className="col-span-2" label="Users">
{approver?.user
?.map(
(el) => approverSequence?.membersGroupById?.[el.id]?.[0]?.user?.username
)
.join(", ")}
<GenericFieldLabel className="col-span-2" icon={faUser} label="Users">
{Boolean(approver.user.length) && (
<div className="flex flex-row flex-wrap gap-2">
{approver?.user?.map((el, idx) => {
const member = approverSequence?.membersGroupById?.[el.id]?.[0];
if (!member) return null;
return member.user.isOrgMembershipActive ? (
<div className="flex items-center" key={member.user.id}>
<span>{member.user.username}</span>
{idx < approver.user.length - 1 && ","}
</div>
) : (
<div className="flex items-center" key={member.user.id}>
<span className="flex items-center opacity-40">
{member.user.username}
<span className="text-xs">
<Tooltip content="This user has been deactivated and no longer has an active organization membership.">
<div>
<Badge className="pointer-events-none ml-1 mr-auto flex h-5 w-min items-center gap-1.5 whitespace-nowrap bg-mineshaft-400/50 text-bunker-300">
<FontAwesomeIcon icon={faBan} />
Inactive
</Badge>
</div>
</Tooltip>
</span>
</span>
{idx < approver.user.length - 1 && ","}
</div>
);
})}
</div>
)}
</GenericFieldLabel>
<GenericFieldLabel className="col-span-2" label="Groups">
{approver?.group
@@ -413,8 +486,18 @@ export const ReviewAccessRequestModal = ({
key={`reviewer-${idx + 1}`}
className="flex items-center gap-2 px-2 py-2 text-sm"
>
<div className="flex-1">{el.username}</div>
{getReviewedStatusSymbol(el?.status as ApprovalStatus)}
<div
className={twMerge(
"flex-1",
!el.isOrgMembershipActive && "opacity-40"
)}
>
{el.username}
</div>
{getReviewedStatusSymbol(
el?.status as ApprovalStatus,
el.isOrgMembershipActive
)}
</div>
))}
</div>
@@ -43,6 +43,8 @@ import {
import { EnforcementLevel, PolicyType } from "@app/hooks/api/policies/enums";
import { TWorkspaceUser } from "@app/hooks/api/users/types";
import { PolicyMemberOption } from "./PolicyMemberOption";
type Props = {
isOpen?: boolean;
onToggle: (isOpen: boolean) => void;
@@ -59,7 +61,11 @@ const formSchema = z
secretPath: z.string().trim().min(1),
approvals: z.number().min(1).default(1),
userApprovers: z
.object({ type: z.literal(ApproverType.User), id: z.string() })
.object({
type: z.literal(ApproverType.User),
id: z.string(),
isOrgMembershipActive: z.boolean().optional()
})
.array()
.default([]),
groupApprovers: z
@@ -67,7 +73,11 @@ const formSchema = z
.array()
.default([]),
userBypassers: z
.object({ type: z.literal(BypasserType.User), id: z.string() })
.object({
type: z.literal(BypasserType.User),
id: z.string(),
isOrgMembershipActive: z.boolean().optional()
})
.array()
.default([]),
groupBypassers: z
@@ -80,7 +90,11 @@ const formSchema = z
sequenceApprovers: z
.object({
user: z
.object({ type: z.literal(ApproverType.User), id: z.string() })
.object({
type: z.literal(ApproverType.User),
id: z.string(),
isOrgMembershipActive: z.boolean().optional()
})
.array()
.default([]),
group: z
@@ -139,7 +153,11 @@ const Form = ({
userApprovers:
editValues?.approvers
?.filter((approver) => approver.type === ApproverType.User)
.map(({ id, type }) => ({ id, type: type as ApproverType.User })) || [],
.map(({ id, type, isOrgMembershipActive }) => ({
id,
type: type as ApproverType.User,
isOrgMembershipActive
})) || [],
groupApprovers:
editValues?.approvers
?.filter((approver) => approver.type === ApproverType.Group)
@@ -235,7 +253,9 @@ const Form = ({
...data,
approvers: sequenceApprovers?.flatMap((approvers, index) =>
approvers.user
.map((el) => ({ ...el, sequence: index + 1 }) as Approver)
.map(
(el) => ({ ...el, sequence: index + 1 }) as Omit<Approver, "isOrgMembershipActive">
)
.concat(approvers.group.map((el) => ({ ...el, sequence: index + 1 })))
),
approvalsRequired: sequenceApprovers?.map((el, index) => ({
@@ -291,7 +311,9 @@ const Form = ({
...data,
approvers: sequenceApprovers?.flatMap((approvers, index) =>
approvers.user
.map((el) => ({ ...el, sequence: index + 1 }) as Approver)
.map(
(el) => ({ ...el, sequence: index + 1 }) as Omit<Approver, "isOrgMembershipActive">
)
.concat(approvers.group.map((el) => ({ ...el, sequence: index + 1 })))
),
approvalsRequired: sequenceApprovers?.map((el, index) => ({
@@ -329,7 +351,8 @@ const Form = ({
() =>
members.map((member) => ({
id: member.user.id,
type: ApproverType.User
type: ApproverType.User,
isOrgMembershipActive: member.user.isOrgMembershipActive
})),
[members]
);
@@ -347,7 +370,8 @@ const Form = ({
() =>
members.map((member) => ({
id: member.user.id,
type: BypasserType.User
type: BypasserType.User,
isOrgMembershipActive: member.user.isOrgMembershipActive
})),
[members]
);
@@ -608,6 +632,7 @@ const Form = ({
isMulti
placeholder="Select members..."
options={memberOptions}
components={{ Option: PolicyMemberOption }}
getOptionValue={(option) => option.id}
getOptionLabel={(option) => {
const member = members?.find((m) => m.user.id === option.id);
@@ -685,6 +710,7 @@ const Form = ({
menuPlacement="top"
isMulti
placeholder="Select members..."
components={{ Option: PolicyMemberOption }}
options={memberOptions}
getOptionValue={(option) => option.id}
getOptionLabel={(option) => {
@@ -783,6 +809,7 @@ const Form = ({
menuPlacement="top"
isMulti
placeholder="Select members..."
components={{ Option: PolicyMemberOption }}
options={bypasserMemberOptions}
getOptionValue={(option) => option.id}
getOptionLabel={(option) => {
@@ -1,5 +1,6 @@
import { useMemo } from "react";
import {
faBan,
faClipboardCheck,
faEdit,
faEllipsisV,
@@ -19,6 +20,7 @@ import {
GenericFieldLabel,
IconButton,
Td,
Tooltip,
Tr
} from "@app/components/v2";
import { Badge } from "@app/components/v2/Badge";
@@ -86,10 +88,9 @@ export const ApprovalPolicyRow = ({
return entityInSameSequence?.map((el) => {
return {
sequence: el.sequence || policy.approvals,
userLabels: members
?.filter((member) => el.user.find((i) => i.id === member.user.id))
.map((member) => getMemberLabel(member))
.join(", "),
users: members.filter((member) => el.user.find((i) => i.id === member.user.id)),
groupLabels: groups
?.filter(({ group }) => el.group.find((i) => i.id === group.id))
.map(({ group }) => group.name)
@@ -212,7 +213,35 @@ export const ApprovalPolicyRow = ({
)}
<div className="grid flex-1 grid-cols-5 border-b border-mineshaft-600 p-4">
<GenericFieldLabel className="col-span-2" icon={faUser} label="Users">
{el.userLabels}
{Boolean(el.users.length) && (
<div className="flex flex-row flex-wrap gap-2">
{el.users.map((u, idx) => {
return u.user.isOrgMembershipActive ? (
<div className="flex items-center" key={u.id}>
<span>{getMemberLabel(u)}</span>
{idx < el.users.length - 1 && ","}
</div>
) : (
<div className="flex items-center" key={u.id}>
<span className="flex items-center opacity-40">
{getMemberLabel(u)}
<span className="text-xs">
<Tooltip content="This user has been deactivated and no longer has an active organization membership.">
<div>
<Badge className="pointer-events-none ml-1 mr-auto flex h-5 w-min items-center gap-1.5 whitespace-nowrap bg-mineshaft-400/50 text-bunker-300">
<FontAwesomeIcon icon={faBan} />
Inactive
</Badge>
</div>
</Tooltip>
</span>
</span>
{idx < el.users.length - 1 && ","}
</div>
);
})}
</div>
)}
</GenericFieldLabel>
<GenericFieldLabel className="col-span-2" icon={faUserGroup} label="Groups">
{el.groupLabels}
@@ -0,0 +1,40 @@
import { components, OptionProps } from "react-select";
import { faCheckCircle } from "@fortawesome/free-regular-svg-icons";
import { faBan } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { twMerge } from "tailwind-merge";
import { Badge } from "@app/components/v2";
import { BypasserType } from "@app/hooks/api/accessApproval/types";
import { ApproverType } from "@app/hooks/api/secretApproval/types";
export const PolicyMemberOption = ({
isSelected,
children,
...props
}: OptionProps<{
id: string;
type: BypasserType | ApproverType;
isOrgMembershipActive?: boolean;
}>) => {
return (
<components.Option isSelected={isSelected} {...props}>
<div className="flex flex-row items-center justify-between">
<p
className={twMerge("truncate", !props.data.isOrgMembershipActive && "text-mineshaft-400")}
>
{children}
</p>
{!props.data.isOrgMembershipActive && (
<Badge className="pointer-events-none ml-1 mr-auto flex h-5 w-min items-center gap-1.5 whitespace-nowrap bg-mineshaft-400/50 text-bunker-300">
<FontAwesomeIcon icon={faBan} />
Inactive
</Badge>
)}
{isSelected && (
<FontAwesomeIcon className="ml-2 text-primary" icon={faCheckCircle} size="sm" />
)}
</div>
</components.Option>
);
};
@@ -1,3 +1,4 @@
/* eslint-disable no-nested-ternary */
import { ReactNode } from "react";
import { Controller, useForm } from "react-hook-form";
import {
@@ -8,7 +9,8 @@ import {
faCodeBranch,
faComment,
faFolder,
faHourglass
faHourglass,
faUserSlash
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod";
@@ -85,6 +87,7 @@ const getReviewedStatusSymbol = (status?: ApprovalStatus) => {
return <FontAwesomeIcon icon={faCheck} size="xs" className="text-green" />;
if (status === ApprovalStatus.REJECTED)
return <FontAwesomeIcon icon={faBan} size="xs" className="text-red" />;
return <FontAwesomeIcon icon={faHourglass} size="xs" className="text-yellow" />;
};
@@ -162,11 +165,15 @@ export const SecretApprovalRequestChanges = ({
secretApprovalRequestDetails.policy.bypassers.some(({ userId }) => userId === userSession.id);
const reviewedUsers = secretApprovalRequestDetails?.reviewers?.reduce<
Record<string, { status: ApprovalStatus; comment: string }>
Record<string, { status: ApprovalStatus; comment: string; isOrgMembershipActive: boolean }>
>(
(prev, curr) => ({
...prev,
[curr.userId]: { status: curr.status, comment: curr.comment }
[curr.userId]: {
status: curr.status,
comment: curr.comment,
isOrgMembershipActive: curr.isOrgMembershipActive
}
}),
{}
);
@@ -533,26 +540,44 @@ export const SecretApprovalRequestChanges = ({
)
.map((requiredApprover) => {
const reviewer = reviewedUsers?.[requiredApprover.userId];
const { isOrgMembershipActive } = requiredApprover;
return (
<div
className="flex flex-nowrap items-center justify-between space-x-2 rounded border border-mineshaft-600 bg-mineshaft-800 px-2 py-1"
key={`required-approver-${requiredApprover.userId}`}
>
<Tooltip
content={
requiredApprover.firstName
? `${requiredApprover.firstName || ""} ${requiredApprover.lastName || ""}`
: undefined
}
position="left"
sideOffset={10}
<div
className={twMerge(
"flex items-center gap-1 text-sm",
!isOrgMembershipActive && "opacity-40"
)}
>
<div className="flex text-sm">
<div>{requiredApprover?.email}</div>
<span className="text-red">*</span>
</div>
</Tooltip>
<div>
<Tooltip
content={
!isOrgMembershipActive
? "This user has been deactivated and no longer has an active organization membership."
: requiredApprover.firstName
? `${requiredApprover.firstName || ""} ${requiredApprover.lastName || ""}`
: undefined
}
position="left"
sideOffset={10}
>
<div className="flex items-center">
<div>{requiredApprover?.email}</div>
<span className="text-red">*</span>
{!isOrgMembershipActive && (
<FontAwesomeIcon
icon={faUserSlash}
size="xs"
className="ml-1 text-mineshaft-300"
/>
)}
</div>
</Tooltip>
</div>
<div className="flex items-center">
{reviewer?.comment && (
<Tooltip className="max-w-lg break-words" content={reviewer.comment}>
<FontAwesomeIcon
@@ -562,9 +587,21 @@ export const SecretApprovalRequestChanges = ({
/>
</Tooltip>
)}
<Tooltip content={`Status: ${reviewer?.status || ApprovalStatus.PENDING}`}>
{getReviewedStatusSymbol(reviewer?.status)}
</Tooltip>
<div className="flex gap-2">
<Tooltip
className="relative !z-[500]"
content={
<span className="text-sm">
Status:{" "}
<span className="capitalize">
{reviewer?.status || ApprovalStatus.PENDING}
</span>
</span>
}
>
{getReviewedStatusSymbol(reviewer?.status)}
</Tooltip>
</div>
</div>
</div>
);
@@ -578,20 +615,42 @@ export const SecretApprovalRequestChanges = ({
)
.map((reviewer) => {
const status = reviewedUsers?.[reviewer.userId].status;
const { isOrgMembershipActive } = reviewer;
return (
<div
className="flex flex-nowrap items-center space-x-2 rounded bg-mineshaft-800 px-2 py-1"
className="flex flex-nowrap items-center justify-between space-x-2 rounded bg-mineshaft-800 px-2 py-1"
key={`required-approver-${reviewer.userId}`}
>
<div className="flex-grow text-sm">
<Tooltip content={`${reviewer.firstName || ""} ${reviewer.lastName || ""}`}>
<span>{reviewer?.email} </span>
<div
className={twMerge(
"flex items-center gap-1 text-sm",
!isOrgMembershipActive && "opacity-40"
)}
>
<Tooltip
className="relative !z-[500]"
content={
!isOrgMembershipActive
? "This user has been deactivated and no longer has an active organization membership."
: `${reviewer.firstName || ""} ${reviewer.lastName || ""}`
}
>
<div className="flex items-center">
<span>{reviewer?.email} </span>
{!isOrgMembershipActive && (
<FontAwesomeIcon
icon={faUserSlash}
size="xs"
className="ml-1 text-mineshaft-300"
/>
)}
</div>
</Tooltip>
<span className="text-red">*</span>
</div>
<div>
{reviewer.comment && (
<Tooltip content={reviewer.comment}>
<Tooltip className="relative !z-[500]" content={reviewer.comment}>
<FontAwesomeIcon
icon={faComment}
size="xs"
@@ -599,7 +658,15 @@ export const SecretApprovalRequestChanges = ({
/>
</Tooltip>
)}
<Tooltip content={status || ApprovalStatus.PENDING}>
<Tooltip
className="relative !z-[500]"
content={
<span className="text-sm">
Status:{" "}
<span className="capitalize">{status || ApprovalStatus.PENDING}</span>
</span>
}
>
{getReviewedStatusSymbol(status)}
</Tooltip>
</div>
@@ -14,6 +14,7 @@ import {
faFingerprint,
faFolder,
faFolderPlus,
faInfoCircle,
faKey,
faLock,
faPaste,
@@ -32,6 +33,7 @@ import { createNotification } from "@app/components/notifications";
import { ProjectPermissionCan } from "@app/components/permissions";
import { CreateSecretRotationV2Modal } from "@app/components/secret-rotations-v2";
import {
Badge,
Button,
DeleteActionModal,
DropdownMenu,
@@ -97,7 +99,7 @@ import { CreateSecretImportForm } from "./CreateSecretImportForm";
import { FolderForm } from "./FolderForm";
import { MoveSecretsModal } from "./MoveSecretsModal";
type TParsedEnv = Record<string, { value: string; comments: string[]; secretPath?: string }>;
type TParsedEnv = { value: string; comments: string[]; secretPath?: string; secretKey: string }[];
type TParsedFolderEnv = Record<
string,
Record<string, { value: string; comments: string[]; secretPath?: string }>
@@ -405,8 +407,8 @@ export const ActionBar = ({
}
try {
const allUpdateSecrets: TParsedEnv = {};
const allCreateSecrets: TParsedEnv = {};
const allUpdateSecrets: TParsedEnv = [];
const allCreateSecrets: TParsedEnv = [];
await Promise.all(
Object.entries(envByPath).map(async ([folderPath, secrets]) => {
@@ -437,7 +439,7 @@ export const ActionBar = ({
(_, i) => secretFolderKeys.slice(i * batchSize, (i + 1) * batchSize)
);
const existingSecretLookup: Record<string, boolean> = {};
const existingSecretLookup = new Set<string>();
const processBatches = async () => {
await secretBatches.reduce(async (previous, batch) => {
@@ -451,7 +453,7 @@ export const ActionBar = ({
});
batchSecrets.forEach((secret) => {
existingSecretLookup[secret.secretKey] = true;
existingSecretLookup.add(`${normalizedPath}-${secret.secretKey}`);
});
}, Promise.resolve());
};
@@ -465,18 +467,18 @@ export const ActionBar = ({
// Store the path with the secret for later batch processing
const secretWithPath = {
...secretData,
secretPath: normalizedPath
secretPath: normalizedPath,
secretKey
};
if (existingSecretLookup[secretKey]) {
allUpdateSecrets[secretKey] = secretWithPath;
if (existingSecretLookup.has(`${normalizedPath}-${secretKey}`)) {
allUpdateSecrets.push(secretWithPath);
} else {
allCreateSecrets[secretKey] = secretWithPath;
allCreateSecrets.push(secretWithPath);
}
});
})
);
handlePopUpOpen("confirmUpload", {
update: allUpdateSecrets,
create: allCreateSecrets
@@ -519,7 +521,7 @@ export const ActionBar = ({
const allPaths = new Set<string>();
// Add paths from create secrets
Object.values(create || {}).forEach((secData) => {
create.forEach((secData) => {
if (secData.secretPath && secData.secretPath !== secretPath) {
allPaths.add(secData.secretPath);
}
@@ -575,8 +577,8 @@ export const ActionBar = ({
return Promise.resolve();
}, Promise.resolve());
if (Object.keys(create || {}).length > 0) {
Object.entries(create).forEach(([secretKey, secData]) => {
if (create.length > 0) {
create.forEach((secData) => {
// Use the stored secretPath or fall back to the current secretPath
const path = secData.secretPath || secretPath;
@@ -588,7 +590,7 @@ export const ActionBar = ({
type: SecretType.Shared,
secretComment: secData.comments.join("\n"),
secretValue: secData.value,
secretKey
secretKey: secData.secretKey
});
});
@@ -604,8 +606,8 @@ export const ActionBar = ({
);
}
if (Object.keys(update || {}).length > 0) {
Object.entries(update).forEach(([secretKey, secData]) => {
if (update.length > 0) {
update.forEach((secData) => {
// Use the stored secretPath or fall back to the current secretPath
const path = secData.secretPath || secretPath;
@@ -617,7 +619,7 @@ export const ActionBar = ({
type: SecretType.Shared,
secretComment: secData.comments.join("\n"),
secretValue: secData.value,
secretKey
secretKey: secData.secretKey
});
});
@@ -665,6 +667,8 @@ export const ActionBar = ({
const isTableFiltered =
Object.values(filter.tags).some(Boolean) || Object.values(filter.include).some(Boolean);
const filteredTags = Object.values(filter?.tags ?? {}).filter(Boolean).length;
return (
<>
<div className="mt-4 flex items-center space-x-2">
@@ -697,7 +701,7 @@ export const ActionBar = ({
Filters
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="p-0">
<DropdownMenuContent align="end" sideOffset={2} className="p-0">
<DropdownMenuGroup>Filter By</DropdownMenuGroup>
<DropdownMenuItem
onClick={(e) => {
@@ -776,11 +780,19 @@ export const ActionBar = ({
iconPos="right"
icon={<FontAwesomeIcon icon={faChevronRight} size="sm" />}
>
Tags
<div className="flex w-full justify-between">
<span>Tags</span>
{Boolean(filteredTags) && <Badge>{filteredTags} Applied</Badge>}
</div>
</DropdownSubMenuTrigger>
<DropdownSubMenuContent className="thin-scrollbar max-h-[20rem] overflow-y-auto rounded-l-none">
<DropdownMenuLabel className="sticky top-0 bg-mineshaft-900">
Apply Tags to Filter Secrets
<div className="flex w-full items-center justify-between">
<span>Filter by Secret Tags</span>
<Tooltip content="Matches secrets with one or more of the applied tags">
<FontAwesomeIcon icon={faInfoCircle} />
</Tooltip>
</div>
</DropdownMenuLabel>
{tags.map(({ id, slug, color }) => (
<DropdownMenuItem
@@ -1229,8 +1241,8 @@ export const ActionBar = ({
<div className="flex flex-col text-gray-300">
<div>Your project already contains the following {updateSecretCount} secrets:</div>
<div className="mt-2 text-sm text-gray-400">
{Object.keys((popUp?.confirmUpload?.data as TSecOverwriteOpt)?.update || {})
?.map((key) => key)
{(popUp?.confirmUpload?.data as TSecOverwriteOpt)?.update
?.map((sec) => sec.secretKey)
.join(", ")}
</div>
<div className="mt-6">
@@ -0,0 +1,948 @@
/* eslint-disable jsx-a11y/label-has-associated-control */
import { Controller, useForm } from "react-hook-form";
import { faPlus, faTrash } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod";
import ms from "ms";
import { z } from "zod";
import { TtlFormLabel } from "@app/components/features";
import { createNotification } from "@app/components/notifications";
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
Button,
FilterableSelect,
FormControl,
IconButton,
Input,
SecretInput,
Switch,
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";
import { slugSchema } from "@app/lib/schemas";
// Component for managing scopes and collections within a bucket
const BucketScopesConfiguration = ({
control,
bucketIndex,
bucketsValue,
setValue,
addScope,
removeScope,
addCollection,
removeCollection
}: {
control: any;
bucketIndex: number;
bucketsValue: any;
setValue: any;
addScope: (bucketIndex: number) => void;
removeScope: (bucketIndex: number, scopeIndex: number) => void;
addCollection: (bucketIndex: number, scopeIndex: number) => void;
removeCollection: (bucketIndex: number, scopeIndex: number, collectionIndex: number) => void;
}) => {
const bucket = Array.isArray(bucketsValue) ? bucketsValue[bucketIndex] : null;
const scopeFields = bucket?.scopes || [];
return (
<div className="space-y-3">
<div className="flex items-center justify-between">
<label className="text-sm font-medium text-mineshaft-300">Scopes</label>
<Button
type="button"
variant="outline_bg"
size="xs"
onClick={() => addScope(bucketIndex)}
leftIcon={<FontAwesomeIcon icon={faPlus} />}
>
Add Scope
</Button>
</div>
{scopeFields.map((_scope: any, scopeIndex: number) => (
<div
key={`scope-${scopeIndex + 1}`}
className="space-y-3 rounded border border-mineshaft-600 bg-mineshaft-700 p-3"
>
<div className="flex items-center justify-between">
<h5 className="text-xs font-medium text-mineshaft-200">Scope {scopeIndex + 1}</h5>
<IconButton
type="button"
variant="plain"
ariaLabel="Remove scope"
size="sm"
onClick={() => removeScope(bucketIndex, scopeIndex)}
>
<FontAwesomeIcon icon={faTrash} className="text-red-400" />
</IconButton>
</div>
<Controller
control={control}
name={`provider.buckets.${bucketIndex}.scopes.${scopeIndex}.name`}
render={({ field, fieldState: { error } }) => (
<FormControl label="Scope Name" isError={Boolean(error)} errorText={error?.message}>
<Input {...field} placeholder="e.g., inventory, _default" className="text-sm" />
</FormControl>
)}
/>
<div className="space-y-2 pl-4">
<div className="flex items-center justify-between">
<label className="text-xs font-medium text-mineshaft-300">Collections</label>
<Button
type="button"
variant="outline_bg"
size="xs"
onClick={() => addCollection(bucketIndex, scopeIndex)}
leftIcon={<FontAwesomeIcon icon={faPlus} />}
>
Add Collection
</Button>
</div>
{scopeFields[scopeIndex]?.collections?.map(
(collection: string, collectionIndex: number) => (
<div
// eslint-disable-next-line react/no-array-index-key
key={`collection-${bucketIndex}-${scopeIndex}-${collectionIndex}`}
className="flex items-center space-x-2"
>
<FormControl className="flex-1">
<Input
value={collection || ""}
onChange={(e) => {
const currentBuckets = Array.isArray(bucketsValue) ? [...bucketsValue] : [];
if (currentBuckets[bucketIndex]?.scopes?.[scopeIndex]?.collections) {
currentBuckets[bucketIndex].scopes[scopeIndex].collections[
collectionIndex
] = e.target.value;
setValue("provider.buckets", currentBuckets);
}
}}
placeholder="e.g., airport, airline"
className="text-sm"
/>
</FormControl>
<IconButton
type="button"
variant="plain"
ariaLabel="Remove collection"
className="mb-4"
size="sm"
onClick={() => removeCollection(bucketIndex, scopeIndex, collectionIndex)}
>
<FontAwesomeIcon icon={faTrash} className="text-red-400" />
</IconButton>
</div>
)
)}
{(!scopeFields[scopeIndex]?.collections ||
scopeFields[scopeIndex].collections.length === 0) && (
<div className="text-xs italic text-mineshaft-400">
No collections specified (access to all collections in scope)
</div>
)}
</div>
</div>
))}
{scopeFields.length === 0 && (
<div className="rounded border border-dashed border-mineshaft-600 bg-mineshaft-700 p-4 text-center">
<p className="mb-2 text-xs text-mineshaft-400">
No scopes configured (access to all scopes in bucket)
</p>
<Button
type="button"
variant="outline_bg"
size="xs"
onClick={() => addScope(bucketIndex)}
leftIcon={<FontAwesomeIcon icon={faPlus} />}
>
Add Scope
</Button>
</div>
)}
</div>
);
};
const couchbaseRoles = [
{ value: "read", label: "Read", description: "Read-only access to bucket data" },
{
value: "write",
label: "Write",
description: "Full write access to bucket data"
}
];
const passwordRequirementsSchema = z
.object({
length: z.number().min(8, "Password must be at least 8 characters").max(128),
required: z
.object({
lowercase: z.number().min(1, "At least 1 lowercase character required"),
uppercase: z.number().min(1, "At least 1 uppercase character required"),
digits: z.number().min(1, "At least 1 digit required"),
symbols: z.number().min(1, "At least 1 special character required")
})
.refine((data) => {
const total = Object.values(data).reduce((sum, count) => sum + count, 0);
return total <= 128;
}, "Sum of required characters cannot exceed 128"),
allowedSymbols: z
.string()
.refine((symbols) => {
const forbiddenChars = ["<", ">", ";", ".", "*", "&", "|", "£"];
return !forbiddenChars.some((char) => symbols?.includes(char));
}, "Cannot contain: < > ; . * & | £")
.optional()
})
.refine((data) => {
const total = Object.values(data.required).reduce((sum, count) => sum + count, 0);
return total <= data.length;
}, "Sum of required characters cannot exceed the total length");
const bucketSchema = z.object({
name: z.string().trim().min(1, "Bucket name is required"),
scopes: z
.array(
z.object({
name: z.string().trim().min(1, "Scope name is required"),
collections: z.array(z.string().trim().min(1)).optional()
})
)
.optional()
});
const formSchema = z.object({
provider: z.object({
url: z.string().url().trim().min(1),
orgId: z.string().trim().min(1),
projectId: z.string().trim().min(1),
clusterId: z.string().trim().min(1),
roles: z.array(z.string()).min(1, "At least one role must be selected"),
buckets: z.union([z.string().trim().min(1), z.array(bucketSchema)]),
useAdvancedBuckets: z.boolean().default(false),
passwordRequirements: passwordRequirementsSchema.optional(),
auth: z.object({
apiKey: z.string().trim().min(1)
})
}),
defaultTTL: z.string().superRefine((val, ctx) => {
const valMs = ms(val);
if (valMs < 60 * 1000)
ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be a greater than 1min" });
if (valMs > 24 * 60 * 60 * 1000)
ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than a day" });
}),
maxTTL: z
.string()
.optional()
.superRefine((val, ctx) => {
if (!val) return;
const valMs = ms(val);
if (valMs < 60 * 1000)
ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be a greater than 1min" });
if (valMs > 24 * 60 * 60 * 1000)
ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than a day" });
}),
name: slugSchema(),
environment: z.object({ name: z.string(), slug: z.string() }),
usernameTemplate: z.string().nullable().optional()
});
type TForm = z.infer<typeof formSchema>;
type Props = {
onCompleted: () => void;
onCancel: () => void;
secretPath: string;
projectSlug: string;
environments: WorkspaceEnv[];
isSingleEnvironmentMode?: boolean;
};
export const CouchbaseInputForm = ({
onCompleted,
onCancel,
environments,
secretPath,
projectSlug,
isSingleEnvironmentMode
}: Props) => {
const {
control,
formState: { isSubmitting },
handleSubmit,
setValue,
getValues,
watch
} = useForm<TForm>({
resolver: zodResolver(formSchema),
defaultValues: {
provider: {
url: "https://cloudapi.cloud.couchbase.com",
roles: ["read"],
buckets: "*",
useAdvancedBuckets: false,
passwordRequirements: {
length: 12,
required: {
lowercase: 1,
uppercase: 1,
digits: 1,
symbols: 1
},
allowedSymbols: "!@#$%^()_+-=[]{}:,?/~`"
},
auth: {
apiKey: ""
}
},
environment: isSingleEnvironmentMode ? environments[0] : undefined,
usernameTemplate: "{{randomUsername}}"
}
});
const createDynamicSecret = useCreateDynamicSecret();
const isAdvancedMode = watch("provider.useAdvancedBuckets");
const bucketsValue = watch("provider.buckets");
const addBucket = () => {
const currentBuckets = Array.isArray(bucketsValue) ? bucketsValue : [];
setValue("provider.buckets", [...currentBuckets, { name: "", scopes: [] }]);
};
const removeBucket = (index: number) => {
const currentBuckets = Array.isArray(bucketsValue) ? bucketsValue : [];
const newBuckets = currentBuckets.filter((_, i) => i !== index);
setValue("provider.buckets", newBuckets);
};
const addScope = (bucketIndex: number) => {
const currentBuckets = Array.isArray(bucketsValue) ? [...bucketsValue] : [];
if (currentBuckets[bucketIndex]) {
const currentScopes = currentBuckets[bucketIndex].scopes || [];
currentBuckets[bucketIndex] = {
...currentBuckets[bucketIndex],
scopes: [...currentScopes, { name: "", collections: [] }]
};
setValue("provider.buckets", currentBuckets);
}
};
const removeScope = (bucketIndex: number, scopeIndex: number) => {
const currentBuckets = Array.isArray(bucketsValue) ? [...bucketsValue] : [];
if (currentBuckets[bucketIndex]?.scopes) {
currentBuckets[bucketIndex].scopes = currentBuckets[bucketIndex].scopes.filter(
(_, i) => i !== scopeIndex
);
setValue("provider.buckets", currentBuckets);
}
};
const addCollection = (bucketIndex: number, scopeIndex: number) => {
const currentBuckets = Array.isArray(bucketsValue) ? [...bucketsValue] : [];
if (currentBuckets[bucketIndex]?.scopes?.[scopeIndex]) {
const currentCollections = currentBuckets[bucketIndex].scopes[scopeIndex].collections || [];
currentBuckets[bucketIndex].scopes[scopeIndex].collections = [...currentCollections, ""];
setValue("provider.buckets", currentBuckets);
}
};
const removeCollection = (bucketIndex: number, scopeIndex: number, collectionIndex: number) => {
const currentBuckets = Array.isArray(bucketsValue) ? [...bucketsValue] : [];
if (currentBuckets[bucketIndex]?.scopes?.[scopeIndex]?.collections) {
currentBuckets[bucketIndex].scopes[scopeIndex].collections = currentBuckets[
bucketIndex
].scopes[scopeIndex].collections.filter((_, i) => i !== collectionIndex);
setValue("provider.buckets", currentBuckets);
}
};
const handleCreateDynamicSecret = async ({
name,
maxTTL,
provider,
defaultTTL,
environment,
usernameTemplate
}: TForm) => {
if (createDynamicSecret.isPending) return;
const isDefaultUsernameTemplate = usernameTemplate === "{{randomUsername}}";
const transformedProvider = {
...provider,
buckets: provider.useAdvancedBuckets ? provider.buckets : (provider.buckets as string)
};
const { useAdvancedBuckets, ...finalProvider } = transformedProvider;
try {
await createDynamicSecret.mutateAsync({
provider: { type: DynamicSecretProviders.Couchbase, inputs: finalProvider },
maxTTL,
name,
path: secretPath,
defaultTTL,
projectSlug,
environmentSlug: environment.slug,
usernameTemplate:
!usernameTemplate || isDefaultUsernameTemplate ? undefined : usernameTemplate
});
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">
<Controller
control={control}
name="defaultTTL"
defaultValue="1h"
render={({ field, fieldState: { error } }) => (
<FormControl
label={<TtlFormLabel label="Default TTL" />}
isError={Boolean(error?.message)}
errorText={error?.message}
>
<Input {...field} />
</FormControl>
)}
/>
</div>
<div className="w-32">
<Controller
control={control}
name="maxTTL"
defaultValue="24h"
render={({ field, fieldState: { error } }) => (
<FormControl
label={<TtlFormLabel label="Max TTL" />}
isError={Boolean(error?.message)}
errorText={error?.message}
>
<Input {...field} />
</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">
<div className="flex items-center space-x-2">
<Controller
control={control}
name="provider.url"
defaultValue="https://cloudapi.cloud.couchbase.com"
render={({ field, fieldState: { error } }) => (
<FormControl
label="URL"
className="w-full"
isError={Boolean(error?.message)}
errorText={error?.message}
>
<Input placeholder="https://cloudapi.cloud.couchbase.com" {...field} />
</FormControl>
)}
/>
</div>
<div className="flex flex-col space-y-4">
<Controller
control={control}
name="provider.orgId"
defaultValue=""
render={({ field, fieldState: { error } }) => (
<FormControl
label="Organization ID"
className="w-full"
isError={Boolean(error?.message)}
errorText={error?.message}
>
<Input {...field} />
</FormControl>
)}
/>
<div className="flex items-center space-x-2">
<Controller
control={control}
name="provider.projectId"
defaultValue=""
render={({ field, fieldState: { error } }) => (
<FormControl
label="Project ID"
className="w-full"
isError={Boolean(error?.message)}
errorText={error?.message}
>
<Input {...field} />
</FormControl>
)}
/>
<Controller
control={control}
name="provider.clusterId"
defaultValue=""
render={({ field, fieldState: { error } }) => (
<FormControl
label="Cluster ID"
className="w-full"
isError={Boolean(error?.message)}
errorText={error?.message}
>
<Input {...field} />
</FormControl>
)}
/>
</div>
<Controller
control={control}
name="provider.roles"
defaultValue={["read"]}
render={({ field: { value, onChange }, fieldState: { error } }) => (
<FormControl
label="Roles"
className="w-full"
isError={Boolean(error?.message)}
errorText={error?.message}
helperText="Select one or more roles to assign to the user"
>
<FilterableSelect
isMulti
value={couchbaseRoles.filter((role) => value?.includes(role.value))}
onChange={(selectedRoles) => {
if (Array.isArray(selectedRoles)) {
onChange(selectedRoles.map((role: any) => role.value));
} else {
onChange([]);
}
}}
options={couchbaseRoles}
placeholder="Select roles..."
getOptionLabel={(option) => option.label}
getOptionValue={(option) => option.value}
/>
</FormControl>
)}
/>
<Controller
control={control}
name="provider.useAdvancedBuckets"
render={({ field: { value, onChange } }) => (
<FormControl
label="Advanced Bucket Configuration"
helperText="Enable to configure specific buckets, scopes and collections. When disabled, '*' grants access to all buckets, scopes, and collections."
>
<Switch
id="advanced-buckets-switch"
isChecked={value}
onCheckedChange={(checked) => {
onChange(checked);
const bucketsController = getValues("provider.buckets");
if (checked && typeof bucketsController === "string") {
setValue("provider.buckets", []);
} else if (!checked && Array.isArray(bucketsController)) {
setValue("provider.buckets", "*");
}
}}
/>
</FormControl>
)}
/>
{!watch("provider.useAdvancedBuckets") && (
<Controller
control={control}
name="provider.buckets"
defaultValue="*"
render={({ field, fieldState: { error } }) => (
<FormControl
label="Bucket Access"
className="w-full"
isError={Boolean(error?.message)}
errorText={error?.message}
helperText="Specify bucket names separated by commas (e.g., 'bucket1,bucket2') or use '*' for all buckets, scopes, and collections"
>
<Input
{...field}
value={typeof field.value === "string" ? field.value : "*"}
onChange={(e) => field.onChange(e.target.value)}
placeholder="* (all buckets, scopes & collections) or bucket1,bucket2,bucket3"
/>
</FormControl>
)}
/>
)}
{isAdvancedMode && Array.isArray(bucketsValue) && (
<div className="space-y-4">
<div className="flex items-center justify-between">
<div>
<div className="text-sm font-medium text-mineshaft-200">
Advanced Bucket Configuration
</div>
<div className="text-sm text-mineshaft-400">
Configure specific buckets with their scopes and collections. Leave scopes
empty for access to all scopes in a bucket.
</div>
</div>
<Button
type="button"
variant="outline_bg"
size="sm"
onClick={addBucket}
leftIcon={<FontAwesomeIcon icon={faPlus} />}
>
Add Bucket
</Button>
</div>
<div className="space-y-4">
{Array.isArray(bucketsValue) &&
(bucketsValue as any[]).map((_, bucketIndex) => (
<div
key={`bucket-${bucketIndex + 1}`}
className="space-y-4 rounded border border-mineshaft-600 bg-mineshaft-800 p-4"
>
<div className="flex items-center justify-between">
<h4 className="text-sm font-medium text-mineshaft-200">
Bucket {bucketIndex + 1}
</h4>
<IconButton
type="button"
variant="plain"
ariaLabel="Remove bucket"
onClick={() => removeBucket(bucketIndex)}
>
<FontAwesomeIcon icon={faTrash} className="text-red-400" />
</IconButton>
</div>
<Controller
control={control}
name={`provider.buckets.${bucketIndex}.name`}
render={({ field, fieldState: { error } }) => (
<FormControl
label="Bucket Name"
isError={Boolean(error)}
errorText={error?.message}
>
<Input {...field} placeholder="e.g., travel-sample" />
</FormControl>
)}
/>
<BucketScopesConfiguration
control={control}
bucketIndex={bucketIndex}
bucketsValue={bucketsValue}
setValue={setValue}
addScope={addScope}
removeScope={removeScope}
addCollection={addCollection}
removeCollection={removeCollection}
/>
</div>
))}
{(!Array.isArray(bucketsValue) || bucketsValue.length === 0) && (
<div className="rounded border border-dashed border-mineshaft-600 p-8 text-center">
<p className="mb-2 text-sm text-mineshaft-400">No buckets configured</p>
<Button
type="button"
variant="outline_bg"
size="sm"
onClick={addBucket}
leftIcon={<FontAwesomeIcon icon={faPlus} />}
>
Add First Bucket
</Button>
</div>
)}
</div>
</div>
)}
<Controller
name="provider.auth.apiKey"
control={control}
render={({ field: { value, onChange }, fieldState: { error } }) => (
<FormControl
errorText={error?.message}
isError={Boolean(error?.message)}
className="w-full"
label="API Key"
>
<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}
valueAlwaysHidden
rows={1}
wrap="hard"
onChange={(e) => onChange(e.target.value)}
/>
</FormControl>
)}
/>
</div>
<Controller
control={control}
name="usernameTemplate"
defaultValue=""
render={({ field, fieldState: { error } }) => (
<FormControl
label="Username Template"
isError={Boolean(error?.message)}
errorText={error?.message}
>
<Input
{...field}
value={field.value || undefined}
className="border-mineshaft-600 bg-mineshaft-900 text-sm"
placeholder="{{randomUsername}}"
/>
</FormControl>
)}
/>
<Accordion type="multiple" className="mb-2 mt-4 w-full bg-mineshaft-700">
<AccordionItem value="password-config">
<AccordionTrigger>
<div className="flex items-center space-x-2">
<span>Password Configuration (optional)</span>
<Tooltip content="Couchbase password requirements: minimum 8 characters, at least 1 uppercase, 1 lowercase, 1 digit, 1 special character. Cannot contain: < > ; . * & | £">
<div className="flex h-4 w-4 cursor-help items-center justify-center rounded-full bg-mineshaft-600 text-xs text-mineshaft-300">
?
</div>
</Tooltip>
</div>
</AccordionTrigger>
<AccordionContent>
<div className="mb-4 text-sm text-mineshaft-300">
Set constraints on the generated Couchbase user password (8-128 characters)
<br />
<span className="text-xs text-mineshaft-400">
Forbidden characters: &lt; &gt; ; . * &amp; | £
</span>
</div>
<div className="space-y-4">
<div>
<Controller
control={control}
name="provider.passwordRequirements.length"
defaultValue={12}
render={({ field, fieldState: { error } }) => (
<FormControl
label="Password Length"
isError={Boolean(error)}
errorText={error?.message}
>
<Input
type="number"
min={8}
max={128}
{...field}
onChange={(e) => field.onChange(Number(e.target.value))}
/>
</FormControl>
)}
/>
</div>
<div className="space-y-2">
<h4 className="text-sm font-medium">Minimum Required Character Counts</h4>
<div className="text-sm text-gray-500">
{(() => {
const total = Object.values(
watch("provider.passwordRequirements.required") || {}
).reduce((sum, count) => sum + Number(count || 0), 0);
const length = watch("provider.passwordRequirements.length") || 0;
const isError = total > length;
return (
<span className={isError ? "text-red-500" : ""}>
Total required characters: {total}{" "}
{isError ? `(exceeds length of ${length})` : ""}
</span>
);
})()}
</div>
<div className="grid grid-cols-2 gap-4">
<Controller
control={control}
name="provider.passwordRequirements.required.lowercase"
defaultValue={1}
render={({ field, fieldState: { error } }) => (
<FormControl
label="Lowercase Count"
isError={Boolean(error)}
errorText={error?.message}
helperText="Min lowercase letters (required: ≥1)"
>
<Input
type="number"
min={1}
{...field}
onChange={(e) => field.onChange(Number(e.target.value))}
/>
</FormControl>
)}
/>
<Controller
control={control}
name="provider.passwordRequirements.required.uppercase"
defaultValue={1}
render={({ field, fieldState: { error } }) => (
<FormControl
label="Uppercase Count"
isError={Boolean(error)}
errorText={error?.message}
helperText="Min uppercase letters (required: ≥1)"
>
<Input
type="number"
min={1}
{...field}
onChange={(e) => field.onChange(Number(e.target.value))}
/>
</FormControl>
)}
/>
<Controller
control={control}
name="provider.passwordRequirements.required.digits"
defaultValue={1}
render={({ field, fieldState: { error } }) => (
<FormControl
label="Digit Count"
isError={Boolean(error)}
errorText={error?.message}
helperText="Min digits (required: ≥1)"
>
<Input
type="number"
min={1}
{...field}
onChange={(e) => field.onChange(Number(e.target.value))}
/>
</FormControl>
)}
/>
<Controller
control={control}
name="provider.passwordRequirements.required.symbols"
defaultValue={1}
render={({ field, fieldState: { error } }) => (
<FormControl
label="Symbol Count"
isError={Boolean(error)}
errorText={error?.message}
helperText="Min special characters (required: ≥1)"
>
<Input
type="number"
min={1}
{...field}
onChange={(e) => field.onChange(Number(e.target.value))}
/>
</FormControl>
)}
/>
</div>
</div>
<div className="space-y-2">
<h4 className="text-sm font-medium">Allowed Symbols</h4>
<Controller
control={control}
name="provider.passwordRequirements.allowedSymbols"
defaultValue="!@#$%^()_+-=[]{}:,?/~`"
render={({ field, fieldState: { error } }) => (
<FormControl
label="Allowed Symbols"
isError={Boolean(error)}
errorText={error?.message}
helperText="Cannot contain: < > ; . * & | £"
>
<Input {...field} placeholder="!@#$%^()_+-=[]{}:,?/~`" />
</FormControl>
)}
/>
</div>
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
{!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>
<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>
);
};
@@ -2,6 +2,7 @@ import { useState } from "react";
import { DiRedis } from "react-icons/di";
import {
SiApachecassandra,
SiCouchbase,
SiElasticsearch,
SiFiles,
SiKubernetes,
@@ -29,6 +30,7 @@ import { AwsElastiCacheInputForm } from "./AwsElastiCacheInputForm";
import { AwsIamInputForm } from "./AwsIamInputForm";
import { AzureEntraIdInputForm } from "./AzureEntraIdInputForm";
import { CassandraInputForm } from "./CassandraInputForm";
import { CouchbaseInputForm } from "./CouchbaseInputForm";
import { ElasticSearchInputForm } from "./ElasticSearchInputForm";
import { GcpIamInputForm } from "./GcpIamInputForm";
import { GithubInputForm } from "./GithubInputForm";
@@ -154,6 +156,11 @@ const DYNAMIC_SECRET_LIST = [
icon: <FontAwesomeIcon icon={faGithub} size="lg" />,
provider: DynamicSecretProviders.Github,
title: "GitHub"
},
{
icon: <SiCouchbase size="1.5rem" />,
provider: DynamicSecretProviders.Couchbase,
title: "Couchbase"
}
];
@@ -608,6 +615,25 @@ export const CreateDynamicSecretForm = ({
/>
</motion.div>
)}
{wizardStep === WizardSteps.ProviderInputs &&
selectedProvider === DynamicSecretProviders.Couchbase && (
<motion.div
key="dynamic-couchbase-step"
transition={{ duration: 0.1 }}
initial={{ opacity: 0, translateX: 30 }}
animate={{ opacity: 1, translateX: 0 }}
exit={{ opacity: 0, translateX: -30 }}
>
<CouchbaseInputForm
onCompleted={handleFormReset}
onCancel={handleFormReset}
projectSlug={projectSlug}
secretPath={secretPath}
environments={environments}
isSingleEnvironmentMode={isSingleEnvironmentMode}
/>
</motion.div>
)}
</AnimatePresence>
</ModalContent>
</Modal>
@@ -8,6 +8,7 @@ import {
faSave
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { AnimatePresence, motion } from "framer-motion";
import { Badge, Button, Input, Modal, ModalContent } from "@app/components/v2";
import { PendingAction } from "@app/hooks/api/secretFolders/types";
@@ -302,47 +303,61 @@ export const CommitForm: React.FC<CommitFormProps> = ({
<>
{/* Floating Panel */}
{!isModalOpen && (
<div className="fixed bottom-4 left-1/2 z-40 w-full max-w-3xl -translate-x-1/2 self-center rounded-lg border border-yellow/30 bg-mineshaft-800 shadow-2xl lg:left-auto lg:translate-x-0">
<div className="flex items-center justify-between p-4">
{/* Left Content */}
<div className="flex-1">
{/* Header */}
<div className="flex items-center gap-2">
<div className="h-2 w-2 rounded-full bg-yellow-500" />
<span className="font-medium text-mineshaft-100">Pending Changes</span>
<Badge variant="primary" className="text-xs">
{totalChangesCount} Change{totalChangesCount !== 1 ? "s" : ""}
</Badge>
<div className="fixed bottom-4 left-1/2 z-40 w-full max-w-3xl -translate-x-1/2 self-center lg:left-auto lg:translate-x-0">
<AnimatePresence mode="wait">
<motion.div
key="commit-panel"
transition={{ duration: 0.3 }}
initial={{ opacity: 0, translateY: 30 }}
animate={{ opacity: 1, translateY: 0 }}
exit={{ opacity: 0, translateY: -30 }}
>
<div className="rounded-lg border border-yellow/30 bg-mineshaft-800 shadow-2xl">
<div className="flex items-center justify-between p-4">
{/* Left Content */}
<div className="flex-1">
{/* Header */}
<div className="flex items-center gap-2">
<div className="h-2 w-2 rounded-full bg-yellow-500" />
<span className="font-medium text-mineshaft-100">Pending Changes</span>
<Badge variant="primary" className="text-xs">
{totalChangesCount} Change{totalChangesCount !== 1 ? "s" : ""}
</Badge>
</div>
{/* Description */}
<p className="text-sm leading-5 text-mineshaft-400">
Review pending changes and commit them to apply the updates.
</p>
</div>
{/* Right Buttons */}
<div className="ml-6 mt-0.5 flex items-center gap-3">
<Button
size="sm"
onClick={() =>
clearAllPendingChanges({ workspaceId, environment, secretPath })
}
isDisabled={totalChangesCount === 0}
variant="outline_bg"
className="px-4 hover:border-red/40 hover:bg-red/[0.1]"
>
Discard
</Button>
<Button
variant="solid"
leftIcon={<FontAwesomeIcon icon={faSave} />}
onClick={() => setIsModalOpen(true)}
isDisabled={totalChangesCount === 0}
className="px-6"
>
Save Changes
</Button>
</div>
</div>
</div>
{/* Description */}
<p className="text-sm leading-5 text-mineshaft-400">
Review pending changes and commit them to apply the updates.
</p>
</div>
{/* Right Buttons */}
<div className="ml-6 mt-0.5 flex items-center gap-3">
<Button
size="sm"
onClick={() => clearAllPendingChanges({ workspaceId, environment, secretPath })}
isDisabled={totalChangesCount === 0}
variant="outline_bg"
className="px-4 hover:border-red/40 hover:bg-red/[0.1]"
>
Discard
</Button>
<Button
variant="solid"
leftIcon={<FontAwesomeIcon icon={faSave} />}
onClick={() => setIsModalOpen(true)}
isDisabled={totalChangesCount === 0}
className="px-6"
>
Save Changes
</Button>
</div>
</div>
</motion.div>
</AnimatePresence>
</div>
)}
@@ -384,6 +384,24 @@ const renderOutputForm = (
);
}
if (provider === DynamicSecretProviders.Couchbase) {
const { username, password } = data as {
username: string;
password: string;
};
return (
<div>
<OutputDisplay label="Username" value={username} />
<OutputDisplay
label="Password"
value={password}
helperText="Important: Copy these credentials now. You will not be able to see them again after you close the modal."
/>
</div>
);
}
return null;
};
@@ -0,0 +1,929 @@
/* eslint-disable jsx-a11y/label-has-associated-control */
import { Controller, useForm } from "react-hook-form";
import { faPlus, faTrash } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod";
import ms from "ms";
import { z } from "zod";
import { TtlFormLabel } from "@app/components/features";
import { createNotification } from "@app/components/notifications";
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
Button,
FilterableSelect,
FormControl,
IconButton,
Input,
SecretInput,
Switch,
Tooltip
} from "@app/components/v2";
import { useUpdateDynamicSecret } from "@app/hooks/api";
import { TDynamicSecret } from "@app/hooks/api/dynamicSecret/types";
import { slugSchema } from "@app/lib/schemas";
import { MetadataForm } from "../MetadataForm";
const BucketScopesConfiguration = ({
control,
bucketIndex,
bucketsValue,
setValue,
addScope,
removeScope,
addCollection,
removeCollection
}: {
control: any;
bucketIndex: number;
bucketsValue: any;
setValue: any;
addScope: (bucketIndex: number) => void;
removeScope: (bucketIndex: number, scopeIndex: number) => void;
addCollection: (bucketIndex: number, scopeIndex: number) => void;
removeCollection: (bucketIndex: number, scopeIndex: number, collectionIndex: number) => void;
}) => {
const bucket = Array.isArray(bucketsValue) ? bucketsValue[bucketIndex] : null;
const scopeFields = bucket?.scopes || [];
return (
<div className="space-y-3">
<div className="flex items-center justify-between">
<label className="text-sm font-medium text-mineshaft-300">Scopes</label>
<Button
type="button"
variant="outline_bg"
size="xs"
onClick={() => addScope(bucketIndex)}
leftIcon={<FontAwesomeIcon icon={faPlus} />}
>
Add Scope
</Button>
</div>
{scopeFields.map((_scope: any, scopeIndex: number) => (
<div
key={`scope-${scopeIndex + 1}`}
className="space-y-3 rounded border border-mineshaft-600 bg-mineshaft-700 p-3"
>
<div className="flex items-center justify-between">
<h5 className="text-xs font-medium text-mineshaft-200">Scope {scopeIndex + 1}</h5>
<IconButton
type="button"
variant="plain"
ariaLabel="Remove scope"
size="sm"
onClick={() => removeScope(bucketIndex, scopeIndex)}
>
<FontAwesomeIcon icon={faTrash} className="text-red-400" />
</IconButton>
</div>
<Controller
control={control}
name={`inputs.buckets.${bucketIndex}.scopes.${scopeIndex}.name`}
render={({ field, fieldState: { error } }) => (
<FormControl label="Scope Name" isError={Boolean(error)} errorText={error?.message}>
<Input {...field} placeholder="e.g., inventory, _default" className="text-sm" />
</FormControl>
)}
/>
<div className="space-y-2 pl-4">
<div className="flex items-center justify-between">
<label className="text-xs font-medium text-mineshaft-300">Collections</label>
<Button
type="button"
variant="outline_bg"
size="xs"
onClick={() => addCollection(bucketIndex, scopeIndex)}
leftIcon={<FontAwesomeIcon icon={faPlus} />}
>
Add Collection
</Button>
</div>
{scopeFields[scopeIndex]?.collections?.map(
(collection: string, collectionIndex: number) => (
<div
// eslint-disable-next-line react/no-array-index-key
key={`collection-${bucketIndex}-${scopeIndex}-${collectionIndex}`}
className="flex items-center space-x-2"
>
<FormControl className="flex-1">
<Input
value={collection || ""}
onChange={(e) => {
const currentBuckets = Array.isArray(bucketsValue) ? [...bucketsValue] : [];
if (currentBuckets[bucketIndex]?.scopes?.[scopeIndex]?.collections) {
currentBuckets[bucketIndex].scopes[scopeIndex].collections[
collectionIndex
] = e.target.value;
setValue("inputs.buckets", currentBuckets);
}
}}
placeholder="e.g., airport, airline"
className="text-sm"
/>
</FormControl>
<IconButton
type="button"
variant="plain"
ariaLabel="Remove collection"
size="sm"
onClick={() => removeCollection(bucketIndex, scopeIndex, collectionIndex)}
>
<FontAwesomeIcon icon={faTrash} className="mb-4 text-red-400" />
</IconButton>
</div>
)
)}
{(!scopeFields[scopeIndex]?.collections ||
scopeFields[scopeIndex].collections.length === 0) && (
<div className="text-xs italic text-mineshaft-400">
No collections specified (access to all collections in scope)
</div>
)}
</div>
</div>
))}
{scopeFields.length === 0 && (
<div className="rounded border border-dashed border-mineshaft-600 bg-mineshaft-700 p-4 text-center">
<p className="mb-2 text-xs text-mineshaft-400">
No scopes configured (access to all scopes in bucket)
</p>
<Button
type="button"
variant="outline_bg"
size="xs"
onClick={() => addScope(bucketIndex)}
leftIcon={<FontAwesomeIcon icon={faPlus} />}
>
Add Scope
</Button>
</div>
)}
</div>
);
};
const couchbaseRoles = [
{ value: "read", label: "Read", description: "Read-only access to bucket data" },
{
value: "write",
label: "Write",
description: "Full write access to bucket data"
}
];
const passwordRequirementsSchema = z
.object({
length: z.number().min(8, "Password must be at least 8 characters").max(128),
required: z
.object({
lowercase: z.number().min(1, "At least 1 lowercase character required"),
uppercase: z.number().min(1, "At least 1 uppercase character required"),
digits: z.number().min(1, "At least 1 digit required"),
symbols: z.number().min(1, "At least 1 special character required")
})
.refine((data) => {
const total = Object.values(data).reduce((sum, count) => sum + count, 0);
return total <= 128;
}, "Sum of required characters cannot exceed 128"),
allowedSymbols: z
.string()
.refine((symbols) => {
const forbiddenChars = ["<", ">", ";", ".", "*", "&", "|", "�"];
return !forbiddenChars.some((char) => symbols?.includes(char));
}, "Cannot contain: < > ; . * &")
.optional()
})
.refine((data) => {
const total = Object.values(data.required).reduce((sum, count) => sum + count, 0);
return total <= data.length;
}, "Sum of required characters cannot exceed the total length");
const bucketSchema = z.object({
name: z.string().trim().min(1, "Bucket name is required"),
scopes: z
.array(
z.object({
name: z.string().trim().min(1, "Scope name is required"),
collections: z.array(z.string().trim().min(1)).optional()
})
)
.optional()
});
const formSchema = z.object({
inputs: z
.object({
url: z.string().url().min(1),
orgId: z.string().min(1),
projectId: z.string().min(1),
clusterId: z.string().min(1),
roles: z.array(z.string()).min(1),
buckets: z.union([z.string().trim().min(1), z.array(bucketSchema)]),
useAdvancedBuckets: z.boolean().default(false),
passwordRequirements: passwordRequirementsSchema.optional(),
auth: z.object({
apiKey: z.string().min(1)
})
})
.partial(),
defaultTTL: z.string().superRefine((val, ctx) => {
const valMs = ms(val);
if (valMs < 60 * 1000)
ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be a greater than 1min" });
if (valMs > 24 * 60 * 60 * 1000)
ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than a day" });
}),
maxTTL: z
.string()
.optional()
.superRefine((val, ctx) => {
if (!val) return;
const valMs = ms(val);
if (valMs < 60 * 1000)
ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be a greater than 1min" });
if (valMs > 24 * 60 * 60 * 1000)
ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than a day" });
})
.nullable(),
newName: slugSchema().optional(),
metadata: z
.object({
key: z.string().trim().min(1),
value: z.string().trim().default("")
})
.array()
.optional(),
usernameTemplate: z.string().trim().nullable().optional()
});
type TForm = z.infer<typeof formSchema>;
type Props = {
onClose: () => void;
dynamicSecret: TDynamicSecret & { inputs: unknown };
secretPath: string;
projectSlug: string;
environment: string;
};
export const EditDynamicSecretCouchbaseForm = ({
onClose,
dynamicSecret,
secretPath,
environment,
projectSlug
}: Props) => {
const {
control,
formState: { isSubmitting },
handleSubmit,
setValue,
watch
} = useForm<TForm>({
resolver: zodResolver(formSchema),
defaultValues: {
defaultTTL: dynamicSecret.defaultTTL,
maxTTL: dynamicSecret.maxTTL || undefined,
newName: dynamicSecret.name,
metadata: dynamicSecret.metadata,
usernameTemplate: dynamicSecret.usernameTemplate,
inputs: {
...(dynamicSecret.inputs as any),
useAdvancedBuckets: Array.isArray((dynamicSecret.inputs as any)?.buckets)
}
}
});
const updateDynamicSecret = useUpdateDynamicSecret();
const isAdvancedMode = watch("inputs.useAdvancedBuckets");
const bucketsValue = watch("inputs.buckets");
const addBucket = () => {
const currentBuckets = Array.isArray(bucketsValue) ? bucketsValue : [];
setValue("inputs.buckets", [...currentBuckets, { name: "", scopes: [] }]);
};
const removeBucket = (index: number) => {
const currentBuckets = Array.isArray(bucketsValue) ? bucketsValue : [];
const newBuckets = currentBuckets.filter((_, i) => i !== index);
setValue("inputs.buckets", newBuckets);
};
const addScope = (bucketIndex: number) => {
const currentBuckets = Array.isArray(bucketsValue) ? [...bucketsValue] : [];
if (currentBuckets[bucketIndex]) {
const currentScopes = currentBuckets[bucketIndex].scopes || [];
currentBuckets[bucketIndex] = {
...currentBuckets[bucketIndex],
scopes: [...currentScopes, { name: "", collections: [] }]
};
setValue("inputs.buckets", currentBuckets);
}
};
const removeScope = (bucketIndex: number, scopeIndex: number) => {
const currentBuckets = Array.isArray(bucketsValue) ? [...bucketsValue] : [];
if (currentBuckets[bucketIndex]?.scopes) {
currentBuckets[bucketIndex].scopes = currentBuckets[bucketIndex].scopes.filter(
(_, i) => i !== scopeIndex
);
setValue("inputs.buckets", currentBuckets);
}
};
const addCollection = (bucketIndex: number, scopeIndex: number) => {
const currentBuckets = Array.isArray(bucketsValue) ? [...bucketsValue] : [];
if (currentBuckets[bucketIndex]?.scopes?.[scopeIndex]) {
const currentCollections = currentBuckets[bucketIndex].scopes[scopeIndex].collections || [];
currentBuckets[bucketIndex].scopes[scopeIndex].collections = [...currentCollections, ""];
setValue("inputs.buckets", currentBuckets);
}
};
const removeCollection = (bucketIndex: number, scopeIndex: number, collectionIndex: number) => {
const currentBuckets = Array.isArray(bucketsValue) ? [...bucketsValue] : [];
if (currentBuckets[bucketIndex]?.scopes?.[scopeIndex]?.collections) {
currentBuckets[bucketIndex].scopes[scopeIndex].collections = currentBuckets[
bucketIndex
].scopes[scopeIndex].collections.filter((_, i) => i !== collectionIndex);
setValue("inputs.buckets", currentBuckets);
}
};
const handleUpdateDynamicSecret = async ({
inputs,
newName,
defaultTTL,
maxTTL,
metadata,
usernameTemplate
}: TForm) => {
if (updateDynamicSecret.isPending) return;
const transformedInputs = inputs
? {
...inputs,
buckets: inputs.useAdvancedBuckets ? inputs.buckets : (inputs.buckets as string)
}
: inputs;
const finalInputs = transformedInputs
? (() => {
const { useAdvancedBuckets, ...rest } = transformedInputs;
return rest;
})()
: transformedInputs;
try {
await updateDynamicSecret.mutateAsync({
name: dynamicSecret.name,
path: secretPath,
projectSlug,
environmentSlug: environment,
data: {
defaultTTL,
maxTTL: maxTTL || undefined,
newName: newName === dynamicSecret.name ? undefined : newName,
metadata,
usernameTemplate:
!usernameTemplate || usernameTemplate === "{{randomUsername}}"
? undefined
: usernameTemplate,
inputs: finalInputs
}
});
createNotification({
type: "success",
text: "Successfully updated dynamic secret"
});
onClose();
} catch (err) {
createNotification({
type: "error",
text: `Failed to update dynamic secret: ${err}`
});
}
};
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">
<Controller
control={control}
name="defaultTTL"
defaultValue="1h"
render={({ field, fieldState: { error } }) => (
<FormControl
label={<TtlFormLabel label="Default TTL" />}
isError={Boolean(error?.message)}
errorText={error?.message}
>
<Input {...field} />
</FormControl>
)}
/>
</div>
<div className="w-32">
<Controller
control={control}
name="maxTTL"
defaultValue="24h"
render={({ field, fieldState: { error } }) => (
<FormControl
label={<TtlFormLabel label="Max TTL" />}
isError={Boolean(error?.message)}
errorText={error?.message}
>
<Input {...field} value={field.value || ""} />
</FormControl>
)}
/>
</div>
</div>
<MetadataForm control={control} />
<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 space-y-4">
<div className="flex items-center space-x-2">
<Controller
control={control}
name="inputs.url"
defaultValue="https://cloudapi.cloud.couchbase.com"
render={({ field, fieldState: { error } }) => (
<FormControl
label="URL"
className="w-full"
isError={Boolean(error?.message)}
errorText={error?.message}
>
<Input placeholder="https://cloudapi.cloud.couchbase.com" {...field} />
</FormControl>
)}
/>
</div>
<Controller
control={control}
name="inputs.orgId"
render={({ field, fieldState: { error } }) => (
<FormControl
label="Organization ID"
className="w-full"
isError={Boolean(error?.message)}
errorText={error?.message}
>
<Input {...field} />
</FormControl>
)}
/>
<div className="flex items-center space-x-2">
<Controller
control={control}
name="inputs.projectId"
render={({ field, fieldState: { error } }) => (
<FormControl
label="Project ID"
className="w-full"
isError={Boolean(error?.message)}
errorText={error?.message}
>
<Input {...field} />
</FormControl>
)}
/>
<Controller
control={control}
name="inputs.clusterId"
render={({ field, fieldState: { error } }) => (
<FormControl
label="Cluster ID"
className="w-full"
isError={Boolean(error?.message)}
errorText={error?.message}
>
<Input {...field} />
</FormControl>
)}
/>
</div>
<Controller
control={control}
name="inputs.roles"
defaultValue={["read"]}
render={({ field: { value, onChange }, fieldState: { error } }) => (
<FormControl
label="Roles"
className="w-full"
isError={Boolean(error?.message)}
errorText={error?.message}
helperText="Select one or more roles to assign to the user"
>
<FilterableSelect
isMulti
value={couchbaseRoles.filter((role) => value?.includes(role.value))}
onChange={(selectedRoles) => {
if (Array.isArray(selectedRoles)) {
onChange(selectedRoles.map((role: any) => role.value));
} else {
onChange([]);
}
}}
options={couchbaseRoles}
placeholder="Select roles..."
getOptionLabel={(option) => option.label}
getOptionValue={(option) => option.value}
/>
</FormControl>
)}
/>
<Controller
control={control}
name="inputs.useAdvancedBuckets"
render={({ field: { value, onChange } }) => (
<FormControl
label="Advanced Bucket Configuration"
helperText="Enable to configure specific buckets, scopes and collections. When disabled, '*' grants access to all buckets, scopes, and collections."
>
<Switch
id="advanced-buckets-switch"
isChecked={value}
onCheckedChange={(checked) => {
onChange(checked);
const bucketsController = watch("inputs.buckets");
if (checked && typeof bucketsController === "string") {
setValue("inputs.buckets", []);
} else if (!checked && Array.isArray(bucketsController)) {
setValue("inputs.buckets", "*");
}
}}
/>
</FormControl>
)}
/>
{!watch("inputs.useAdvancedBuckets") && (
<Controller
control={control}
name="inputs.buckets"
defaultValue="*"
render={({ field, fieldState: { error } }) => (
<FormControl
label="Bucket Access"
className="w-full"
isError={Boolean(error?.message)}
errorText={error?.message}
helperText="Specify bucket names separated by commas (e.g., 'bucket1,bucket2') or use '*' for all buckets, scopes, and collections"
>
<Input
{...field}
value={typeof field.value === "string" ? field.value : "*"}
onChange={(e) => field.onChange(e.target.value)}
placeholder="* (all buckets, scopes & collections) or bucket1,bucket2,bucket3"
/>
</FormControl>
)}
/>
)}
{isAdvancedMode && Array.isArray(bucketsValue) && (
<div className="space-y-4">
<div className="flex items-center justify-between">
<div>
<div className="text-sm font-medium text-mineshaft-200">
Advanced Bucket Configuration
</div>
<div className="text-sm text-mineshaft-400">
Configure specific buckets with their scopes and collections. Leave scopes
empty for access to all scopes in a bucket.
</div>
</div>
<Button
type="button"
variant="outline_bg"
size="sm"
onClick={addBucket}
leftIcon={<FontAwesomeIcon icon={faPlus} />}
>
Add Bucket
</Button>
</div>
<div className="space-y-4">
{Array.isArray(bucketsValue) &&
(bucketsValue as any[]).map((_, bucketIndex) => (
<div
key={`bucket-${bucketIndex + 1}`}
className="space-y-4 rounded border border-mineshaft-600 bg-mineshaft-800 p-4"
>
<div className="flex items-center justify-between">
<h4 className="text-sm font-medium text-mineshaft-200">
Bucket {bucketIndex + 1}
</h4>
<IconButton
type="button"
variant="plain"
ariaLabel="Remove bucket"
onClick={() => removeBucket(bucketIndex)}
>
<FontAwesomeIcon icon={faTrash} className="text-red-400" />
</IconButton>
</div>
<Controller
control={control}
name={`inputs.buckets.${bucketIndex}.name`}
render={({ field, fieldState: { error } }) => (
<FormControl
label="Bucket Name"
isError={Boolean(error)}
errorText={error?.message}
>
<Input {...field} placeholder="e.g., travel-sample" />
</FormControl>
)}
/>
<BucketScopesConfiguration
control={control}
bucketIndex={bucketIndex}
bucketsValue={bucketsValue}
setValue={setValue}
addScope={addScope}
removeScope={removeScope}
addCollection={addCollection}
removeCollection={removeCollection}
/>
</div>
))}
{(!Array.isArray(bucketsValue) || bucketsValue.length === 0) && (
<div className="rounded border border-dashed border-mineshaft-600 p-8 text-center">
<p className="mb-2 text-sm text-mineshaft-400">No buckets configured</p>
<Button
type="button"
variant="outline_bg"
size="sm"
onClick={addBucket}
leftIcon={<FontAwesomeIcon icon={faPlus} />}
>
Add First Bucket
</Button>
</div>
)}
</div>
</div>
)}
<Controller
name="inputs.auth.apiKey"
control={control}
render={({ field: { value, onChange }, fieldState: { error } }) => (
<FormControl
errorText={error?.message}
isError={Boolean(error?.message)}
className="w-full"
label="API Key"
>
<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}
valueAlwaysHidden
rows={1}
wrap="hard"
onChange={(e) => onChange(e.target.value)}
/>
</FormControl>
)}
/>
<Controller
control={control}
name="usernameTemplate"
render={({ field, fieldState: { error } }) => (
<FormControl
label="Username Template"
isError={Boolean(error?.message)}
errorText={error?.message}
>
<Input
{...field}
value={field.value || ""}
className="border-mineshaft-600 bg-mineshaft-900 text-sm"
placeholder="{{randomUsername}}"
/>
</FormControl>
)}
/>
<Accordion type="multiple" className="mb-2 mt-4 w-full bg-mineshaft-700">
<AccordionItem value="password-config">
<AccordionTrigger>
<div className="flex items-center space-x-2">
<span>Password Configuration (optional)</span>
<Tooltip content="Couchbase password requirements: minimum 8 characters, at least 1 uppercase, 1 lowercase, 1 digit, 1 special character. Cannot contain: < > ; . * & | �">
<div className="flex h-4 w-4 cursor-help items-center justify-center rounded-full bg-mineshaft-600 text-xs text-mineshaft-300">
?
</div>
</Tooltip>
</div>
</AccordionTrigger>
<AccordionContent>
<div className="mb-4 text-sm text-mineshaft-300">
Set constraints on the generated Couchbase user password (8-128 characters)
<br />
<span className="text-xs text-mineshaft-400">
Forbidden characters: &lt; &gt; ; . * &amp; | �
</span>
</div>
<div className="space-y-4">
<div>
<Controller
control={control}
name="inputs.passwordRequirements.length"
defaultValue={12}
render={({ field, fieldState: { error } }) => (
<FormControl
label="Password Length"
isError={Boolean(error)}
errorText={error?.message}
>
<Input
type="number"
min={8}
max={128}
{...field}
onChange={(e) => field.onChange(Number(e.target.value))}
/>
</FormControl>
)}
/>
</div>
<div className="space-y-2">
<h4 className="text-sm font-medium">Minimum Required Character Counts</h4>
<div className="text-sm text-gray-500">
{(() => {
const total = Object.values(
watch("inputs.passwordRequirements.required") || {}
).reduce((sum, count) => sum + Number(count || 0), 0);
const length = watch("inputs.passwordRequirements.length") || 0;
const isError = total > length;
return (
<span className={isError ? "text-red-500" : ""}>
Total required characters: {total}{" "}
{isError ? `(exceeds length of ${length})` : ""}
</span>
);
})()}
</div>
<div className="grid grid-cols-2 gap-4">
<Controller
control={control}
name="inputs.passwordRequirements.required.lowercase"
defaultValue={1}
render={({ field, fieldState: { error } }) => (
<FormControl
label="Lowercase Count"
isError={Boolean(error)}
errorText={error?.message}
helperText="Min lowercase letters (required: e1)"
>
<Input
type="number"
min={1}
{...field}
onChange={(e) => field.onChange(Number(e.target.value))}
/>
</FormControl>
)}
/>
<Controller
control={control}
name="inputs.passwordRequirements.required.uppercase"
defaultValue={1}
render={({ field, fieldState: { error } }) => (
<FormControl
label="Uppercase Count"
isError={Boolean(error)}
errorText={error?.message}
helperText="Min uppercase letters (required: e1)"
>
<Input
type="number"
min={1}
{...field}
onChange={(e) => field.onChange(Number(e.target.value))}
/>
</FormControl>
)}
/>
<Controller
control={control}
name="inputs.passwordRequirements.required.digits"
defaultValue={1}
render={({ field, fieldState: { error } }) => (
<FormControl
label="Digit Count"
isError={Boolean(error)}
errorText={error?.message}
helperText="Min digits (required: e1)"
>
<Input
type="number"
min={1}
{...field}
onChange={(e) => field.onChange(Number(e.target.value))}
/>
</FormControl>
)}
/>
<Controller
control={control}
name="inputs.passwordRequirements.required.symbols"
defaultValue={1}
render={({ field, fieldState: { error } }) => (
<FormControl
label="Symbol Count"
isError={Boolean(error)}
errorText={error?.message}
helperText="Min special characters (required: e1)"
>
<Input
type="number"
min={1}
{...field}
onChange={(e) => field.onChange(Number(e.target.value))}
/>
</FormControl>
)}
/>
</div>
</div>
<div className="space-y-2">
<h4 className="text-sm font-medium">Allowed Symbols</h4>
<Controller
control={control}
name="inputs.passwordRequirements.allowedSymbols"
defaultValue="!@#$%^()_+-=[]{}:,?/~`"
render={({ field, fieldState: { error } }) => (
<FormControl
label="Allowed Symbols"
isError={Boolean(error)}
errorText={error?.message}
helperText="Cannot contain: < > ; . * & | �"
>
<Input {...field} placeholder="!@#$%^()_+-=[]{}:,?/~`" />
</FormControl>
)}
/>
</div>
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
</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>
);
};
@@ -8,6 +8,7 @@ import { EditDynamicSecretAwsElastiCacheProviderForm } from "./EditDynamicSecret
import { EditDynamicSecretAwsIamForm } from "./EditDynamicSecretAwsIamForm";
import { EditDynamicSecretAzureEntraIdForm } from "./EditDynamicSecretAzureEntraIdForm";
import { EditDynamicSecretCassandraForm } from "./EditDynamicSecretCassandraForm";
import { EditDynamicSecretCouchbaseForm } from "./EditDynamicSecretCouchbaseForm";
import { EditDynamicSecretElasticSearchForm } from "./EditDynamicSecretElasticSearchForm";
import { EditDynamicSecretGcpIamForm } from "./EditDynamicSecretGcpIamForm";
import { EditDynamicSecretGithubForm } from "./EditDynamicSecretGithubForm";
@@ -384,6 +385,23 @@ export const EditDynamicSecretForm = ({
/>
</motion.div>
)}
{dynamicSecretDetails?.type === DynamicSecretProviders.Couchbase && (
<motion.div
key="couchbase-edit"
transition={{ duration: 0.1 }}
initial={{ opacity: 0, translateX: 30 }}
animate={{ opacity: 1, translateX: 0 }}
exit={{ opacity: 0, translateX: -30 }}
>
<EditDynamicSecretCouchbaseForm
onClose={onClose}
projectSlug={projectSlug}
secretPath={secretPath}
dynamicSecret={dynamicSecretDetails}
environment={environment}
/>
</motion.div>
)}
</AnimatePresence>
);
};
@@ -16,7 +16,7 @@ import { ProjectPermissionCan } from "@app/components/permissions";
import { DeleteActionModal, IconButton, Modal, ModalContent } from "@app/components/v2";
import { Tooltip } from "@app/components/v2/Tooltip/Tooltip";
import { ROUTE_PATHS } from "@app/const/routes";
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";
import { ProjectPermissionActions, ProjectPermissionSub, useSubscription } from "@app/context";
import { usePopUp } from "@app/hooks";
import { useDeleteFolder, useUpdateFolder } from "@app/hooks/api";
import { PendingAction, TSecretFolder } from "@app/hooks/api/secretFolders/types";
@@ -54,6 +54,7 @@ export const FolderListView = ({
from: ROUTE_PATHS.SecretManager.SecretDashboardPage.id,
select: (el) => el.secretPath
});
const { subscription } = useSubscription();
const { mutateAsync: updateFolder } = useUpdateFolder();
const { mutateAsync: deleteFolder } = useDeleteFolder();
@@ -319,6 +320,11 @@ export const FolderListView = ({
isOpen={popUp.deleteFolder.isOpen}
deleteKey={(popUp.deleteFolder?.data as TSecretFolder)?.name}
title="Do you want to delete this folder?"
subTitle={`This folder and all its contents will be removed. ${
subscription?.pitRecovery
? "You can reverse this action by rolling back to a previous commit."
: "Rolling back to a previous commit isn't available on your current plan. Upgrade to enable this feature."
}`}
onChange={(isOpen) => handlePopUpToggle("deleteFolder", isOpen)}
onDeleteApproved={handleFolderDelete}
/>
@@ -28,7 +28,7 @@ export const SecretSyncAuditLogsSection = ({ secretSync }: Props) => {
<h3 className="font-semibold text-mineshaft-100">Sync Logs</h3>
{subscription.auditLogs && (
<p className="text-xs text-bunker-300">
Displaying audit logs from the last {auditLogsRetentionDays} days
Displaying audit logs from the last {Math.min(auditLogsRetentionDays, 60)} days
</p>
)}
</div>
@@ -38,7 +38,9 @@ export const SecretSyncAuditLogsSection = ({ secretSync }: Props) => {
showFilters={false}
presets={{
eventMetadata: { syncId: secretSync.id },
startDate: new Date(new Date().setDate(new Date().getDate() - auditLogsRetentionDays)),
startDate: new Date(
new Date().setDate(new Date().getDate() - Math.min(auditLogsRetentionDays, 60))
),
eventType: INTEGRATION_EVENTS
}}
/>
@@ -1,23 +1,50 @@
import { GenericFieldLabel } from "@app/components/secret-syncs";
import { useRenderConnectionListServices } from "@app/hooks/api/appConnections/render";
import { TRenderSync } from "@app/hooks/api/secretSyncs/types/render-sync";
import {
useRenderConnectionListEnvironmentGroups,
useRenderConnectionListServices
} from "@app/hooks/api/appConnections/render";
import { RenderSyncScope, TRenderSync } from "@app/hooks/api/secretSyncs/types/render-sync";
type Props = {
secretSync: TRenderSync;
};
export const RenderSyncDestinationSection = ({ secretSync }: Props) => {
const isServiceScope = secretSync.destinationConfig.scope === RenderSyncScope.Service;
const { data: services = [], isPending } = useRenderConnectionListServices(
secretSync.connectionId
secretSync.connectionId,
{
enabled: isServiceScope
}
);
const {
destinationConfig: { serviceId }
} = secretSync;
if (isPending) {
return <GenericFieldLabel label="Service">Loading...</GenericFieldLabel>;
const { data: groups = [], isPending: isGroupsPending } =
useRenderConnectionListEnvironmentGroups(secretSync.connectionId, { enabled: !isServiceScope });
switch (secretSync.destinationConfig.scope) {
case RenderSyncScope.Service: {
const id = secretSync.destinationConfig.serviceId;
if (isPending) {
return <GenericFieldLabel label="Service">Loading...</GenericFieldLabel>;
}
const serviceName = services.find((service) => service.id === id)?.name;
return <GenericFieldLabel label="Service">{serviceName ?? id}</GenericFieldLabel>;
}
case RenderSyncScope.EnvironmentGroup: {
const id = secretSync.destinationConfig.environmentGroupId;
if (isGroupsPending) {
return <GenericFieldLabel label="Environment Group">Loading...</GenericFieldLabel>;
}
const envName = groups.find((g) => g.id === id)?.name;
return <GenericFieldLabel label="Environment Group">{envName ?? id}</GenericFieldLabel>;
}
default:
throw new Error("Unknown render sync destination scope");
}
const serviceName = services.find((service) => service.id === serviceId)?.name;
return <GenericFieldLabel label="Service">{serviceName ?? serviceId}</GenericFieldLabel>;
};
@@ -12,9 +12,15 @@ import {
Td,
Th,
THead,
Tooltip,
Tr
} from "@app/components/v2";
import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
import {
ProjectPermissionActions,
ProjectPermissionSub,
useSubscription,
useWorkspace
} from "@app/context";
import { useUpdateWsEnvironment } from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp";
@@ -35,6 +41,7 @@ type Props = {
export const EnvironmentTable = ({ handlePopUpOpen }: Props) => {
const { currentWorkspace } = useWorkspace();
const { subscription } = useSubscription();
const updateEnvironment = useUpdateWsEnvironment();
@@ -61,6 +68,16 @@ export const EnvironmentTable = ({ handlePopUpOpen }: Props) => {
}
};
const isMoreEnvironmentsAllowed =
subscription?.environmentLimit && currentWorkspace?.environments
? currentWorkspace.environments.length <= subscription.environmentLimit
: true;
const environmentsOverPlanLimit =
subscription?.environmentLimit && currentWorkspace?.environments
? Math.max(0, currentWorkspace.environments.length - subscription.environmentLimit)
: 0;
return (
<TableContainer>
<Table>
@@ -122,18 +139,26 @@ export const EnvironmentTable = ({ handlePopUpOpen }: Props) => {
a={ProjectPermissionSub.Environments}
>
{(isAllowed) => (
<IconButton
className="mr-3 py-2"
onClick={() => {
handlePopUpOpen("updateEnv", { name, slug, id });
}}
isDisabled={!isAllowed}
colorSchema="primary"
variant="plain"
ariaLabel="update"
<Tooltip
content={
isMoreEnvironmentsAllowed
? ""
: `You have exceeded the number of environments allowed by your plan. To edit an existing environment, either upgrade your plan or remove at least ${environmentsOverPlanLimit} environment${environmentsOverPlanLimit === 1 ? "" : "s"}.`
}
>
<FontAwesomeIcon icon={faPencil} />
</IconButton>
<IconButton
className="mr-3 py-2"
onClick={() => {
handlePopUpOpen("updateEnv", { name, slug, id });
}}
isDisabled={!isAllowed || !isMoreEnvironmentsAllowed}
colorSchema="primary"
variant="plain"
ariaLabel="update"
>
<FontAwesomeIcon icon={faPencil} />
</IconButton>
</Tooltip>
)}
</ProjectPermissionCan>
<ProjectPermissionCan