Skip to content

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

improvement: revamp access requests ui

Scott Wilson1676d21fa340
diff --git a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/SpecificPrivilegeSection.tsx b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/SpecificPrivilegeSection.tsx
deleted file mode 100644
index c3eb0c9aad..0000000000
--- a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/SpecificPrivilegeSection.tsx
+++ /dev/null
@@ -1,685 +0,0 @@
-/* eslint-disable jsx-a11y/label-has-associated-control */
-import { useMemo } from "react";
-import { Controller, useForm } from "react-hook-form";
-import { faEye, faTrashCan } from "@fortawesome/free-regular-svg-icons";
-import {
- faArrowRotateLeft,
- faCaretDown,
- faCheck,
- faClock,
- faLockOpen,
- faPencil,
- faPlus,
- faTrash
-} from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { zodResolver } from "@hookform/resolvers/zod";
-import { format, formatDistance } from "date-fns";
-import ms from "ms";
-import { twMerge } from "tailwind-merge";
-import { z } from "zod";
-
-import { TtlFormLabel } from "@app/components/features";
-import { createNotification } from "@app/components/notifications";
-import {
- Button,
- Checkbox,
- DeleteActionModal,
- FormControl,
- FormLabel,
- IconButton,
- Input,
- Popover,
- PopoverContent,
- PopoverTrigger,
- Select,
- SelectItem,
- Spinner,
- Tag,
- Tooltip
-} from "@app/components/v2";
-import { SecretPathInput } from "@app/components/v2/SecretPathInput";
-import {
- ProjectPermissionActions,
- ProjectPermissionMemberActions,
- ProjectPermissionSub,
- useProject,
- useProjectPermission
-} from "@app/context";
-import { removeTrailingSlash } from "@app/helpers/string";
-import { usePopUp } from "@app/hooks";
-import {
- TProjectUserPrivilege,
- useCreateAccessRequest,
- useDeleteProjectUserAdditionalPrivilege
-} from "@app/hooks/api";
-import { TAccessApprovalPolicy } from "@app/hooks/api/types";
-
-const secretPermissionSchema = z.object({
- secretPath: z.string().optional(),
- environmentSlug: z.string(),
- [ProjectPermissionActions.Edit]: z.boolean().optional(),
- [ProjectPermissionActions.Read]: z.boolean().optional(),
- [ProjectPermissionActions.Create]: z.boolean().optional(),
- [ProjectPermissionActions.Delete]: z.boolean().optional(),
- temporaryAccess: z.discriminatedUnion("isTemporary", [
- z.object({
- isTemporary: z.literal(true),
- temporaryRange: z.string().min(1),
- temporaryAccessStartTime: z.string().datetime(),
- temporaryAccessEndTime: z.string().datetime().nullable().optional()
- }),
- z.object({
- isTemporary: z.literal(false)
- })
- ]),
- note: z.string().optional()
-});
-type TSecretPermissionForm = z.infer<typeof secretPermissionSchema>;
-export const SpecificPrivilegeSecretForm = ({
- privilege,
- policies,
- onClose,
- selectedActions = [],
- secretPath: initialSecretPath
-}: {
- privilege?: TProjectUserPrivilege;
- policies?: TAccessApprovalPolicy[];
- selectedActions?: ProjectPermissionActions[];
- secretPath?: string;
- onClose?: () => void;
-}) => {
- const { currentProject } = useProject();
-
- const { popUp, handlePopUpOpen, handlePopUpToggle, handlePopUpClose } = usePopUp([
- "deletePrivilege",
- "requestAccess"
- ] as const);
- const { permission } = useProjectPermission();
- const isMemberEditDisabled =
- permission.cannot(ProjectPermissionMemberActions.Edit, ProjectPermissionSub.Member) &&
- Boolean(privilege);
-
- const deleteUserPrivilege = useDeleteProjectUserAdditionalPrivilege();
- const requestAccess = useCreateAccessRequest();
-
- const privilegeForm = useForm<TSecretPermissionForm>({
- resolver: zodResolver(secretPermissionSchema),
- values: {
- ...(privilege
- ? {
- environmentSlug: privilege.permissions?.[0]?.conditions?.environment,
- // secret path will be inside $glob operator
- secretPath: privilege.permissions?.[0]?.conditions?.secretPath?.$glob
- ? removeTrailingSlash(privilege.permissions?.[0]?.conditions?.secretPath?.$glob)
- : "",
- read: privilege.permissions?.some(({ action }) =>
- action.includes(ProjectPermissionActions.Read)
- ),
- edit: privilege.permissions?.some(({ action }) =>
- action.includes(ProjectPermissionActions.Edit)
- ),
- create: privilege.permissions?.some(({ action }) =>
- action.includes(ProjectPermissionActions.Create)
- ),
- delete: privilege.permissions?.some(({ action }) =>
- action.includes(ProjectPermissionActions.Delete)
- ),
- // zod will pick it
- temporaryAccess: privilege
- }
- : {
- environmentSlug: currentProject.environments?.[0]?.slug,
- secretPath: initialSecretPath,
- read: selectedActions.includes(ProjectPermissionActions.Read),
- edit: selectedActions.includes(ProjectPermissionActions.Edit),
- create: selectedActions.includes(ProjectPermissionActions.Create),
- delete: selectedActions.includes(ProjectPermissionActions.Delete),
- temporaryAccess: {
- isTemporary: false
- }
- })
- }
- });
-
- const temporaryAccessField = privilegeForm.watch("temporaryAccess");
- const selectedEnvironment = privilegeForm.watch("environmentSlug");
- const secretPath = privilegeForm.watch("secretPath");
-
- const readAccess = privilegeForm.watch("read");
- const createAccess = privilegeForm.watch("create");
- const editAccess = privilegeForm.watch("edit");
- const deleteAccess = privilegeForm.watch("delete");
-
- const accessSelected = readAccess || createAccess || editAccess || deleteAccess;
-
- const selectablePaths = useMemo(() => {
- if (!policies) return [];
- const environmentPolicies = policies.filter((policy) =>
- policy.environments.find((env) => env.slug === selectedEnvironment)
- );
-
- privilegeForm.setValue("secretPath", "", {
- shouldValidate: true
- });
-
- return [...environmentPolicies.map((policy) => policy.secretPath)];
- }, [policies, selectedEnvironment]);
-
- const isTemporary = temporaryAccessField?.isTemporary;
- const isExpired =
- temporaryAccessField.isTemporary &&
- new Date() > new Date(temporaryAccessField.temporaryAccessEndTime || "");
-
- const handleDeletePrivilege = async () => {
- if (!privilege) {
- createNotification({
- type: "error",
- text: "No privilege to delete found.",
- title: "Error"
- });
- return;
- }
-
- if (deleteUserPrivilege.isPending) return;
- await deleteUserPrivilege.mutateAsync({
- privilegeId: privilege.id,
- projectMembershipId: privilege.projectMembershipId
- });
- createNotification({
- type: "success",
- text: "Successfully deleted privilege"
- });
- };
-
- // This is used for requesting access additional privileges, not directly creating a privilege!
- const handleRequestAccess = async (data: TSecretPermissionForm) => {
- if (!policies) return;
- if (!currentProject) {
- createNotification({
- type: "error",
- text: "No workspace found.",
- title: "Error"
- });
- return;
- }
-
- if (!data.secretPath) {
- createNotification({
- type: "error",
- text: "Please select a secret path...",
- title: "Error"
- });
- return;
- }
-
- const policy = policies.find(
- (p) =>
- p.environments.find((e) => e.slug === selectedEnvironment) && p.secretPath === secretPath
- );
-
- if (
- policy?.maxTimePeriod &&
- (!data.temporaryAccess.isTemporary ||
- ms(data.temporaryAccess.temporaryRange) > ms(policy.maxTimePeriod))
- ) {
- createNotification({
- type: "error",
- text: `Requested access time range is limited to ${policy.maxTimePeriod} by policy`,
- title: "Error"
- });
- return;
- }
-
- const actions = [
- { action: ProjectPermissionActions.Read, allowed: data.read },
- { action: ProjectPermissionActions.Create, allowed: data.create },
- { action: ProjectPermissionActions.Delete, allowed: data.delete },
- { action: ProjectPermissionActions.Edit, allowed: data.edit }
- ];
- const conditions: Record<string, any> = { environment: data.environmentSlug };
- if (data.secretPath) {
- conditions.secretPath = { $glob: data.secretPath };
- }
- await requestAccess.mutateAsync({
- ...data,
- ...(data.temporaryAccess.isTemporary && {
- temporaryRange: data.temporaryAccess.temporaryRange
- }),
- projectSlug: currentProject.slug,
- isTemporary: data.temporaryAccess.isTemporary,
- permissions: actions
- .filter(({ allowed }) => allowed)
- .map(({ action }) => ({
- action,
- subject: [ProjectPermissionSub.Secrets],
- conditions
- })),
- note: data.note
- });
-
- createNotification({
- type: "success",
- text: "Successfully requested access"
- });
- privilegeForm.reset();
- if (onClose) onClose();
- };
-
- const handleSubmit = async (data: TSecretPermissionForm) => {
- handleRequestAccess(data);
- };
-
- const getAccessLabel = (exactTime = false) => {
- if (isExpired) return "Access expired";
- if (!temporaryAccessField?.isTemporary) return "Permanent";
-
- if (exactTime && !policies) {
- return `Until ${format(
- new Date(temporaryAccessField.temporaryAccessEndTime || ""),
- "yyyy-MM-dd HH:mm:ss"
- )}`;
- }
- return formatDistance(new Date(temporaryAccessField.temporaryAccessEndTime || ""), new Date());
- };
-
- return (
- <div className="w-full">
- <form onSubmit={privilegeForm.handleSubmit(handleSubmit)}>
- <div className={twMerge("flex items-start", !privilege && "flex-col")}>
- <Controller
- control={privilegeForm.control}
- name="environmentSlug"
- render={({ field: { onChange, ...field } }) => (
- <FormControl label="Environment" className="w-full">
- <Select
- {...field}
- isDisabled={isMemberEditDisabled}
- className="w-full bg-mineshaft-900 hover:bg-mineshaft-800"
- onValueChange={(e) => onChange(e)}
- position="popper"
- dropdownContainerClassName="max-w-none"
- >
- {currentProject?.environments?.map(({ slug, id, name }) => (
- <SelectItem value={slug} key={id}>
- {name}
- </SelectItem>
- ))}
- </Select>
- </FormControl>
- )}
- />
- <Controller
- control={privilegeForm.control}
- name="secretPath"
- render={({ field }) => {
- if (policies) {
- return (
- <Tooltip
- isDisabled={!!selectablePaths.length}
- content="The selected environment doesn't have any policies."
- >
- <div className="w-full">
- <FormControl label="Secret Path">
- <Select
- {...field}
- isDisabled={isMemberEditDisabled || !selectablePaths.length}
- className="w-full hover:bg-mineshaft-800"
- placeholder="Select a secret path"
- onValueChange={(e) => field.onChange(e)}
- position="popper"
- dropdownContainerClassName="max-w-none"
- >
- {selectablePaths.map((path) => (
- <SelectItem value={path} key={path}>
- {path}
- </SelectItem>
- ))}
- </Select>
- </FormControl>
- </div>
- </Tooltip>
- );
- }
- return (
- <FormControl label="Secret Path">
- <SecretPathInput
- {...field}
- isDisabled={isMemberEditDisabled}
- containerClassName="w-48"
- environment={selectedEnvironment}
- />
- </FormControl>
- );
- }}
- />
- <FormControl label="Permissions" className="w-full">
- <div className="flex w-full flex-col justify-between">
- <div className="flex w-full flex-row gap-2">
- <Controller
- control={privilegeForm.control}
- name="read"
- render={({ field }) => (
- <label
- className={`group my-1 flex w-full cursor-pointer flex-row items-center justify-start gap-2 rounded-md border border-mineshaft-600 bg-mineshaft-900 p-3 duration-100 hover:border-primary/30 hover:bg-primary/10 ${field.value ? "border-primary/50 bg-primary/10 hover:border-primary/50" : ""}`}
- htmlFor="secret-read"
- >
- <Checkbox
- isDisabled={isMemberEditDisabled}
- id="secret-read"
- className={`mx-2 h-5 w-5 ${field.value ? "hover:bg-primary/40" : ""}`}
- isChecked={field.value}
- onCheckedChange={(isChecked) => field.onChange(isChecked)}
- />
- <div className="pointer-events-none ml-1 flex flex-col text-mineshaft-300 select-none">
- <div className="flex flex-row items-center gap-1">
- <FontAwesomeIcon
- icon={faEye}
- className={`text-sm ${field.value ? "text-primary-200" : ""}`}
- />
- <FormLabel
- label="View"
- className={`my-0 ml-0.5 text-mineshaft-300 ${field.value ? "text-primary-200" : ""}`}
- />
- </div>
- <p className="text-xs text-mineshaft-400">Read secret values</p>
- </div>
- </label>
- )}
- />
- <Controller
- control={privilegeForm.control}
- name="create"
- render={({ field }) => (
- <label
- className={`group my-1 flex w-full cursor-pointer flex-row items-center justify-start gap-2 rounded-md border border-mineshaft-600 bg-mineshaft-900 p-3 duration-100 hover:border-primary/30 hover:bg-primary/10 ${field.value ? "border-primary/50 bg-primary/10 hover:border-primary/50" : ""}`}
- htmlFor="secret-change"
- >
- <Checkbox
- isDisabled={isMemberEditDisabled}
- id="secret-change"
- className={`mx-2 h-5 w-5 ${field.value ? "hover:bg-primary/40" : ""}`}
- isChecked={field.value}
- onCheckedChange={(isChecked) => field.onChange(isChecked)}
- />
- <div className="pointer-events-none ml-1 flex flex-col text-mineshaft-300 select-none">
- <div className="flex flex-row items-center gap-1">
- <FontAwesomeIcon
- icon={faPlus}
- className={`text-sm ${field.value ? "text-primary-200" : ""}`}
- />
- <FormLabel
- label="Create"
- className={`my-0 ml-0.5 text-mineshaft-300 ${field.value ? "text-primary-200" : ""}`}
- />
- </div>
- <p className="text-xs text-mineshaft-400">Create new secrets</p>
- </div>
- </label>
- )}
- />
- </div>
- <div className="flex w-full flex-row gap-2">
- <Controller
- control={privilegeForm.control}
- name="edit"
- render={({ field }) => (
- <label
- className={`group my-1 flex w-full cursor-pointer flex-row items-center justify-start gap-2 rounded-md border border-mineshaft-600 bg-mineshaft-900 p-3 duration-100 hover:border-primary/30 hover:bg-primary/10 ${field.value ? "border-primary/50 bg-primary/10 hover:border-primary/50" : ""}`}
- htmlFor="secret-modify"
- >
- <Checkbox
- isDisabled={isMemberEditDisabled}
- id="secret-modify"
- className={`mx-2 h-5 w-5 ${field.value ? "hover:bg-primary/40" : ""}`}
- isChecked={field.value}
- onCheckedChange={(isChecked) => field.onChange(isChecked)}
- />
- <div className="pointer-events-none ml-1 flex flex-col text-mineshaft-300 select-none">
- <div className="flex flex-row items-center gap-1">
- <FontAwesomeIcon
- icon={faPencil}
- className={`text-sm ${field.value ? "text-primary-200" : ""}`}
- />
- <FormLabel
- label="Modify"
- className={`my-0 ml-0.5 text-mineshaft-300 ${field.value ? "text-primary-200" : ""}`}
- />
- </div>
- <p className="text-xs text-mineshaft-400">Update existing secrets</p>
- </div>
- </label>
- )}
- />
- <Controller
- control={privilegeForm.control}
- name="delete"
- render={({ field }) => (
- <label
- className={`group my-1 flex w-full cursor-pointer flex-row items-center justify-start gap-2 rounded-md border border-mineshaft-600 bg-mineshaft-900 p-3 duration-100 hover:border-primary/30 hover:bg-primary/10 ${field.value ? "border-primary/50 bg-primary/10 hover:border-primary/50" : ""}`}
- htmlFor="secret-delete"
- >
- <Checkbox
- isDisabled={isMemberEditDisabled}
- id="secret-delete"
- className={`mx-2 h-5 w-5 ${field.value ? "hover:bg-primary/40" : ""}`}
- isChecked={field.value}
- onCheckedChange={(isChecked) => field.onChange(isChecked)}
- />
- <div className="pointer-events-none ml-1 flex flex-col text-mineshaft-300 select-none">
- <div className="flex flex-row items-center gap-1">
- <FontAwesomeIcon
- icon={faTrashCan}
- className={`text-sm ${field.value ? "text-primary-200" : ""}`}
- />
- <FormLabel
- label="Delete"
- className={`my-0 ml-0.5 text-mineshaft-300 ${field.value ? "text-primary-200" : ""}`}
- />
- </div>
- <p className="text-xs text-mineshaft-400">Delete existing secrets</p>
- </div>
- </label>
- )}
- />
- </div>
- </div>
- </FormControl>
- <FormControl label="Time Period" className="w-full">
- <div className="mt-1 flex w-full items-center space-x-2">
- <Popover>
- <PopoverTrigger disabled={isMemberEditDisabled}>
- <div className="w-full">
- <Tooltip content={getAccessLabel(true)}>
- <Button
- variant="outline_bg"
- leftIcon={isTemporary ? <FontAwesomeIcon icon={faClock} /> : undefined}
- rightIcon={<FontAwesomeIcon icon={faCaretDown} className="ml-4" />}
- isDisabled={isMemberEditDisabled}
- className={twMerge(
- "w-full border-mineshaft-600 bg-mineshaft-900 py-2.5 text-sm text-mineshaft-300 capitalize hover:border-mineshaft-600 hover:bg-mineshaft-800",
- isExpired && "text-red-600"
- )}
- >
- {getAccessLabel(false)}
- </Button>
- </Tooltip>
- </div>
- </PopoverTrigger>
- <PopoverContent
- arrowClassName="fill-mineshaft-600"
- side="right"
- sideOffset={12}
- hideCloseBtn
- className="border border-mineshaft-600 bg-mineshaft-800 pt-4"
- >
- <div className="flex flex-col space-y-4">
- <div className="text-sm text-mineshaft-300">Configure timed access</div>
- {isExpired && <Tag colorSchema="red">Expired</Tag>}
- <Controller
- control={privilegeForm.control}
- defaultValue="1h"
- name="temporaryAccess.temporaryRange"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label={<TtlFormLabel label="Validity" />}
- isError={Boolean(error?.message)}
- errorText={error?.message}
- >
- <Input {...field} />
- </FormControl>
- )}
- />
- <div className="flex items-center space-x-2">
- <Button
- size="xs"
- onClick={() => {
- const temporaryRange = privilegeForm.getValues(
- "temporaryAccess.temporaryRange"
- );
- if (!temporaryRange) {
- privilegeForm.setError(
- "temporaryAccess.temporaryRange",
- { type: "required", message: "Required" },
- { shouldFocus: true }
- );
- return;
- }
- privilegeForm.clearErrors("temporaryAccess.temporaryRange");
- privilegeForm.setValue(
- "temporaryAccess",
- {
- isTemporary: true,
- temporaryAccessStartTime: new Date().toISOString(),
- temporaryRange,
- temporaryAccessEndTime: new Date(
- new Date().getTime() + ms(temporaryRange)
- ).toISOString()
- },
- { shouldDirty: true }
- );
- }}
- >
- {temporaryAccessField.isTemporary && !policies ? "Restart" : "Grant"}
- </Button>
-
- {temporaryAccessField.isTemporary && (
- <Button
- size="xs"
- variant="outline_bg"
- colorSchema="danger"
- onClick={() => {
- privilegeForm.setValue("temporaryAccess", {
- isTemporary: false
- });
- }}
- >
- Cancel
- </Button>
- )}
- </div>
- </div>
- </PopoverContent>
- </Popover>
- {/* eslint-disable-next-line no-nested-ternary */}
- {privilegeForm.formState.isDirty && privilege ? (
- <>
- <Tooltip content="Cancel" className="mr-4">
- <IconButton
- variant="outline_bg"
- className="border border-mineshaft-500 bg-mineshaft-600 py-2.5 hover:border-red/70 hover:bg-red/20"
- ariaLabel="delete-privilege"
- isDisabled={privilegeForm.formState.isSubmitting}
- onClick={() => privilegeForm.reset()}
- >
- <FontAwesomeIcon icon={faArrowRotateLeft} className="py-0.5" />
- </IconButton>
- </Tooltip>
- <Tooltip
- content={isMemberEditDisabled ? "Access restricted" : "Save"}
- className="mr-4"
- >
- <IconButton
- isDisabled={isMemberEditDisabled}
- className="border-none py-3"
- ariaLabel="save-privilege"
- type="submit"
- >
- {privilegeForm.formState.isSubmitting ? (
- <Spinner size="xs" className="m-0 h-3 w-3 text-slate-500" />
- ) : (
- <FontAwesomeIcon icon={faCheck} className="px-0.5" />
- )}
- </IconButton>
- </Tooltip>
- </>
- ) : // eslint-disable-next-line no-nested-ternary
- privilege ? (
- <Tooltip
- content={isMemberEditDisabled ? "Access restricted" : "Delete"}
- className="mr-4"
- >
- <IconButton
- isDisabled={isMemberEditDisabled}
- variant="outline_bg"
- className="border border-mineshaft-500 bg-mineshaft-600 py-3 hover:border-red/70 hover:bg-red/20"
- ariaLabel="delete-privilege"
- onClick={() => handlePopUpOpen("deletePrivilege")}
- >
- <FontAwesomeIcon icon={faTrash} />
- </IconButton>
- </Tooltip>
- ) : (
- <div />
- )}
- </div>
- </FormControl>
- </div>
- <div className="mb-4 flex w-full">
- <Controller
- control={privilegeForm.control}
- name="note"
- render={({ field }) => (
- <div className="w-full">
- <FormLabel label="Note" className="mb-2" />
- <Input
- {...field}
- isDisabled={isMemberEditDisabled}
- maxLength={255}
- placeholder="Add the reason for this access request..."
- className="text-mineshaft-300"
- />
- </div>
- )}
- />
- </div>
- {!!policies && (
- <Button
- type="submit"
- variant="outline_bg"
- isLoading={privilegeForm.formState.isSubmitting || requestAccess.isPending}
- isDisabled={
- isMemberEditDisabled ||
- !policies.length ||
- !privilegeForm.formState.isValid ||
- !secretPath ||
- !accessSelected
- }
- className="mt-4"
- leftIcon={<FontAwesomeIcon icon={faLockOpen} />}
- >
- Request Access
- </Button>
- )}
- </form>
- <DeleteActionModal
- isOpen={popUp.deletePrivilege.isOpen}
- title="Remove user additional privilege"
- onChange={(isOpen) => handlePopUpToggle("deletePrivilege", isOpen)}
- deleteKey="delete"
- onClose={() => handlePopUpClose("deletePrivilege")}
- onDeleteApproved={handleDeletePrivilege}
- />
- </div>
- );
-};
diff --git a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/AccessApprovalRequest.tsx b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/AccessApprovalRequest.tsx
index eeb320ca34..85d1c1fae0 100644
--- a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/AccessApprovalRequest.tsx
+++ b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/AccessApprovalRequest.tsx
@@ -1,43 +1,74 @@
/* eslint-disable no-nested-ternary */
/* eslint-disable react/jsx-no-useless-fragment */
import { useCallback, useMemo, useState } from "react";
-import {
- faCheck,
- faCheckCircle,
- faChevronDown,
- faLock,
- faMagnifyingGlass,
- faPlus,
- faSearch,
- faUser
-} from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { format, formatDistance } from "date-fns";
import {
BanIcon,
CheckIcon,
+ ChevronsUpDownIcon,
ClipboardCheckIcon,
+ EllipsisIcon,
+ EyeIcon,
+ HourglassIcon,
LucideIcon,
+ PlusIcon,
+ SearchIcon,
ShieldBanIcon,
TimerIcon
} from "lucide-react";
-import { twMerge } from "tailwind-merge";
+import ms from "ms";
import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";
import {
+ Badge,
Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+ CommandSeparator,
+ DocumentationLinkBadge,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
- DropdownMenuLabel,
DropdownMenuTrigger,
- EmptyState,
- Input,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ IconButton,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ Label,
Pagination,
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+ Skeleton,
Switch,
- Tooltip
-} from "@app/components/v2";
-import { Badge, DocumentationLinkBadge } from "@app/components/v3";
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+ Tabs,
+ TabsList,
+ TabsTrigger,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
+import { cn } from "@app/components/v3/utils";
import {
ProjectPermissionMemberActions,
ProjectPermissionSub,
@@ -67,22 +98,93 @@ import { ApprovalStatus, TWorkspaceUser } from "@app/hooks/api/types";
import { RequestAccessModal } from "./components/RequestAccessModal";
import { ReviewAccessRequestModal } from "./components/ReviewAccessModal";
-const generateRequestText = (request: TAccessApprovalRequest) => {
- const { isTemporary } = request;
+type FilterMenuProps = {
+ className?: string;
+ searchPlaceholder: string;
+ allLabel: string;
+ options: { value: string; label: string }[];
+ value?: string;
+ onChange: (value?: string) => void;
+};
+
+const FilterMenu = ({
+ className,
+ searchPlaceholder,
+ allLabel,
+ options,
+ value,
+ onChange
+}: FilterMenuProps) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const [inputValue, setInputValue] = useState("");
+
+ const selectedOption = options.find((option) => option.value === value);
return (
- <div className="flex items-center justify-between text-sm">
- <div>
- Requested {isTemporary ? "temporary" : "permanent"} access to{" "}
- <code className="mx-1 rounded-sm bg-mineshaft-600 px-1.5 py-0.5 font-mono text-[13px] text-mineshaft-200">
- {request.policy.secretPath}
- </code>{" "}
- in{" "}
- <code className="mx-1 rounded-sm bg-mineshaft-600 px-1.5 py-0.5 font-mono text-[13px] text-mineshaft-200">
- {request.environmentName}
- </code>
- </div>
- </div>
+ <Popover open={isOpen} onOpenChange={setIsOpen}>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ role="combobox"
+ aria-expanded={isOpen}
+ className={cn("justify-between", className)}
+ >
+ <span className="truncate">{selectedOption ? selectedOption.label : allLabel}</span>
+ <ChevronsUpDownIcon className="ml-2 size-4 shrink-0 opacity-50" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="end" className="w-[220px] p-0">
+ <Command>
+ <CommandInput
+ value={inputValue}
+ onValueChange={setInputValue}
+ placeholder={searchPlaceholder}
+ />
+ <CommandList>
+ <CommandEmpty>No results found.</CommandEmpty>
+ {!inputValue && (
+ <>
+ <CommandGroup>
+ <CommandItem
+ forceMount
+ keywords={[]}
+ onSelect={() => {
+ onChange(undefined);
+ setIsOpen(false);
+ }}
+ >
+ <CheckIcon className={cn("size-4", !value ? "opacity-100" : "opacity-0")} />
+ {allLabel}
+ </CommandItem>
+ </CommandGroup>
+ <CommandSeparator />
+ </>
+ )}
+ <CommandGroup>
+ {options.map((option) => (
+ <CommandItem
+ key={option.value}
+ value={option.value}
+ keywords={[option.label]}
+ onSelect={() => {
+ onChange(value === option.value ? undefined : option.value);
+ setIsOpen(false);
+ }}
+ >
+ <CheckIcon
+ className={cn(
+ "size-4 shrink-0",
+ value === option.value ? "opacity-100" : "opacity-0"
+ )}
+ />
+ <span className="truncate">{option.label}</span>
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
);
};
@@ -120,6 +222,10 @@ export const AccessApprovalRequest = ({
{}
);
+ const environmentNamesBySlug = (currentProject?.environments ?? []).reduce<
+ Record<string, string>
+ >((prev, curr) => ({ ...prev, [curr.slug]: curr.name }), {});
+
const [statusFilter, setStatusFilter] = useState<"open" | "close">("open");
const [requestedByFilter, setRequestedByFilter] = useState<string | undefined>(undefined);
const [envFilter, setEnvFilter] = useState<string | undefined>(undefined);
@@ -346,265 +452,328 @@ export const AccessApprovalRequest = ({
return (
<>
- <div className="w-full rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
- <div className="mb-4 flex flex-wrap items-center justify-between gap-2">
- <div>
- <div className="flex items-center gap-x-2">
- <p className="text-xl font-medium text-mineshaft-100">Access Requests</p>
- <DocumentationLinkBadge href="https://infisical.com/docs/documentation/platform/access-controls/access-requests" />
- </div>
- <p className="text-sm text-bunker-300">
- Request and review access to secrets in sensitive environments and folders
- </p>
- </div>
- <Tooltip
- content="To submit Access Requests, your project needs to create Access Request policies first."
- isDisabled={policiesLoading || !!policies?.length}
- >
- <Button
- onClick={() => {
- if (subscription && !subscription?.secretApproval) {
- handlePopUpOpen("upgradePlan", {
- text: "Access requests feature can be unlocked if you upgrade to Infisical Pro plan."
- });
- return;
- }
- handlePopUpOpen("requestAccess");
- }}
- colorSchema="secondary"
- leftIcon={<FontAwesomeIcon icon={faPlus} />}
- isDisabled={policiesLoading || !policies?.length}
- >
- Request Access
- </Button>
- </Tooltip>
- </div>
- <Input
- value={search}
- onChange={(e) => setSearch(e.target.value)}
- leftIcon={<FontAwesomeIcon icon={faMagnifyingGlass} />}
- placeholder="Search approval requests by requesting user or environment..."
- className="flex-1"
- containerClassName="mb-4"
- />
- <div className="flex items-center space-x-8 rounded-t-md border-x border-t border-mineshaft-600 bg-mineshaft-800 px-8 py-3 text-sm">
- <div
- role="button"
- tabIndex={0}
- onClick={() => setStatusFilter("open")}
- onKeyDown={(evt) => {
- if (evt.key === "Enter") setStatusFilter("open");
- }}
- className={twMerge(
- "cursor-pointer font-medium",
- statusFilter !== "open" && "text-gray-500 duration-100 hover:text-gray-400"
- )}
- >
- <FontAwesomeIcon icon={faLock} className="mr-2" />
- {requestCount?.pendingCount ?? 0} Pending
- </div>
- <div
- className={twMerge(
- "cursor-pointer font-medium",
- statusFilter !== "close" && "text-gray-500 duration-100 hover:text-gray-400"
- )}
- role="button"
- tabIndex={0}
- onClick={() => setStatusFilter("close")}
- onKeyDown={(evt) => {
- if (evt.key === "Enter") setStatusFilter("close");
- }}
- >
- <FontAwesomeIcon icon={faCheck} className="mr-2" />
- {requestCount?.finalizedCount ?? 0} Closed
- </div>
- <div className="flex grow justify-end space-x-8">
- {statusFilter === "close" && (
- <Switch
- id="show-expired-toggle"
- isChecked={showExpired}
- onCheckedChange={setShowExpired}
- containerClassName="cursor-pointer text-sm"
- className="cursor-pointer"
- >
- Show Expired
- </Switch>
- )}
- <DropdownMenu>
- <DropdownMenuTrigger>
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ Access Requests
+ <DocumentationLinkBadge href="https://infisical.com/docs/documentation/platform/access-controls/access-requests" />
+ </CardTitle>
+ <CardDescription>
+ Request and review access to secrets in sensitive environments and folders
+ </CardDescription>
+ <CardAction>
+ {(() => {
+ const requestAccessButton = (
<Button
- variant="plain"
- colorSchema="secondary"
- className={envFilter ? "text-white" : "text-bunker-300"}
- rightIcon={<FontAwesomeIcon icon={faChevronDown} size="sm" className="ml-2" />}
+ onClick={() => {
+ if (subscription && !subscription?.secretApproval) {
+ handlePopUpOpen("upgradePlan", {
+ text: "Access requests feature can be unlocked if you upgrade to Infisical Pro plan."
+ });
+ return;
+ }
+ handlePopUpOpen("requestAccess");
+ }}
+ variant="project"
+ isDisabled={policiesLoading || !policies?.length}
>
- Environments
+ <PlusIcon />
+ Request Access
</Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- align="end"
- sideOffset={1}
- className="max-h-80 thin-scrollbar overflow-y-auto"
- >
- <DropdownMenuLabel className="sticky top-0 bg-mineshaft-900">
- Select an Environment
- </DropdownMenuLabel>
- {currentProject?.environments.map(({ slug, name }) => (
- <DropdownMenuItem
- onClick={() => setEnvFilter((state) => (state === slug ? undefined : slug))}
- key={`request-filter-${slug}`}
- icon={envFilter === slug && <FontAwesomeIcon icon={faCheckCircle} />}
- iconPos="right"
- >
- {name}
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- {!!permission.can(ProjectPermissionMemberActions.Read, ProjectPermissionSub.Member) && (
- <DropdownMenu>
- <DropdownMenuTrigger>
- <Button
- variant="plain"
- colorSchema="secondary"
- className={requestedByFilter ? "text-white" : "text-bunker-300"}
- rightIcon={<FontAwesomeIcon icon={faChevronDown} size="sm" className="ml-2" />}
+ );
+
+ if (!policiesLoading && !policies?.length) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ {/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex -- focusable wrapper required so the tooltip surfaces on keyboard focus despite the inner button being disabled */}
+ <span tabIndex={0}>{requestAccessButton}</span>
+ </TooltipTrigger>
+ <TooltipContent>
+ To submit Access Requests, your project needs to create Access Request
+ policies first.
+ </TooltipContent>
+ </Tooltip>
+ );
+ }
+
+ return requestAccessButton;
+ })()}
+ </CardAction>
+ </CardHeader>
+ <CardContent className="flex flex-col">
+ <div className="mb-4 flex flex-wrap items-center gap-2 2xl:flex-nowrap">
+ <Tabs
+ value={statusFilter}
+ onValueChange={(value) => setStatusFilter(value as "open" | "close")}
+ >
+ <TabsList variant="filled">
+ <TabsTrigger value="open">
+ <HourglassIcon className="mr-1.5 size-3.5" />
+ {requestCount?.pendingCount ?? 0} Pending
+ </TabsTrigger>
+ <TabsTrigger value="close">
+ <CheckIcon className="mr-1.5 size-3.5" />
+ {requestCount?.finalizedCount ?? 0} Closed
+ </TabsTrigger>
+ </TabsList>
+ </Tabs>
+ <div className="flex flex-wrap items-center gap-2 2xl:mr-auto 2xl:flex-nowrap">
+ <InputGroup className="xl:w-[26rem]">
+ <InputGroupAddon>
+ <SearchIcon />
+ </InputGroupAddon>
+ <InputGroupInput
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Search by requesting user or environment..."
+ />
+ </InputGroup>
+ {statusFilter === "close" && (
+ <div className="flex items-center gap-2">
+ <Switch
+ id="show-expired-toggle"
+ variant="project"
+ size="sm"
+ checked={showExpired}
+ onCheckedChange={setShowExpired}
+ />
+ <Label
+ htmlFor="show-expired-toggle"
+ className="cursor-pointer text-sm font-normal"
>
- Requested By
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- align="end"
- sideOffset={1}
- className="max-h-80 thin-scrollbar overflow-y-auto"
- >
- <DropdownMenuLabel className="sticky top-0 bg-mineshaft-900">
- Select Requesting User
- </DropdownMenuLabel>
- {members?.map(({ user: membershipUser, id }) => (
- <DropdownMenuItem
- onClick={() =>
- setRequestedByFilter((state) =>
- state === membershipUser.id ? undefined : membershipUser.id
- )
- }
- key={`request-filter-member-${id}`}
- icon={
- requestedByFilter === membershipUser.id && (
- <FontAwesomeIcon icon={faCheckCircle} />
- )
- }
- iconPos="right"
- >
- {membershipUser.username}
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
+ Show Expired
+ </Label>
+ </div>
+ )}
+ </div>
+ <FilterMenu
+ className="w-[200px]"
+ searchPlaceholder="Filter environments"
+ allLabel="All Environments"
+ value={envFilter}
+ onChange={setEnvFilter}
+ options={(currentProject?.environments ?? []).map((env) => ({
+ value: env.slug,
+ label: env.name
+ }))}
+ />
+ {permission.can(ProjectPermissionMemberActions.Read, ProjectPermissionSub.Member) && (
+ <FilterMenu
+ className="w-[220px]"
+ searchPlaceholder="Filter users"
+ allLabel="All Users"
+ value={requestedByFilter}
+ onChange={setRequestedByFilter}
+ options={(members ?? []).map(({ user: membershipUser }) => ({
+ value: membershipUser.id,
+ label: membershipUser.username
+ }))}
+ />
)}
</div>
- </div>
- <div className="flex flex-col rounded-b-md border-x border-t border-b border-mineshaft-600 bg-mineshaft-800">
- {filteredRequests?.length === 0 && !isFiltered && (
- <div className="py-12">
- <EmptyState
- title={`No ${statusFilter === "open" ? "Pending" : "Closed"} Access Requests`}
- />
- </div>
+ {!areRequestsPending && filteredRequests?.length === 0 && !isFiltered && (
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>
+ No {statusFilter === "open" ? "Pending" : "Closed"} Access Requests
+ </EmptyTitle>
+ <EmptyDescription>
+ {statusFilter === "open"
+ ? "Access requests awaiting review will appear here."
+ : "Approved, rejected, revoked, or expired access requests will appear here."}
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
)}
{Boolean(!filteredRequests?.length && isFiltered && !areRequestsPending) && (
- <div className="py-12">
- <EmptyState title="No Requests Match Filters" icon={faSearch} />
- </div>
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>No Requests Match Filters</EmptyTitle>
+ <EmptyDescription>
+ No access requests match your current search or filters.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
)}
- {!!filteredRequests?.length &&
- filteredRequests?.slice(offset, perPage * page).map((request) => {
- const details = generateRequestDetails(request);
-
- const StatusIcon = details.displayData.icon;
-
- return (
- <div
- key={request.id}
- className="flex w-full cursor-pointer border-b border-mineshaft-600 px-8 py-3 last:border-b-0 hover:bg-mineshaft-700 aria-disabled:opacity-80"
- role="button"
- tabIndex={0}
- onClick={() => handleSelectRequest(request)}
- onKeyDown={(evt) => {
- if (evt.key === "Enter") {
- handleSelectRequest(request);
- }
- }}
- >
- <div className="flex flex-1 items-center justify-between">
- <div className="flex w-full flex-col justify-between">
- <div className="mb-1 flex w-full items-center">
- <FontAwesomeIcon
- icon={faLock}
- size="xs"
- className="mr-1.5 text-mineshaft-300"
- />
- {generateRequestText(request)}
- </div>
- <div className="flex items-center justify-between">
- <div className="text-xs leading-3 text-gray-500">
- {(() => {
- const memberUser = membersGroupById?.[request.requestedByUserId]?.user;
- const requester = memberUser || request.requestedByUser;
- if (!requester) return null;
- return (
- <>
- Requested {formatDistance(new Date(request.createdAt), new Date())}{" "}
- ago by {requester.firstName} {requester.lastName} ({requester.email}
- ){" "}
- </>
- );
- })()}
- </div>
- </div>
- </div>
- <div className="flex shrink-0 items-center gap-4">
- {request.requestedByUserId === user.id && (
- <div className="flex items-center gap-1.5 text-xs whitespace-nowrap text-bunker-300">
- <FontAwesomeIcon icon={faUser} size="sm" />
- <span>Requested By You</span>
- </div>
- )}
- {request.expiresAt &&
- request.status === ApprovalStatus.PENDING &&
- !isRequestExpired(request) && (
- <Tooltip
- content={`Expires ${format(request.expiresAt, "M/d/yyyy h:mm aa")}`}
- >
- <Badge
- variant={
- new Date(request.expiresAt).getTime() - Date.now() <
- 24 * 60 * 60 * 1000
- ? "danger"
- : "warning"
- }
- >
- <TimerIcon />
- Expires in {formatDistance(new Date(request.expiresAt), new Date())}
- </Badge>
- </Tooltip>
- )}
- <div className="flex shrink-0 justify-end">
- <Tooltip content={details.displayData.tooltipContent}>
- <Badge variant={details.displayData.type}>
- {StatusIcon && <StatusIcon />}
- <span className="whitespace-nowrap">{details.displayData.label}</span>
+ {(areRequestsPending || !!filteredRequests?.length) && (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Duration</TableHead>
+ <TableHead>Environment</TableHead>
+ <TableHead>Secret Path</TableHead>
+ <TableHead>Requested By</TableHead>
+ <TableHead>Requested</TableHead>
+ <TableHead>Status</TableHead>
+ <TableHead className="w-5" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {areRequestsPending &&
+ Array.from({ length: 3 }).map((_, idx) => (
+ // eslint-disable-next-line react/no-array-index-key
+ <TableRow key={`access-request-skeleton-${idx}`}>
+ <TableCell>
+ <Skeleton className="h-5 w-full" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-full" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-full" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-full" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-full" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-full" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-5 w-full" />
+ </TableCell>
+ </TableRow>
+ ))}
+ {filteredRequests?.slice(offset, perPage * page).map((request) => {
+ const details = generateRequestDetails(request);
+ const StatusIcon = details.displayData.icon;
+ const memberUser = membersGroupById?.[request.requestedByUserId]?.user;
+ const requester = memberUser || request.requestedByUser;
+ const requesterName =
+ [requester?.firstName, requester?.lastName].filter(Boolean).join(" ") ||
+ requester?.email;
+ const isExpiringSoon =
+ request.expiresAt &&
+ request.status === ApprovalStatus.PENDING &&
+ !isRequestExpired(request);
+ const environmentDisplayName =
+ environmentNamesBySlug[request.environmentName] ?? request.environmentName;
+
+ return (
+ <TableRow
+ className="h-12"
+ key={request.id}
+ tabIndex={0}
+ onClick={() => handleSelectRequest(request)}
+ onKeyDown={(evt) => {
+ if (evt.key === "Enter") handleSelectRequest(request);
+ }}
+ >
+ <TableCell>
+ {request.isTemporary ? (
+ <Badge variant="info">
+ <TimerIcon />
+ <span className="whitespace-nowrap">
+ {request.temporaryRange
+ ? ms(ms(request.temporaryRange), { long: true })
+ : "Temporary"}
+ </span>
</Badge>
+ ) : (
+ <Badge variant="neutral">Permanent</Badge>
+ )}
+ </TableCell>
+ <TableCell isTruncatable className="w-1/2">
+ {environmentDisplayName}
+ </TableCell>
+ <TableCell isTruncatable className="w-1/2">
+ <p className="truncate text-foreground">{request.policy.secretPath}</p>
+ </TableCell>
+ <TableCell>
+ {requester ? (
+ <div className="flex items-center gap-2">
+ <span className="text-foreground">{requesterName}</span>
+ {request.requestedByUserId === user.id && (
+ <Badge variant="neutral">You</Badge>
+ )}
+ </div>
+ ) : (
+ <span className="text-muted">—</span>
+ )}
+ </TableCell>
+ <TableCell>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>
+ {formatDistance(new Date(request.createdAt), new Date())} ago
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>
+ {format(new Date(request.createdAt), "M/d/yyyy h:mm aa")}
+ </TooltipContent>
</Tooltip>
- </div>
- </div>
- </div>
- </div>
- );
- })}
+ </TableCell>
+ <TableCell>
+ <div className="flex items-center gap-2">
+ {details.displayData.tooltipContent ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge variant={details.displayData.type}>
+ {StatusIcon && <StatusIcon />}
+ <span className="whitespace-nowrap">
+ {details.displayData.label}
+ </span>
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent>{details.displayData.tooltipContent}</TooltipContent>
+ </Tooltip>
+ ) : (
+ <Badge variant={details.displayData.type}>
+ {StatusIcon && <StatusIcon />}
+ <span className="whitespace-nowrap">{details.displayData.label}</span>
+ </Badge>
+ )}
+ {isExpiringSoon && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge
+ variant={
+ new Date(request.expiresAt!).getTime() - Date.now() <
+ 24 * 60 * 60 * 1000
+ ? "danger"
+ : "warning"
+ }
+ >
+ <TimerIcon />
+ {formatDistance(new Date(request.expiresAt!), new Date())}
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent>
+ Expires {format(request.expiresAt!, "M/d/yyyy h:mm aa")}
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+ </TableCell>
+ <TableCell
+ onClick={(e) => e.stopPropagation()}
+ onKeyDown={(e) => e.stopPropagation()}
+ >
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton variant="ghost" size="xs" aria-label="Request actions">
+ <EllipsisIcon />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => handleSelectRequest(request)}>
+ <EyeIcon />
+ View Request
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ )}
{Boolean(filteredRequests.length) && (
<Pagination
- className="border-none"
count={filteredRequests.length}
page={page}
perPage={perPage}
@@ -612,8 +781,8 @@ export const AccessApprovalRequest = ({
onChangePerPage={handlePerPageChange}
/>
)}
- </div>
- </div>
+ </CardContent>
+ </Card>
{!!policies && (
<RequestAccessModal
policies={policies}
diff --git a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/EditAccessRequestModal.tsx b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/EditAccessRequestModal.tsx
index 922a5b8b13..2da9a0b2ab 100644
--- a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/EditAccessRequestModal.tsx
+++ b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/EditAccessRequestModal.tsx
@@ -1,22 +1,31 @@
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 { TriangleAlertIcon } from "lucide-react";
import ms from "ms";
import { z } from "zod";
import { TtlFormLabel } from "@app/components/features";
import { createNotification } from "@app/components/notifications";
import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
Button,
- FormControl,
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
Input,
- Modal,
- ModalClose,
- ModalContent,
TextArea
-} from "@app/components/v2";
+} from "@app/components/v3";
import { useUpdateAccessRequest } from "@app/hooks/api/accessApproval/mutation";
import { accessApprovalKeys } from "@app/hooks/api/accessApproval/queries";
import { TAccessApprovalRequest } from "@app/hooks/api/accessApproval/types";
@@ -82,60 +91,60 @@ const Content = ({ accessRequest, onComplete, projectSlug }: ContentProps) => {
};
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="mt-1 mr-2.5 text-base text-yellow" />
- Updating this access request will restart the review process and require all approvers to
- re-approve it.
- </div>
+ <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">
+ <Alert variant="warning">
+ <TriangleAlertIcon />
+ <AlertTitle>Updating restarts the review process</AlertTitle>
+ <AlertDescription>
+ All approvers will be required to re-approve this access request.
+ </AlertDescription>
+ </Alert>
<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>
+ <Field>
+ <FieldLabel htmlFor="temporaryRange">
+ <TtlFormLabel label="Access Duration" />
+ </FieldLabel>
+ <Input id="temporaryRange" {...field} isError={Boolean(error?.message)} />
+ {!error && (
+ <FieldDescription>
+ Must be less than current access duration:{" "}
+ {accessRequest.isTemporary ? accessRequest.temporaryRange : "Permanent"}
+ </FieldDescription>
+ )}
+ <FieldError errors={[error]} />
+ </Field>
)}
/>
<Controller
control={control}
name="editNote"
render={({ field, fieldState: { error } }) => (
- <FormControl
- label="Reason for Editing"
- isError={Boolean(error?.message)}
- errorText={error?.message}
- >
+ <Field>
+ <FieldLabel htmlFor="editNote">Reason for Editing</FieldLabel>
<TextArea
+ id="editNote"
className="resize-none!"
rows={4}
{...field}
+ isError={Boolean(error?.message)}
placeholder="Provide a reason for updating this request..."
/>
- </FormControl>
+ <FieldError errors={[error]} />
+ </Field>
)}
/>
- <div className="mt-4 flex gap-x-2">
- <Button
- type="submit"
- variant="outline_bg"
- isLoading={isSubmitting}
- isDisabled={isSubmitting}
- >
+ <DialogFooter>
+ <DialogClose asChild>
+ <Button variant="outline">Cancel</Button>
+ </DialogClose>
+ <Button type="submit" variant="project" isPending={isSubmitting} isDisabled={isSubmitting}>
Update Request
</Button>
- <ModalClose asChild>
- <Button variant="plain" colorSchema="secondary">
- Cancel
- </Button>
- </ModalClose>
- </div>
+ </DialogFooter>
</form>
);
};
@@ -158,11 +167,12 @@ export const EditAccessRequestModal = ({
if (!accessRequest) return null;
return (
- <Modal isOpen={isOpen} onOpenChange={onOpenChange}>
- <ModalContent
- title="Edit Access Request"
- subTitle="Modify this access request for re-approval."
- >
+ <Dialog open={isOpen} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>Edit Access Request</DialogTitle>
+ <DialogDescription>Modify this access request for re-approval.</DialogDescription>
+ </DialogHeader>
<Content
projectSlug={projectSlug}
accessRequest={accessRequest}
@@ -171,7 +181,7 @@ export const EditAccessRequestModal = ({
onOpenChange(false);
}}
/>
- </ModalContent>
- </Modal>
+ </DialogContent>
+ </Dialog>
);
};
diff --git a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/RequestAccessForm.tsx b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/RequestAccessForm.tsx
new file mode 100644
index 0000000000..4b7383a0ec
--- /dev/null
+++ b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/RequestAccessForm.tsx
@@ -0,0 +1,420 @@
+import { useMemo } from "react";
+import { Controller, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { formatDistance } from "date-fns";
+import {
+ ChevronDownIcon,
+ ClockIcon,
+ EyeIcon,
+ PencilIcon,
+ PlusIcon,
+ Trash2Icon
+} from "lucide-react";
+import ms from "ms";
+import { z } from "zod";
+
+import { TtlFormLabel } from "@app/components/features";
+import { createNotification } from "@app/components/notifications";
+import {
+ Badge,
+ Button,
+ Checkbox,
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+ FieldTitle,
+ Input,
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ SheetFooter,
+ TextArea,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
+import { useCreateAccessRequest } from "@app/hooks/api";
+import { TAccessApprovalPolicy } from "@app/hooks/api/types";
+
+const secretPermissionSchema = z.object({
+ secretPath: z.string().optional(),
+ environmentSlug: z.string(),
+ [ProjectPermissionActions.Edit]: z.boolean().optional(),
+ [ProjectPermissionActions.Read]: z.boolean().optional(),
+ [ProjectPermissionActions.Create]: z.boolean().optional(),
+ [ProjectPermissionActions.Delete]: z.boolean().optional(),
+ temporaryAccess: z.discriminatedUnion("isTemporary", [
+ z.object({
+ isTemporary: z.literal(true),
+ temporaryRange: z.string().min(1),
+ temporaryAccessStartTime: z.string().datetime(),
+ temporaryAccessEndTime: z.string().datetime().nullable().optional()
+ }),
+ z.object({
+ isTemporary: z.literal(false),
+ temporaryRange: z.string().optional()
+ })
+ ]),
+ note: z.string().optional()
+});
+
+type TSecretPermissionForm = z.infer<typeof secretPermissionSchema>;
+
+const PERMISSIONS = [
+ { name: "read", label: "View", description: "Read secret values", Icon: EyeIcon },
+ { name: "create", label: "Create", description: "Create new secrets", Icon: PlusIcon },
+ { name: "edit", label: "Modify", description: "Update existing secrets", Icon: PencilIcon },
+ { name: "delete", label: "Delete", description: "Delete existing secrets", Icon: Trash2Icon }
+] as const;
+
+export const RequestAccessForm = ({
+ policies,
+ onClose,
+ selectedActions = [],
+ secretPath: initialSecretPath
+}: {
+ policies: TAccessApprovalPolicy[];
+ selectedActions?: ProjectPermissionActions[];
+ secretPath?: string;
+ onClose?: () => void;
+}) => {
+ const { currentProject } = useProject();
+ const requestAccess = useCreateAccessRequest();
+
+ const privilegeForm = useForm<TSecretPermissionForm>({
+ resolver: zodResolver(secretPermissionSchema),
+ defaultValues: {
+ environmentSlug: currentProject.environments?.[0]?.slug,
+ secretPath: initialSecretPath,
+ read: selectedActions.includes(ProjectPermissionActions.Read),
+ edit: selectedActions.includes(ProjectPermissionActions.Edit),
+ create: selectedActions.includes(ProjectPermissionActions.Create),
+ delete: selectedActions.includes(ProjectPermissionActions.Delete),
+ temporaryAccess: {
+ isTemporary: false,
+ temporaryRange: "1h"
+ }
+ }
+ });
+
+ const temporaryAccessField = privilegeForm.watch("temporaryAccess");
+ const selectedEnvironment = privilegeForm.watch("environmentSlug");
+ const secretPath = privilegeForm.watch("secretPath");
+
+ const readAccess = privilegeForm.watch("read");
+ const createAccess = privilegeForm.watch("create");
+ const editAccess = privilegeForm.watch("edit");
+ const deleteAccess = privilegeForm.watch("delete");
+
+ const accessSelected = readAccess || createAccess || editAccess || deleteAccess;
+
+ const selectablePaths = useMemo(() => {
+ const environmentPolicies = policies.filter((policy) =>
+ policy.environments.find((env) => env.slug === selectedEnvironment)
+ );
+
+ privilegeForm.setValue("secretPath", "", {
+ shouldValidate: true
+ });
+
+ return [...environmentPolicies.map((policy) => policy.secretPath)];
+ }, [policies, selectedEnvironment]);
+
+ const isTemporary = temporaryAccessField?.isTemporary;
+ const isExpired =
+ temporaryAccessField.isTemporary &&
+ new Date() > new Date(temporaryAccessField.temporaryAccessEndTime || "");
+
+ const handleRequestAccess = async (data: TSecretPermissionForm) => {
+ if (!currentProject) {
+ createNotification({
+ type: "error",
+ text: "No workspace found.",
+ title: "Error"
+ });
+ return;
+ }
+
+ if (!data.secretPath) {
+ createNotification({
+ type: "error",
+ text: "Please select a secret path...",
+ title: "Error"
+ });
+ return;
+ }
+
+ const policy = policies.find(
+ (p) =>
+ p.environments.find((e) => e.slug === selectedEnvironment) && p.secretPath === secretPath
+ );
+
+ if (
+ policy?.maxTimePeriod &&
+ (!data.temporaryAccess.isTemporary ||
+ ms(data.temporaryAccess.temporaryRange) > ms(policy.maxTimePeriod))
+ ) {
+ createNotification({
+ type: "error",
+ text: `Requested access time range is limited to ${policy.maxTimePeriod} by policy`,
+ title: "Error"
+ });
+ return;
+ }
+
+ const actions = [
+ { action: ProjectPermissionActions.Read, allowed: data.read },
+ { action: ProjectPermissionActions.Create, allowed: data.create },
+ { action: ProjectPermissionActions.Delete, allowed: data.delete },
+ { action: ProjectPermissionActions.Edit, allowed: data.edit }
+ ];
+ const conditions: Record<string, any> = { environment: data.environmentSlug };
+ if (data.secretPath) {
+ conditions.secretPath = { $glob: data.secretPath };
+ }
+ await requestAccess.mutateAsync({
+ ...data,
+ ...(data.temporaryAccess.isTemporary && {
+ temporaryRange: data.temporaryAccess.temporaryRange
+ }),
+ projectSlug: currentProject.slug,
+ isTemporary: data.temporaryAccess.isTemporary,
+ permissions: actions
+ .filter(({ allowed }) => allowed)
+ .map(({ action }) => ({
+ action,
+ subject: [ProjectPermissionSub.Secrets],
+ conditions
+ })),
+ note: data.note
+ });
+
+ createNotification({
+ type: "success",
+ text: "Successfully requested access"
+ });
+ privilegeForm.reset();
+ if (onClose) onClose();
+ };
+
+ const handleGrant = () => {
+ const temporaryRange = privilegeForm.getValues("temporaryAccess.temporaryRange");
+ if (!temporaryRange) {
+ privilegeForm.setError(
+ "temporaryAccess.temporaryRange",
+ { type: "required", message: "Required" },
+ { shouldFocus: true }
+ );
+ return;
+ }
+ privilegeForm.clearErrors("temporaryAccess.temporaryRange");
+ privilegeForm.setValue(
+ "temporaryAccess",
+ {
+ isTemporary: true,
+ temporaryAccessStartTime: new Date().toISOString(),
+ temporaryRange,
+ temporaryAccessEndTime: new Date(new Date().getTime() + ms(temporaryRange)).toISOString()
+ },
+ { shouldDirty: true }
+ );
+ };
+
+ const handleCancelTemporary = () => {
+ privilegeForm.setValue("temporaryAccess", {
+ isTemporary: false,
+ temporaryRange: privilegeForm.getValues("temporaryAccess.temporaryRange")
+ });
+ };
+
+ const getAccessLabel = () => {
+ if (isExpired) return "Access expired";
+ if (!temporaryAccessField?.isTemporary) return "Permanent";
+ return formatDistance(new Date(temporaryAccessField.temporaryAccessEndTime || ""), new Date());
+ };
+
+ return (
+ <form
+ onSubmit={privilegeForm.handleSubmit(handleRequestAccess)}
+ className="flex flex-1 flex-col gap-4 overflow-hidden"
+ >
+ <div className="flex thin-scrollbar flex-1 flex-col gap-4 overflow-y-auto p-4">
+ <Controller
+ control={privilegeForm.control}
+ name="environmentSlug"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel htmlFor="environmentSlug">Environment</FieldLabel>
+ <Select value={field.value} onValueChange={field.onChange}>
+ <SelectTrigger id="environmentSlug" className="w-full">
+ <SelectValue placeholder="Select an environment" />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {currentProject?.environments?.map(({ slug, id, name }) => (
+ <SelectItem value={slug} key={id}>
+ {name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+ )}
+ />
+ <Controller
+ control={privilegeForm.control}
+ name="secretPath"
+ render={({ field }) => {
+ const secretPathField = (
+ <Field>
+ <FieldLabel htmlFor="secretPath">Secret Path</FieldLabel>
+ <Select
+ value={field.value || ""}
+ onValueChange={field.onChange}
+ disabled={!selectablePaths.length}
+ >
+ <SelectTrigger id="secretPath" className="w-full">
+ <SelectValue placeholder="Select a secret path" />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {selectablePaths.map((path) => (
+ <SelectItem value={path} key={path}>
+ {path}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+ );
+
+ if (selectablePaths.length) return secretPathField;
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div className="w-full">{secretPathField}</div>
+ </TooltipTrigger>
+ <TooltipContent>
+ The selected environment doesn&apos;t have any policies.
+ </TooltipContent>
+ </Tooltip>
+ );
+ }}
+ />
+ <Field>
+ <FieldLabel>Permissions</FieldLabel>
+ <div className="grid grid-cols-2 gap-2">
+ {PERMISSIONS.map(({ name, label, description, Icon }) => (
+ <Controller
+ key={name}
+ control={privilegeForm.control}
+ name={name}
+ render={({ field }) => (
+ <FieldLabel htmlFor={`secret-${name}`} variant="project">
+ <Field orientation="horizontal">
+ <FieldContent>
+ <FieldTitle>
+ <Icon />
+ {label}
+ </FieldTitle>
+ <FieldDescription>{description}</FieldDescription>
+ </FieldContent>
+ <Checkbox
+ id={`secret-${name}`}
+ variant="project"
+ isChecked={field.value}
+ onCheckedChange={(isChecked) => field.onChange(isChecked)}
+ />
+ </Field>
+ </FieldLabel>
+ )}
+ />
+ ))}
+ </div>
+ </Field>
+ <Field>
+ <FieldLabel>Duration</FieldLabel>
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button variant="outline" className="w-full justify-between capitalize">
+ <span className="flex items-center gap-2">
+ {isTemporary && <ClockIcon className="size-3.5" />}
+ {getAccessLabel()}
+ </span>
+ <ChevronDownIcon className="size-3.5" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="start" className="flex flex-col gap-4">
+ <div className="text-sm text-foreground">Configure timed access</div>
+ {isExpired && (
+ <Badge variant="danger" className="w-fit">
+ Expired
+ </Badge>
+ )}
+ <Controller
+ control={privilegeForm.control}
+ name="temporaryAccess.temporaryRange"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel htmlFor="temporaryRange">
+ <TtlFormLabel label="Validity" />
+ </FieldLabel>
+ <Input id="temporaryRange" {...field} isError={Boolean(error?.message)} />
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+ <div className="flex items-center gap-2">
+ <Button size="xs" variant="project" onClick={handleGrant}>
+ Grant
+ </Button>
+ {temporaryAccessField.isTemporary && (
+ <Button size="xs" variant="danger" onClick={handleCancelTemporary}>
+ Cancel
+ </Button>
+ )}
+ </div>
+ </PopoverContent>
+ </Popover>
+ </Field>
+ <Controller
+ control={privilegeForm.control}
+ name="note"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel htmlFor="note">Note</FieldLabel>
+ <TextArea
+ id="note"
+ {...field}
+ maxLength={255}
+ placeholder="Add the reason for this access request..."
+ />
+ </Field>
+ )}
+ />
+ </div>
+ <SheetFooter className="border-t">
+ <Button
+ type="submit"
+ variant="project"
+ isPending={privilegeForm.formState.isSubmitting || requestAccess.isPending}
+ isDisabled={
+ !policies.length || !privilegeForm.formState.isValid || !secretPath || !accessSelected
+ }
+ >
+ Request Access
+ </Button>
+ <Button type="button" variant="outline" onClick={onClose}>
+ Cancel
+ </Button>
+ </SheetFooter>
+ </form>
+ );
+};
diff --git a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/RequestAccessModal.tsx b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/RequestAccessModal.tsx
index 0da6331557..a61ad94357 100644
--- a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/RequestAccessModal.tsx
+++ b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/RequestAccessModal.tsx
@@ -1,7 +1,8 @@
-import { Modal, ModalContent } from "@app/components/v2";
+import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@app/components/v3";
import { ProjectPermissionActions } from "@app/context";
import { TAccessApprovalPolicy } from "@app/hooks/api/types";
-import { SpecificPrivilegeSecretForm } from "@app/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/SpecificPrivilegeSection";
+
+import { RequestAccessForm } from "./RequestAccessForm";
export const RequestAccessModal = ({
isOpen,
@@ -16,18 +17,16 @@ export const RequestAccessModal = ({
secretPath?: string;
}) => {
return (
- <Modal isOpen={isOpen} onOpenChange={onOpenChange}>
- <ModalContent
- className="max-w-xl"
- title="Request Access"
- subTitle="Request access to any secrets and resources based on the predefined policies."
- >
- <SpecificPrivilegeSecretForm
- onClose={() => onOpenChange(false)}
- policies={policies}
- {...props}
- />
- </ModalContent>
- </Modal>
+ <Sheet open={isOpen} onOpenChange={onOpenChange}>
+ <SheetContent className="flex h-full flex-col gap-y-0 overflow-y-auto sm:max-w-lg">
+ <SheetHeader className="border-b">
+ <SheetTitle>Request Access</SheetTitle>
+ <SheetDescription>
+ Request access to any secrets and resources based on the predefined policies.
+ </SheetDescription>
+ </SheetHeader>
+ <RequestAccessForm onClose={() => onOpenChange(false)} policies={policies} {...props} />
+ </SheetContent>
+ </Sheet>
);
};
diff --git a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/ReviewAccessModal.tsx b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/ReviewAccessModal.tsx
index 28ec5466c9..8979f78ff0 100644
--- a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/ReviewAccessModal.tsx
+++ b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/ReviewAccessModal.tsx
@@ -1,34 +1,63 @@
-import { ReactNode, useCallback, useMemo, useState } from "react";
-import {
- faBan,
- faCheck,
- faEdit,
- faHourglass,
- faTriangleExclamation,
- faUser,
- faUserSlash
-} from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { Fragment, ReactNode, useCallback, useMemo, useState } from "react";
import { format } from "date-fns";
-import { BanIcon, CheckIcon, HourglassIcon } from "lucide-react";
+import {
+ BanIcon,
+ CheckIcon,
+ ClipboardCheckIcon,
+ HourglassIcon,
+ InfoIcon,
+ SquarePenIcon,
+ TimerIcon,
+ TriangleAlertIcon,
+ UserIcon,
+ UsersIcon,
+ UserXIcon
+} from "lucide-react";
import ms from "ms";
import picomatch from "picomatch";
import { twMerge } from "tailwind-merge";
import { createNotification } from "@app/components/notifications";
import {
+ Alert,
+ AlertDescription,
+ AlertDialog,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertTitle,
+ Badge,
Button,
Checkbox,
- DeleteActionModal,
- FormControl,
- GenericFieldLabel,
+ Detail,
+ DetailLabel,
+ DetailValue,
+ Field,
+ FieldLabel,
IconButton,
Input,
- Modal,
- ModalContent,
- Tooltip
-} from "@app/components/v2";
-import { Badge } from "@app/components/v3";
+ Item,
+ ItemActions,
+ ItemContent,
+ ItemGroup,
+ ItemMedia,
+ ItemSeparator,
+ Label,
+ ProjectIcon,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+ TextArea,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
import {
ProjectPermissionActions,
ProjectPermissionMemberActions,
@@ -62,13 +91,13 @@ const getReviewedStatusSymbol = (status?: ApprovalStatus, isOrgMembershipActive?
if (status === ApprovalStatus.APPROVED)
return (
<Badge variant="success">
- <FontAwesomeIcon icon={faCheck} size="xs" />
+ <CheckIcon />
</Badge>
);
if (status === ApprovalStatus.REJECTED)
return (
<Badge variant="danger">
- <FontAwesomeIcon icon={faBan} size="xs" />
+ <BanIcon />
</Badge>
);
@@ -78,13 +107,13 @@ const getReviewedStatusSymbol = (status?: ApprovalStatus, isOrgMembershipActive?
// TODO(daniel): Fix nested tooltips in the future.
<Badge variant="neutral">
- <FontAwesomeIcon size="xs" icon={faUserSlash} />
+ <UserXIcon />
</Badge>
);
}
return (
<Badge variant="warning">
- <FontAwesomeIcon icon={faHourglass} size="xs" />
+ <HourglassIcon />
</Badge>
);
};
@@ -117,6 +146,7 @@ export const ReviewAccessRequestModal = ({
const [bypassApproval, setBypassApproval] = useState(false);
const [bypassReason, setBypassReason] = useState("");
+ const [revokeConfirmText, setRevokeConfirmText] = useState("");
const { currentProject } = useProject();
const { data: groupMemberships = [] } = useListWorkspaceGroups(currentProject?.id || "");
const { user } = useUser();
@@ -155,7 +185,9 @@ export const ReviewAccessRequestModal = ({
}, [permission, assignPrivilegesConditions, request.user?.email, request.isApprover]);
const accessDetails = {
- env: request.environmentName,
+ env:
+ currentProject?.environments.find((env) => env.slug === request.environmentName)?.name ??
+ request.environmentName,
// secret path will be inside $glob operator
secretPath: request.policy.secretPath,
read: request.permissions?.some(({ action }) => action.includes(ProjectPermissionActions.Read)),
@@ -173,6 +205,13 @@ export const ReviewAccessRequestModal = ({
}
};
+ // Collapse the details grid to a single column when the environment name or secret
+ // path is long enough that two side-by-side columns would feel cramped.
+ const DETAILS_COLLAPSE_THRESHOLD = 30;
+ const shouldCollapseDetails =
+ (accessDetails.env?.length ?? 0) > DETAILS_COLLAPSE_THRESHOLD ||
+ (accessDetails.secretPath?.length ?? 0) > DETAILS_COLLAPSE_THRESHOLD;
+
const requestedAccess = useMemo(() => {
const access: string[] = [];
if (accessDetails.read) access.push("Read");
@@ -322,6 +361,10 @@ export const ReviewAccessRequestModal = ({
!hasRevoked &&
request.expiresAt &&
new Date(request.expiresAt) < new Date();
+ const hasAccessExpired =
+ request.privilege &&
+ request.isApproved &&
+ new Date() > new Date(request.privilege.temporaryAccessEndTime || ("" as string));
const isReviewedByMe = request.reviewers.find((i) => i.userId === user.id);
const shouldBlockRequestActions =
@@ -339,393 +382,485 @@ export const ReviewAccessRequestModal = ({
const revokedByEmail = request.revokedByUser?.email;
return `This access has been revoked${revokedByEmail ? ` by ${revokedByEmail}` : ""}.`;
}
+ if (hasAccessExpired) return "This request's access has expired.";
if (hasApproved) return "This request has been approved.";
if (isReviewedByMe) return "You have reviewed this request.";
return "You are not the reviewer in this step.";
};
+ const renderCompletedDescription = () => {
+ if (hasExpired && request.expiresAt)
+ return `Expired on ${format(new Date(request.expiresAt), "MMM d, yyyy h:mm aa")}`;
+ if (hasRejected)
+ return `Rejected on ${format(new Date(request.updatedAt), "MMM d, yyyy h:mm aa")}`;
+ if (hasRevoked) {
+ const timestamps = [
+ request.approvedAt &&
+ `Approved on ${format(new Date(request.approvedAt), "MMM d, yyyy h:mm aa")}`,
+ request.revokedAt &&
+ `Revoked on ${format(new Date(request.revokedAt), "MMM d, yyyy h:mm aa")}`
+ ].filter(Boolean);
+ return timestamps.length ? timestamps.join(" · ") : null;
+ }
+ if (hasAccessExpired) {
+ const approvedAt = format(
+ new Date(request.approvedAt || request.updatedAt),
+ "MMM d, yyyy h:mm aa"
+ );
+ const endTime = request.privilege?.temporaryAccessEndTime;
+ const expiredAt = endTime ? format(new Date(endTime), "MMM d, yyyy h:mm aa") : null;
+ return expiredAt
+ ? `Approved on ${approvedAt} · Expired on ${expiredAt}`
+ : `Approved on ${approvedAt}`;
+ }
+ if (hasApproved) {
+ const approvedAt = format(
+ new Date(request.approvedAt || request.updatedAt),
+ "MMM d, yyyy h:mm aa"
+ );
+ return `Approved on ${approvedAt}`;
+ }
+ return null;
+ };
+
+ const getBannerVariant = () => {
+ if (hasRejected || hasRevoked || hasExpired || hasAccessExpired) return "danger";
+ if (hasApproved) return "success";
+ return "info";
+ };
+ const completedMessageVariant = getBannerVariant();
+ const completedDescription = renderCompletedDescription();
+
+ const renderBannerIcon = () => {
+ if (hasExpired || hasAccessExpired) return <TimerIcon />;
+ if (completedMessageVariant === "danger") return <TriangleAlertIcon />;
+ if (completedMessageVariant === "success") return <CheckIcon />;
+ return <InfoIcon />;
+ };
+
// users can always reject (cancel) their own request
const isRejectionDisabled = request.isRequestedByCurrentUser
? false
: !(request.isApprover && request.isSelfApproveAllowed) && !bypassApproval;
- return (
- <Modal isOpen={isOpen} onOpenChange={onOpenChange}>
- <ModalContent
- className="max-w-4xl"
- title="Review Request"
- subTitle="Review the request and approve or deny access."
- >
- <div className="mb-4 rounded-r border-l-2 border-l-primary bg-mineshaft-300/5 px-4 py-2.5 text-sm">
- {request.user &&
- (request.user.firstName || request.user.lastName) &&
- request.user.email ? (
- <span className="inline font-medium">
- {request.user?.firstName} {request.user?.lastName} ({request.user?.email})
+ const requesterFullName = [request.user?.firstName, request.user?.lastName]
+ .filter(Boolean)
+ .join(" ");
+ const requesterDisplay =
+ requesterFullName && request.user?.email
+ ? `${requesterFullName} (${request.user.email})`
+ : null;
+
+ // The status banner moved to the top of the sheet, so the footer only renders when there
+ // are actions to take: Approve/Reject when unblocked, or Revoke on an approved request.
+ const showFooter = !shouldBlockRequestActions || (hasApproved && canRevokeAccess);
+
+ type ApproverChain = NonNullable<typeof approverSequence.approvers>[number];
+
+ const approvers = approverSequence?.approvers ?? [];
+
+ const getStatusBadge = (approver: ApproverChain) => {
+ if (approver.hasRejected)
+ return (
+ <Badge variant="danger">
+ <BanIcon />
+ Rejected
+ </Badge>
+ );
+ if (approver.hasApproved)
+ return (
+ <Badge variant="success">
+ <CheckIcon />
+ Approved
+ </Badge>
+ );
+ if (approverSequence?.currentSequence === approver.sequence && !hasExpired)
+ return (
+ <Badge variant="warning">
+ <HourglassIcon />
+ Pending
+ </Badge>
+ );
+ return null;
+ };
+
+ const renderApproverMembers = (approver: ApproverChain) => (
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-sm">
+ {approver.user.map((el) => {
+ const member = approverSequence?.membersGroupById?.[el.id]?.[0];
+
+ if (!member) {
+ const policyApprover = request.policy.approvers.find((a) => a.userId === el.id);
+ return (
+ <span className="flex items-center gap-1.5 opacity-40" key={el.id}>
+ <UserIcon className="size-3.5 shrink-0 text-muted" />
+ {policyApprover?.email || policyApprover?.username || el.id}
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge variant="neutral">
+ <BanIcon />
+ Removed
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent>This user has been removed from the project.</TooltipContent>
+ </Tooltip>
</span>
- ) : (
- <span>A user</span>
- )}{" "}
- is requesting access to the following resource:
- </div>
- <div className="">
- <div className="mt-4 mb-2 text-mineshaft-200">
- <div className="flex flex-wrap gap-x-8 gap-y-4">
- <GenericFieldLabel label="Environment">{accessDetails.env}</GenericFieldLabel>
- <GenericFieldLabel truncate label="Secret Path">
- {accessDetails.secretPath}
- </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>
- </>
- )}
+ );
+ }
+
+ return member.user.isOrgMembershipActive ? (
+ <span className="flex items-center gap-1.5" key={member.user.id}>
+ <UserIcon className="size-3.5 shrink-0 text-muted" />
+ {member.user.username}
+ </span>
+ ) : (
+ <span className="flex items-center gap-1.5 opacity-40" key={member.user.id}>
+ <UserIcon className="size-3.5 shrink-0 text-muted" />
+ {member.user.username}
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge variant="neutral">
+ <BanIcon />
+ Inactive
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent>
+ This user has been deactivated and no longer has an active organization membership.
+ </TooltipContent>
+ </Tooltip>
+ </span>
+ );
+ })}
+ {approver.group.map((el) => (
+ <span className="flex items-center gap-1.5" key={el.id}>
+ <UsersIcon className="size-3.5 shrink-0 text-muted" />
+ {approverSequence?.projectGroupsGroupById?.[el.id]?.[0]?.group?.name ?? el.id}
+ </span>
+ ))}
+ </div>
+ );
+
+ const renderReviewersTooltip = (approver: ApproverChain, badge: ReactNode) => {
+ if (!badge) return null;
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div className="flex">{badge}</div>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-lg">
+ <div className="mb-1 text-sm text-bunker-300">Reviewers</div>
+ <div className="flex max-h-64 thin-scrollbar flex-col divide-y divide-mineshaft-500 overflow-y-auto rounded-sm">
+ {approver.reviewers.map((el, idx) => (
+ <div
+ key={`reviewer-${idx + 1}`}
+ className="flex items-center gap-2 px-2 py-2 text-sm"
+ >
+ <div className={twMerge("flex-1", !el.isOrgMembershipActive && "opacity-40")}>
+ {el.username}
</div>
- </GenericFieldLabel>
- <GenericFieldLabel label="Permission">{requestedAccess}</GenericFieldLabel>
- {request.note && (
- <GenericFieldLabel className="col-span-full" label="Note">
- {request.note}
- </GenericFieldLabel>
- )}
- {request.expiresAt &&
- request.status === ApprovalStatus.PENDING &&
- new Date(request.expiresAt) > new Date() && (
- <GenericFieldLabel label="Request Expires">
- <span>
- In{" "}
- {ms(new Date(request.expiresAt).getTime() - Date.now(), {
- long: true
- })}
- </span>
- </GenericFieldLabel>
+ {getReviewedStatusSymbol(el?.status as ApprovalStatus, el.isOrgMembershipActive)}
+ </div>
+ ))}
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ );
+ };
+
+ return (
+ <>
+ <Sheet open={isOpen} onOpenChange={onOpenChange}>
+ <SheetContent className="flex h-full flex-col gap-y-0 overflow-hidden sm:max-w-2xl">
+ <SheetHeader className="border-b">
+ <SheetTitle>Review Request</SheetTitle>
+ <SheetDescription>Review the request and approve or deny access.</SheetDescription>
+ </SheetHeader>
+ <div className="flex min-h-0 thin-scrollbar flex-1 flex-col overflow-y-auto p-4">
+ {shouldBlockRequestActions && (
+ <Alert variant={completedMessageVariant} className="mb-4">
+ {renderBannerIcon()}
+ <AlertTitle>{renderCompletedMessages()}</AlertTitle>
+ {completedDescription && (
+ <AlertDescription>{completedDescription}</AlertDescription>
)}
- {hasExpired && request.expiresAt && (
- <GenericFieldLabel label="Expired At">
- <span className="text-red-400">
- {format(new Date(request.expiresAt), "MMM d, yyyy h:mm aa")}
- </span>
- </GenericFieldLabel>
- )}
- {hasRejected && (
- <GenericFieldLabel label="Rejected At">
- <span className="text-red-400">
- {format(new Date(request.updatedAt), "MMM d, yyyy h:mm aa")}
- </span>
- </GenericFieldLabel>
- )}
- {(hasApproved || hasRevoked) && (request.approvedAt || hasApproved) && (
- <GenericFieldLabel label="Approved At">
- <span className="text-green-400">
- {format(
- new Date(request.approvedAt || request.updatedAt),
- "MMM d, yyyy h:mm aa"
- )}
- </span>
- </GenericFieldLabel>
- )}
- {hasRevoked && request.revokedAt && (
- <GenericFieldLabel label="Revoked At">
- <span className="text-red-400">
- {format(new Date(request.revokedAt), "MMM d, yyyy h:mm aa")}
- </span>
- </GenericFieldLabel>
- )}
+ </Alert>
+ )}
+ <div className="flex items-start gap-2 text-sm text-accent">
+ <ProjectIcon className="mt-0.5 size-4 shrink-0 text-project" />
+ <p>
+ {requesterDisplay ? (
+ <span className="font-medium text-foreground">{requesterDisplay}</span>
+ ) : (
+ "A user"
+ )}{" "}
+ requested access to the following resource:
+ </p>
</div>
- </div>
+ <div className="">
+ <div className="mt-4 mb-2 text-mineshaft-200">
+ <div
+ className={twMerge(
+ "grid gap-x-8 gap-y-4",
+ shouldCollapseDetails ? "grid-cols-1" : "grid-cols-2"
+ )}
+ >
+ <Detail>
+ <DetailLabel>Environment</DetailLabel>
+ <DetailValue>{accessDetails.env}</DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Secret Path</DetailLabel>
+ <DetailValue className={shouldCollapseDetails ? undefined : "truncate"}>
+ {accessDetails.secretPath}
+ </DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Access Duration</DetailLabel>
+ <DetailValue>
+ <div className="flex items-center 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>
+ <TooltipTrigger asChild>
+ <IconButton
+ onClick={() => handlePopUpOpen("editRequest")}
+ variant="ghost"
+ size="xs"
+ tabIndex={-1}
+ aria-label="Edit access duration"
+ className="-my-1"
+ >
+ <SquarePenIcon />
+ </IconButton>
+ </TooltipTrigger>
+ <TooltipContent>Edit Access Duration</TooltipContent>
+ </Tooltip>
+ </>
+ )}
+ </div>
+ </DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Permission</DetailLabel>
+ <DetailValue>{requestedAccess}</DetailValue>
+ </Detail>
+ {request.note && (
+ <Detail className="col-span-full">
+ <DetailLabel>Note</DetailLabel>
+ <DetailValue>{request.note}</DetailValue>
+ </Detail>
+ )}
+ {request.expiresAt &&
+ request.status === ApprovalStatus.PENDING &&
+ new Date(request.expiresAt) > new Date() && (
+ <Detail>
+ <DetailLabel>Request Expires</DetailLabel>
+ <DetailValue>
+ <span>
+ In{" "}
+ {ms(new Date(request.expiresAt).getTime() - Date.now(), {
+ long: true
+ })}
+ </span>
+ </DetailValue>
+ </Detail>
+ )}
+ </div>
+ </div>
- <div className="mt-4 flex items-center justify-between border-b-2 border-mineshaft-500 py-2">
- <span>Approvers</span>
- {approverSequence.isMyReviewInThisSequence &&
- request.status === ApprovalStatus.PENDING &&
- !hasExpired && <Badge variant="warning">Awaiting Your Review</Badge>}
- </div>
- <div className="max-h-[40vh] thin-scrollbar overflow-y-auto rounded-sm py-2">
- {approverSequence?.approvers &&
- approverSequence.approvers.map((approver, index) => {
- const isInactive =
- approverSequence?.currentSequence <
- (approver.sequence ?? approverSequence.approvers!.length);
-
- const isPending = approverSequence?.currentSequence === approver.sequence;
-
- let StepComponent: ReactNode;
- let BadgeComponent: ReactNode = null;
- if (approver.hasRejected) {
- StepComponent = (
- <Badge isSquare variant="danger">
- <BanIcon />
- </Badge>
- );
- BadgeComponent = <Badge variant="danger">Rejected</Badge>;
- } else if (approver.hasApproved) {
- StepComponent = (
- <Badge isSquare variant="success">
- <CheckIcon />
+ <div className="mt-4 mb-3 flex items-center justify-between">
+ <span className="text-sm font-medium text-foreground">Approvers</span>
+ {approverSequence.isMyReviewInThisSequence &&
+ request.status === ApprovalStatus.PENDING &&
+ !hasExpired && (
+ <Badge variant="warning">
+ <ClipboardCheckIcon />
+ Awaiting Your Review
</Badge>
- );
- BadgeComponent = <Badge variant="success">Approved</Badge>;
- } else if (isPending && !hasExpired) {
- StepComponent = (
- <Badge isSquare variant="warning">
- <HourglassIcon />
- </Badge>
- );
- BadgeComponent = <Badge variant="warning">Pending</Badge>;
- } else {
- StepComponent = (
- <Badge isSquare variant="neutral">
- <span>{index + 1}</span>
- </Badge>
- );
- }
-
- return (
- <div
- key={`approval-list-${index + 1}`}
- className={twMerge("flex", isInactive && "opacity-50")}
- >
- {approverSequence.approvers!.length > 1 && (
- <div className="flex w-12 flex-col items-center gap-2 pr-4">
- <div
- className={twMerge(
- "grow border-mineshaft-600",
- index !== 0 && "border-r"
- )}
- />
- {StepComponent}
- <div
+ )}
+ </div>
+ {approvers.length === 1 ? (
+ <ItemGroup className="gap-0 rounded-lg border border-border bg-container">
+ <Item className="flex-nowrap items-start rounded-none border-0">
+ <ItemContent className="min-w-0 gap-1.5">
+ {renderApproverMembers(approvers[0])}
+ </ItemContent>
+ <ItemActions>
+ {renderReviewersTooltip(approvers[0], getStatusBadge(approvers[0]))}
+ <span className="text-xs text-muted">
+ Min <span className="text-foreground">{approvers[0].approvals}</span>
+ </span>
+ </ItemActions>
+ </Item>
+ </ItemGroup>
+ ) : (
+ <ItemGroup className="gap-0 rounded-lg border border-border bg-container">
+ {approvers.map((approver, index) => {
+ const isInactive =
+ approverSequence?.currentSequence < (approver.sequence ?? approvers.length);
+ const badge = getStatusBadge(approver);
+
+ return (
+ <Fragment key={`approval-list-${index + 1}`}>
+ {index > 0 && <ItemSeparator className="m-0" />}
+ <Item
className={twMerge(
- "grow border-mineshaft-600",
- index < approverSequence.approvers!.length - 1 && "border-r"
+ "flex-nowrap items-start rounded-none border-0",
+ isInactive && "opacity-50"
)}
+ >
+ <ItemMedia>
+ <Badge variant="neutral">Step {index + 1}</Badge>
+ </ItemMedia>
+ <ItemContent className="min-w-0 gap-1.5">
+ {renderApproverMembers(approver)}
+ </ItemContent>
+ <ItemActions>
+ {renderReviewersTooltip(approver, badge)}
+ <span className="text-xs text-muted">
+ Min <span className="text-foreground">{approver.approvals}</span>
+ </span>
+ </ItemActions>
+ </Item>
+ </Fragment>
+ );
+ })}
+ </ItemGroup>
+ )}
+ </div>
+ </div>
+ <SheetFooter className={twMerge("flex-col border-t", !showFooter && "hidden")}>
+ {!shouldBlockRequestActions && (
+ <>
+ {isSoftEnforcement && request.isRequestedByCurrentUser && canBypass && (
+ <div className="mb-2 flex flex-col space-y-2">
+ <div className="flex items-center gap-2">
+ <Checkbox
+ onCheckedChange={(checked) => setBypassApproval(checked === true)}
+ isChecked={bypassApproval}
+ id="byPassApproval"
+ variant="warning"
+ />
+ <Label htmlFor="byPassApproval" className="text-xs font-normal text-warning">
+ Approve without waiting for requirements to be met (bypass policy
+ protection)
+ </Label>
+ </div>
+ {bypassApproval && (
+ <Field className="mt-2">
+ <FieldLabel htmlFor="bypassReason">
+ Reason for bypass
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <TriangleAlertIcon className="text-warning" />
+ </TooltipTrigger>
+ <TooltipContent>Enter a reason for bypassing the policy</TooltipContent>
+ </Tooltip>
+ </FieldLabel>
+ <TextArea
+ id="bypassReason"
+ value={bypassReason}
+ onChange={(e) => setBypassReason(e.currentTarget.value)}
+ placeholder="Enter reason for bypass (min 10 chars)"
/>
- </div>
+ </Field>
)}
- <div className="grid flex-1 grid-cols-5 border-b border-mineshaft-600 p-4">
- <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) {
- const policyApprover = request.policy.approvers.find(
- (a) => a.userId === el.id
- );
- return (
- <div className="flex items-center" key={el.id}>
- <span className="flex items-center gap-2 opacity-40">
- {policyApprover?.email || policyApprover?.username || el.id}
- <span className="text-xs">
- <Tooltip content="This user has been removed from the project.">
- <Badge variant="neutral">
- <BanIcon />
- Removed
- </Badge>
- </Tooltip>
- </span>
- </span>
- {idx < approver.user.length - 1 && ","}
- </div>
- );
- }
-
- 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 gap-2 opacity-40">
- {member.user.username}
- <span className="text-xs">
- <Tooltip content="This user has been deactivated and no longer has an active organization membership.">
- <Badge variant="neutral">
- <BanIcon />
- Inactive
- </Badge>
- </Tooltip>
- </span>
- </span>
- {idx < approver.user.length - 1 && ","}
- </div>
- );
- })}
- </div>
- )}
- </GenericFieldLabel>
- <GenericFieldLabel className="col-span-2" label="Groups">
- {approver?.group
- ?.map(
- (el) =>
- approverSequence?.projectGroupsGroupById?.[el.id]?.[0]?.group?.name
- )
- .join(", ")}
- </GenericFieldLabel>
- <GenericFieldLabel label="Approvals Required">
- <div className="flex items-center">
- <span className="mr-2">{approver.approvals}</span>
- {BadgeComponent && (
- <Tooltip
- className="max-w-lg"
- content={
- <div>
- <div className="mb-1 text-sm text-bunker-300">Reviewers</div>
- <div className="flex max-h-64 thin-scrollbar flex-col divide-y divide-mineshaft-500 overflow-y-auto rounded-sm">
- {approver.reviewers.map((el, idx) => (
- <div
- key={`reviewer-${idx + 1}`}
- className="flex items-center gap-2 px-2 py-2 text-sm"
- >
- <div
- className={twMerge(
- "flex-1",
- !el.isOrgMembershipActive && "opacity-40"
- )}
- >
- {el.username}
- </div>
- {getReviewedStatusSymbol(
- el?.status as ApprovalStatus,
- el.isOrgMembershipActive
- )}
- </div>
- ))}
- </div>
- </div>
- }
- >
- <div>{BadgeComponent}</div>
- </Tooltip>
- )}
- </div>
- </GenericFieldLabel>
- </div>
</div>
- );
- })}
- </div>
- {shouldBlockRequestActions ? (
- <div
- className={twMerge(
- "mt-2 rounded-r border-l-2 border-l-red-500 bg-mineshaft-300/5 px-4 py-2.5 text-sm",
- isReviewedByMe && "border-l-green-400",
- !approverSequence.isMyReviewInThisSequence && "border-l-primary-400",
- hasRejected && "border-l-red-500",
- hasRevoked && "border-l-red-500",
- hasExpired && "border-l-red-500"
- )}
- >
- {renderCompletedMessages()}
- </div>
- ) : (
- <>
- {isSoftEnforcement && request.isRequestedByCurrentUser && canBypass && (
- <div className="mt-2 flex flex-col space-y-2">
- <Checkbox
- onCheckedChange={(checked) => setBypassApproval(checked === true)}
- isChecked={bypassApproval}
- id="byPassApproval"
- className={twMerge("mr-2", bypassApproval ? "border-red/50! bg-red/30!" : "")}
+ )}
+ <div className="space-x-2">
+ <Button
+ isPending={isLoading === "approved"}
+ isDisabled={
+ Boolean(isLoading) ||
+ (!(
+ request.isApprover &&
+ (!request.isRequestedByCurrentUser || request.isSelfApproveAllowed)
+ ) &&
+ !bypassApproval)
+ }
+ onClick={() => handleReview("approved")}
+ size="sm"
+ variant={!request.isApprover && isSoftEnforcement ? "danger" : "project"}
>
- <span className="text-xs text-red">
- Approve without waiting for requirements to be met (bypass policy protection)
- </span>
- </Checkbox>
- {bypassApproval && (
- <FormControl
- label="Reason for bypass"
- className="mt-2"
- isRequired
- tooltipText="Enter a reason for bypassing the policy"
- >
- <Input
- value={bypassReason}
- onChange={(e) => setBypassReason(e.currentTarget.value)}
- placeholder="Enter reason for bypass (min 10 chars)"
- leftIcon={<FontAwesomeIcon icon={faTriangleExclamation} />}
- />
- </FormControl>
- )}
+ <CheckIcon />
+ Approve Request
+ </Button>
+ <Button
+ isPending={isLoading === "rejected"}
+ isDisabled={!!isLoading || isRejectionDisabled}
+ onClick={() => handleReview("rejected")}
+ size="sm"
+ variant="danger"
+ >
+ <BanIcon />
+ Reject Request
+ </Button>
</div>
- )}
- <div className="space-x-2">
- <Button
- isLoading={isLoading === "approved"}
- isDisabled={
- Boolean(isLoading) ||
- (!(
- request.isApprover &&
- (!request.isRequestedByCurrentUser || request.isSelfApproveAllowed)
- ) &&
- !bypassApproval)
- }
- onClick={() => handleReview("approved")}
- className="mt-4"
- size="sm"
- variant="outline_bg"
- colorSchema={!request.isApprover && isSoftEnforcement ? "danger" : "primary"}
- >
- Approve Request
- </Button>
+ </>
+ )}
+ {hasApproved && canRevokeAccess && (
+ <div>
<Button
- isLoading={isLoading === "rejected"}
- isDisabled={!!isLoading || isRejectionDisabled}
- onClick={() => handleReview("rejected")}
- className="mt-4 border-transparent bg-transparent text-mineshaft-200 hover:border-red hover:bg-red/20 hover:text-mineshaft-200"
+ isDisabled={Boolean(isLoading)}
+ onClick={() => handlePopUpOpen("revokeConfirm")}
size="sm"
+ variant="danger"
>
- Reject Request
+ Revoke Access
</Button>
</div>
- </>
- )}
- {hasApproved && canRevokeAccess && (
- <div className="mt-4">
- <Button
- isDisabled={Boolean(isLoading)}
- onClick={() => handlePopUpOpen("revokeConfirm")}
- size="sm"
- colorSchema="danger"
- variant="outline_bg"
- >
- Revoke Access
- </Button>
- </div>
- )}
- </div>
- </ModalContent>
- <DeleteActionModal
- isOpen={popUp.revokeConfirm.isOpen}
- onChange={(isOpenState) => handlePopUpToggle("revokeConfirm", isOpenState)}
- title="Revoke access?"
- subTitle="This will immediately remove the privilege granted by this access request. This action cannot be undone."
- deleteKey="confirm"
- buttonText="Revoke Access"
- onDeleteApproved={handleRevoke}
- />
- </Modal>
+ )}
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ <AlertDialog
+ open={popUp.revokeConfirm.isOpen}
+ onOpenChange={(open) => {
+ handlePopUpToggle("revokeConfirm", open);
+ if (!open) setRevokeConfirmText("");
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Revoke access?</AlertDialogTitle>
+ <AlertDialogDescription>
+ This will immediately remove the privilege granted by this access request. This action
+ cannot be undone.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <div className="flex flex-col gap-2">
+ <Label htmlFor="revoke-confirm">
+ Type <span className="font-semibold text-foreground">confirm</span> to revoke
+ </Label>
+ <Input
+ id="revoke-confirm"
+ value={revokeConfirmText}
+ onChange={(e) => setRevokeConfirmText(e.target.value)}
+ placeholder="confirm"
+ />
+ </div>
+ <AlertDialogFooter>
+ <AlertDialogCancel onClick={() => setRevokeConfirmText("")}>Cancel</AlertDialogCancel>
+ <Button
+ variant="danger"
+ isPending={isLoading === "revoked"}
+ isDisabled={revokeConfirmText !== "confirm" || isLoading === "revoked"}
+ onClick={handleRevoke}
+ >
+ Revoke Access
+ </Button>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
);
};