Fix merge conflicts

This commit is contained in:
Tuan Dang
2024-05-14 13:37:39 -07:00
51 changed files with 2590 additions and 429 deletions
@@ -120,7 +120,7 @@ export default function NavHeader({
passHref
legacyBehavior
href={{
pathname: "/project/[id]/secrets/v2/[env]",
pathname: "/project/[id]/secrets/[env]",
query: { id: router.query.id, env: router.query.env }
}}
>
@@ -0,0 +1,19 @@
import { forwardRef, HTMLAttributes } from "react";
type Props = {
symbolName: string;
} & HTMLAttributes<HTMLDivElement>;
export const FontAwesomeSymbol = forwardRef<HTMLDivElement, Props>(
({ symbolName, ...props }, ref) => {
return (
<div ref={ref} {...props}>
<svg className="w-inherit h-inherit">
<use href={`#${symbolName}`} />
</svg>
</div>
);
}
);
FontAwesomeSymbol.displayName = "FontAwesomeSymbol";
@@ -0,0 +1 @@
export { FontAwesomeSymbol } from "./FontAwesomeSymbol";
@@ -1,17 +1,42 @@
import { TextareaHTMLAttributes, useEffect, useRef, useState } from "react";
import { forwardRef, TextareaHTMLAttributes, useCallback, useMemo, useRef, useState } from "react";
import { faCircle, faFolder, faKey } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import * as Popover from "@radix-ui/react-popover";
import { twMerge } from "tailwind-merge";
import { useWorkspace } from "@app/context";
import { useDebounce } from "@app/hooks";
import { useGetFoldersByEnv, useGetProjectSecrets, useGetUserWsKey } from "@app/hooks/api";
import { useDebounce, useToggle } from "@app/hooks";
import { useGetProjectFolders, useGetProjectSecrets, useGetUserWsKey } from "@app/hooks/api";
import { SecretInput } from "../SecretInput";
const REGEX_UNCLOSED_SECRET_REFERENCE = /\${(?![^{}]*\})/g;
const REGEX_OPEN_SECRET_REFERENCE = /\${/g;
const getIndexOfUnclosedRefToTheLeft = (value: string, pos: number) => {
// take substring up to pos in order to consider edits for closed references
for (let i = pos; i >= 1; i -= 1) {
if (value[i] === "}") return -1;
if (value[i - 1] === "$" && value[i] === "{") {
return i;
}
}
return -1;
};
const getIndexOfUnclosedRefToTheRight = (value: string, pos: number) => {
// use it with above to identify an open ${
for (let i = pos; i < value.length; i += 1) {
if (value[i] === "}") return i - 1;
}
return -1;
};
const getClosingSymbol = (isSelectedSecret: boolean, isClosed: boolean) => {
if (!isClosed) {
return isSelectedSecret ? "}" : ".";
}
if (!isSelectedSecret) return ".";
return "";
};
const mod = (n: number, m: number) => ((n % m) + m) % m;
export enum ReferenceType {
ENVIRONMENT = "environment",
@@ -19,8 +44,9 @@ export enum ReferenceType {
SECRET = "secret"
}
type Props = TextareaHTMLAttributes<HTMLTextAreaElement> & {
value?: string | null;
type Props = Omit<TextareaHTMLAttributes<HTMLTextAreaElement>, "onChange" | "value"> & {
value?: string;
onChange: (val: string) => void;
isImport?: boolean;
isVisible?: boolean;
isReadOnly?: boolean;
@@ -31,339 +57,298 @@ type Props = TextareaHTMLAttributes<HTMLTextAreaElement> & {
};
type ReferenceItem = {
name: string;
label: string;
type: ReferenceType;
slug?: string;
slug: string;
};
export const InfisicalSecretInput = ({
value: propValue,
containerClassName,
secretPath: propSecretPath,
environment: propEnvironment,
onChange,
...props
}: Props) => {
const [inputValue, setInputValue] = useState(propValue ?? "");
const [isSuggestionsOpen, setIsSuggestionsOpen] = useState(false);
const [currentCursorPosition, setCurrentCursorPosition] = useState(0);
const [currentReference, setCurrentReference] = useState<string>("");
const [secretPath, setSecretPath] = useState<string>(propSecretPath || "/");
const [environment, setEnvironment] = useState<string | undefined>(propEnvironment);
const { currentWorkspace } = useWorkspace();
const workspaceId = currentWorkspace?.id || "";
const { data: decryptFileKey } = useGetUserWsKey(workspaceId);
const { data: secrets } = useGetProjectSecrets({
decryptFileKey: decryptFileKey!,
environment: environment || currentWorkspace?.environments?.[0].slug!,
secretPath,
workspaceId
});
const { folderNames: folders } = useGetFoldersByEnv({
path: secretPath,
environments: [environment || currentWorkspace?.environments?.[0].slug!],
projectId: workspaceId
});
export const InfisicalSecretInput = forwardRef<HTMLTextAreaElement, Props>(
(
{
value = "",
onChange,
containerClassName,
secretPath: propSecretPath,
environment: propEnvironment,
...props
},
ref
) => {
const { currentWorkspace } = useWorkspace();
const workspaceId = currentWorkspace?.id || "";
const { data: decryptFileKey } = useGetUserWsKey(workspaceId);
const debouncedCurrentReference = useDebounce(currentReference, 100);
const debouncedValue = useDebounce(value, 500);
const [listReference, setListReference] = useState<ReferenceItem[]>([]);
const [highlightedIndex, setHighlightedIndex] = useState(-1);
const inputRef = useRef<HTMLTextAreaElement>(null);
const isPopupOpen = isSuggestionsOpen && listReference.length > 0 && currentReference.length > 0;
const [highlightedIndex, setHighlightedIndex] = useState(-1);
useEffect(() => {
setInputValue(propValue ?? "");
}, [propValue]);
const inputRef = useRef<HTMLTextAreaElement>(null);
const popoverContentRef = useRef<HTMLDivElement>(null);
const [isFocused, setIsFocused] = useToggle(false);
const currentCursorPosition = inputRef.current?.selectionStart || 0;
useEffect(() => {
let currentEnvironment = propEnvironment;
let currentSecretPath = propSecretPath || "/";
const suggestionSource = useMemo(() => {
const left = getIndexOfUnclosedRefToTheLeft(debouncedValue, currentCursorPosition - 1);
if (left === -1) return { left, value: "", predicate: "", isDeep: false };
if (!currentReference) {
setSecretPath(currentSecretPath);
setEnvironment(currentEnvironment);
return;
}
const suggestionSourceValue = debouncedValue.slice(left + 1, currentCursorPosition);
let suggestionSourceEnv: string | undefined = propEnvironment;
let suggestionSourceSecretPath: string | undefined = propSecretPath || "/";
const isNested = currentReference.includes(".");
// means its like <environment>.<folder1>.<...more folder>.secret
const isDeep = suggestionSourceValue.includes(".");
let predicate = suggestionSourceValue;
if (isDeep) {
const [envSlug, ...folderPaths] = suggestionSourceValue.split(".");
const isValidEnvSlug = currentWorkspace?.environments.find((e) => e.slug === envSlug);
suggestionSourceEnv = isValidEnvSlug ? envSlug : undefined;
suggestionSourceSecretPath = `/${folderPaths.slice(0, -1)?.join("/")}`;
predicate = folderPaths[folderPaths.length - 1];
}
if (isNested) {
const [envSlug, ...folderPaths] = currentReference.split(".");
const isValidEnvSlug = currentWorkspace?.environments.find((e) => e.slug === envSlug);
currentEnvironment = isValidEnvSlug ? envSlug : undefined;
return {
left: left + 1,
// the full value inside a ${<value>}
value: suggestionSourceValue,
// the final part after staging.dev.<folder1>.<predicate>
predicate,
isOpen: left !== -1,
isDeep,
environment: suggestionSourceEnv,
secretPath: suggestionSourceSecretPath
};
}, [debouncedValue]);
// should be based on the last valid section (with .)
folderPaths.pop();
currentSecretPath = `/${folderPaths?.join("/")}`;
}
setSecretPath(currentSecretPath);
setEnvironment(currentEnvironment);
}, [debouncedCurrentReference]);
useEffect(() => {
const currentListReference: ReferenceItem[] = [];
const isNested = currentReference?.includes(".");
if (!currentReference) {
setListReference(currentListReference);
return;
}
if (!environment) {
currentWorkspace?.environments.forEach((env) => {
currentListReference.unshift({
name: env.slug,
type: ReferenceType.ENVIRONMENT
});
});
} else if (isNested) {
folders?.forEach((folder) => {
currentListReference.unshift({ name: folder, type: ReferenceType.FOLDER });
});
} else if (environment) {
currentWorkspace?.environments.forEach((env) => {
currentListReference.unshift({
name: env.slug,
type: ReferenceType.ENVIRONMENT
});
});
}
secrets?.forEach((secret) => {
currentListReference.unshift({ name: secret.key, type: ReferenceType.SECRET });
const isPopupOpen = Boolean(suggestionSource.isOpen) && isFocused;
const { data: secrets } = useGetProjectSecrets({
decryptFileKey: decryptFileKey!,
environment: suggestionSource.environment || "",
secretPath: suggestionSource.secretPath || "",
workspaceId,
options: {
enabled: isPopupOpen
}
});
// Get fragment inside currentReference
const searchFragment = isNested ? currentReference.split(".").pop() || "" : currentReference;
const filteredListRef = currentListReference
.filter((suggestionEntry) =>
suggestionEntry.name.toUpperCase().startsWith(searchFragment.toUpperCase())
)
.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
setListReference(filteredListRef);
}, [secrets, environment, debouncedCurrentReference]);
const getIndexOfUnclosedRefToTheLeft = (pos: number) => {
// take substring up to pos in order to consider edits for closed references
const unclosedReferenceIndexMatches = [
...inputValue.substring(0, pos).matchAll(REGEX_UNCLOSED_SECRET_REFERENCE)
].map((match) => match.index);
// find unclosed reference index less than the current cursor position
let indexIter = -1;
unclosedReferenceIndexMatches.forEach((index) => {
if (index !== undefined && index > indexIter && index < pos) {
indexIter = index;
const { data: folders } = useGetProjectFolders({
environment: suggestionSource.environment || "",
path: suggestionSource.secretPath || "",
projectId: workspaceId,
options: {
enabled: isPopupOpen
}
});
return indexIter;
};
const suggestions = useMemo(() => {
if (!isPopupOpen) return [];
// reset highlight whenever recomputation happens
setHighlightedIndex(-1);
const suggestionsArr: ReferenceItem[] = [];
const predicate = suggestionSource.predicate.toLowerCase();
const getIndexOfUnclosedRefToTheRight = (pos: number) => {
const unclosedReferenceIndexMatches = [...inputValue.matchAll(REGEX_OPEN_SECRET_REFERENCE)].map(
(match) => match.index
);
// find the next unclosed reference index to the right of the current cursor position
// this is so that we know the limitation for slicing references
let indexIter = Infinity;
unclosedReferenceIndexMatches.forEach((index) => {
if (index !== undefined && index > pos && index < indexIter) {
indexIter = index;
if (!suggestionSource.isDeep) {
// At first level only environments and secrets
(currentWorkspace?.environments || []).forEach(({ name, slug }) => {
if (name.toLowerCase().startsWith(predicate))
suggestionsArr.push({
label: name,
slug,
type: ReferenceType.ENVIRONMENT
});
});
} else {
// one deeper levels its based on an environment folders and secrets
(folders || []).forEach(({ name }) => {
if (name.toLowerCase().startsWith(predicate))
suggestionsArr.push({
label: name,
slug: name,
type: ReferenceType.FOLDER
});
});
}
});
(secrets || []).forEach(({ key }) => {
if (key.toLowerCase().startsWith(predicate))
suggestionsArr.push({
label: key,
slug: key,
type: ReferenceType.SECRET
});
});
return suggestionsArr;
}, [secrets, folders, currentWorkspace?.environments, isPopupOpen, suggestionSource.value]);
return indexIter;
};
const handleSuggestionSelect = (selectIndex?: number) => {
const selectedSuggestion =
suggestions[typeof selectIndex !== "undefined" ? selectIndex : highlightedIndex];
if (!selectedSuggestion) {
return;
}
const handleKeyUp = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
// open suggestions if current position is to the right of an unclosed secret reference
const indexIter = getIndexOfUnclosedRefToTheLeft(currentCursorPosition);
if (indexIter === -1) {
return;
}
setIsSuggestionsOpen(true);
if (e.key !== "Enter") {
// current reference is then going to be based on the text from the closest ${ to the right
// until the current cursor position
const openReferenceValue = inputValue.slice(indexIter + 2, currentCursorPosition);
setCurrentReference(openReferenceValue);
}
};
const handleSuggestionSelect = (selectedIndex?: number) => {
const selectedSuggestion = listReference[selectedIndex ?? highlightedIndex];
if (!selectedSuggestion) {
return;
}
const leftIndexIter = getIndexOfUnclosedRefToTheLeft(currentCursorPosition);
const rightIndexLimit = getIndexOfUnclosedRefToTheRight(currentCursorPosition);
if (leftIndexIter === -1) {
return;
}
let newValue = "";
const currentOpenRef = inputValue.slice(leftIndexIter + 2, currentCursorPosition);
if (currentOpenRef.includes(".")) {
// append suggestion after last DOT (.)
const lastDotIndex = currentReference.lastIndexOf(".");
const existingPath = currentReference.slice(0, lastDotIndex);
const refEndAfterAppending = Math.min(
leftIndexIter +
3 +
existingPath.length +
selectedSuggestion.name.length +
Number(selectedSuggestion.type !== ReferenceType.SECRET),
rightIndexLimit - 1
const rightBracketIndex = getIndexOfUnclosedRefToTheRight(value, suggestionSource.left);
const isEnclosed = rightBracketIndex !== -1;
// <lhsValue>${}<rhsvalue>
const lhsValue = value.slice(0, suggestionSource.left);
const rhsValue = value.slice(
rightBracketIndex !== -1 ? rightBracketIndex + 1 : currentCursorPosition
);
// mid will be computed value inside the interpolation
const mid = suggestionSource.isDeep
? `${suggestionSource.value.slice(0, -suggestionSource.predicate.length || undefined)}${selectedSuggestion.slug
}`
: selectedSuggestion.slug;
// whether we should append . or closing bracket on selecting suggestion
const closingSymbol = getClosingSymbol(
selectedSuggestion.type === ReferenceType.SECRET,
isEnclosed
);
newValue = `${inputValue.slice(0, leftIndexIter + 2)}${existingPath}.${
selectedSuggestion.name
}${selectedSuggestion.type !== ReferenceType.SECRET ? "." : "}"}${inputValue.slice(
refEndAfterAppending
)}`;
const openReferenceValue = newValue.slice(leftIndexIter + 2, refEndAfterAppending);
setCurrentReference(openReferenceValue);
const newValue = `${lhsValue}${mid}${closingSymbol}${rhsValue}`;
onChange?.(newValue);
// this delay is for cursor adjustment
// cannot do this without a delay because what happens in onChange gets propogated after the cursor change
// Thus the cursor goes last to avoid that we put a slight delay on cursor change to make it happen later
const delay = setTimeout(() => {
clearTimeout(delay);
if (inputRef.current)
inputRef.current.selectionEnd =
lhsValue.length +
mid.length +
closingSymbol.length +
(isEnclosed && selectedSuggestion.type === ReferenceType.SECRET ? 1 : 0); // if secret is selected the cursor should move after the closing bracket -> }
}, 10);
setHighlightedIndex(-1); // reset highlight
};
// add 1 in order to prevent referenceOpen from being triggered by handleKeyUp
setCurrentCursorPosition(refEndAfterAppending + 1);
} else {
// append selectedSuggestion at position after unclosed ${
const refEndAfterAppending = Math.min(
selectedSuggestion.name.length +
leftIndexIter +
2 +
Number(selectedSuggestion.type !== ReferenceType.SECRET),
rightIndexLimit - 1
);
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
// key operation should trigger only when popup is open
if (isPopupOpen) {
if (e.key === "ArrowDown" || (e.key === "Tab" && !e.shiftKey)) {
setHighlightedIndex((prevIndex) => {
const pos = mod(prevIndex + 1, suggestions.length);
popoverContentRef.current?.children?.[pos]?.scrollIntoView({
block: "nearest",
behavior: "smooth"
});
return pos;
});
} else if (e.key === "ArrowUp" || (e.key === "Tab" && e.shiftKey)) {
setHighlightedIndex((prevIndex) => {
const pos = mod(prevIndex - 1, suggestions.length);
popoverContentRef.current?.children?.[pos]?.scrollIntoView({
block: "nearest",
behavior: "smooth"
});
return pos;
});
} else if (e.key === "Enter" && highlightedIndex >= 0) {
e.preventDefault();
handleSuggestionSelect();
}
if (["ArrowDown", "ArrowUp", "Tab"].includes(e.key)) {
e.preventDefault();
}
}
};
newValue = `${inputValue.slice(0, leftIndexIter + 2)}${selectedSuggestion.name}${
selectedSuggestion.type !== ReferenceType.SECRET ? "." : "}"
}${inputValue.slice(refEndAfterAppending)}`;
const handlePopUpOpen = () => {
setHighlightedIndex(-1);
};
const openReferenceValue = newValue.slice(leftIndexIter + 2, refEndAfterAppending);
setCurrentReference(openReferenceValue);
setCurrentCursorPosition(refEndAfterAppending);
}
// to handle multiple ref for single component
const handleRef = useCallback((el: HTMLTextAreaElement) => {
// @ts-expect-error this is for multiple ref single component
inputRef.current = el;
if (ref) {
if (typeof ref === "function") {
ref(el);
} else {
// eslint-disable-next-line
ref.current = el;
}
}
}, []);
onChange?.({ target: { value: newValue } } as any);
setInputValue(newValue);
setHighlightedIndex(-1);
setIsSuggestionsOpen(false);
};
return (
<Popover.Root open={isPopupOpen} onOpenChange={handlePopUpOpen}>
<Popover.Trigger asChild>
<SecretInput
{...props}
ref={handleRef}
onKeyDown={handleKeyDown}
value={value}
onFocus={() => setIsFocused.on()}
onBlur={(evt) => {
// should not on blur when its mouse down selecting a item from suggestion
if (!(evt.relatedTarget?.getAttribute("aria-label") === "suggestion-item"))
setIsFocused.off();
}}
onChange={(e) => onChange?.(e.target.value)}
containerClassName={containerClassName}
/>
</Popover.Trigger>
<Popover.Content
align="start"
onOpenAutoFocus={(e) => e.preventDefault()}
className="relative top-2 z-[100] max-h-64 overflow-auto rounded-md border border-mineshaft-600 bg-mineshaft-900 font-inter text-bunker-100 shadow-md"
style={{
width: "var(--radix-popover-trigger-width)"
}}
>
<div
className="max-w-60 h-full w-full flex-col items-center justify-center rounded-md text-white"
ref={popoverContentRef}
>
{suggestions.map((item, i) => {
let entryIcon;
if (item.type === ReferenceType.SECRET) {
entryIcon = faKey;
} else if (item.type === ReferenceType.ENVIRONMENT) {
entryIcon = faCircle;
} else {
entryIcon = faFolder;
}
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
const mod = (n: number, m: number) => ((n % m) + m) % m;
if (e.key === "ArrowDown") {
setHighlightedIndex((prevIndex) => mod(prevIndex + 1, listReference.length));
} else if (e.key === "ArrowUp") {
setHighlightedIndex((prevIndex) => mod(prevIndex - 1, listReference.length));
} else if (e.key === "Enter" && highlightedIndex >= 0) {
handleSuggestionSelect();
}
if (["ArrowDown", "ArrowUp", "Enter"].includes(e.key) && isPopupOpen) {
e.preventDefault();
}
};
const setIsOpen = (isOpen: boolean) => {
setHighlightedIndex(-1);
if (isSuggestionsOpen) {
setIsSuggestionsOpen(isOpen);
}
};
const handleSecretChange = (e: any) => {
// propagate event to react-hook-form onChange
if (onChange) {
onChange(e);
}
setCurrentCursorPosition(inputRef.current?.selectionStart || 0);
setInputValue(e.target.value);
};
return (
<Popover.Root open={isPopupOpen} onOpenChange={setIsOpen}>
<Popover.Trigger asChild>
<SecretInput
{...props}
ref={inputRef}
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
value={inputValue}
onChange={handleSecretChange}
containerClassName={containerClassName}
/>
</Popover.Trigger>
<Popover.Content
align="start"
onOpenAutoFocus={(e) => e.preventDefault()}
className={twMerge(
"relative top-2 z-[100] overflow-hidden rounded-md border border-mineshaft-600 bg-mineshaft-900 font-inter text-bunker-100 shadow-md"
)}
style={{
width: "var(--radix-popover-trigger-width)",
maxHeight: "var(--radix-select-content-available-height)"
}}
>
<div className="max-w-60 h-full w-full flex-col items-center justify-center rounded-md text-white">
{listReference.map((item, i) => {
let entryIcon;
if (item.type === ReferenceType.SECRET) {
entryIcon = faKey;
} else if (item.type === ReferenceType.ENVIRONMENT) {
entryIcon = faCircle;
} else {
entryIcon = faFolder;
}
return (
<div
tabIndex={0}
role="button"
onMouseDown={(e) => {
e.preventDefault();
setHighlightedIndex(i);
handleSuggestionSelect(i);
}}
style={{ pointerEvents: "auto" }}
className="flex items-center justify-between border-mineshaft-600 text-left"
key={`secret-reference-secret-${i + 1}`}
>
return (
<div
className={`${
highlightedIndex === i ? "bg-gray-600" : ""
} text-md relative mb-0.5 flex w-full cursor-pointer select-none items-center justify-between rounded-md px-2 py-2 outline-none transition-all hover:bg-mineshaft-500 data-[highlighted]:bg-mineshaft-500`}
tabIndex={0}
role="button"
onKeyDown={(e) => {
if (e.key === "Enter") handleSuggestionSelect(i);
}}
aria-label="suggestion-item"
onClick={(e) => {
inputRef.current?.focus();
e.preventDefault();
e.stopPropagation();
handleSuggestionSelect(i);
}}
onMouseEnter={() => setHighlightedIndex(i)}
style={{ pointerEvents: "auto" }}
className="flex items-center justify-between border-mineshaft-600 text-left"
key={`secret-reference-secret-${i + 1}`}
>
<div className="flex w-full gap-2">
<div className="flex items-center text-yellow-700">
<FontAwesomeIcon
icon={entryIcon}
size={item.type === ReferenceType.ENVIRONMENT ? "xs" : "1x"}
/>
<div
className={`${highlightedIndex === i ? "bg-gray-600" : ""
} text-md relative mb-0.5 flex w-full cursor-pointer select-none items-center justify-between rounded-md px-2 py-2 outline-none transition-all hover:bg-mineshaft-500 data-[highlighted]:bg-mineshaft-500`}
>
<div className="flex w-full gap-2">
<div className="flex items-center text-yellow-700">
<FontAwesomeIcon
icon={entryIcon}
size={item.type === ReferenceType.ENVIRONMENT ? "xs" : "1x"}
/>
</div>
<div className="text-md w-10/12 truncate text-left">{item.label}</div>
</div>
<div className="text-md w-10/12 truncate text-left">{item.name}</div>
</div>
</div>
</div>
);
})}
</div>
</Popover.Content>
</Popover.Root>
);
};
);
})}
</div>
</Popover.Content>
</Popover.Root>
);
}
);
InfisicalSecretInput.displayName = "InfisicalSecretInput";
@@ -0,0 +1,26 @@
import { ReactNode } from "react";
import { faWarning, IconDefinition } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { twMerge } from "tailwind-merge";
type Props = {
icon?: IconDefinition;
title: string;
children: ReactNode;
className?: string;
};
export const NoticeBanner = ({ icon = faWarning, title, children, className }: Props) => (
<div
className={twMerge(
"flex w-full flex-row items-center rounded-md border border-primary-600/70 bg-primary/[.07] p-4 text-base text-white",
className
)}
>
<FontAwesomeIcon icon={icon} className="pr-6 text-4xl text-white/80" />
<div className="flex w-full flex-col text-sm">
<div className="mb-2 text-lg font-semibold">{title}</div>
<div>{children}</div>
</div>
</div>
);
@@ -0,0 +1 @@
export { NoticeBanner } from "./NoticeBanner";
@@ -41,7 +41,7 @@ const syntaxHighlight = (content?: string | null, isVisible?: boolean, isImport?
// akhilmhdh: Dont remove this br. I am still clueless how this works but weirdly enough
// when break is added a line break works properly
return formattedContent.concat(<br />);
return formattedContent.concat(<br key={`secret-value-${formattedContent.length + 1}`} />);
};
type Props = TextareaHTMLAttributes<HTMLTextAreaElement> & {
@@ -90,7 +90,10 @@ export const SecretInput = forwardRef<HTMLTextAreaElement, Props>(
aria-label="secret value"
ref={ref}
className={`absolute inset-0 block h-full resize-none overflow-hidden bg-transparent text-transparent no-scrollbar focus:border-0 ${commonClassName}`}
onFocus={() => setIsSecretFocused.on()}
onFocus={(evt) => {
onFocus?.(evt);
setIsSecretFocused.on();
}}
disabled={isDisabled}
spellCheck={false}
onBlur={(evt) => {
+2
View File
@@ -10,12 +10,14 @@ export * from "./Drawer";
export * from "./Dropdown";
export * from "./EmailServiceSetupModal";
export * from "./EmptyState";
export * from "./FontAwesomeSymbol";
export * from "./FormControl";
export * from "./HoverCardv2";
export * from "./IconButton";
export * from "./Input";
export * from "./Menu";
export * from "./Modal";
export * from "./NoticeBanner";
export * from "./Pagination";
export * from "./Popoverv2";
export * from "./SecretInput";
+1
View File
@@ -5,6 +5,7 @@ export type TServerConfig = {
isMigrationModeOn?: boolean;
trustSamlEmails: boolean;
trustLdapEmails: boolean;
isSecretScanningDisabled: boolean;
};
export type TCreateAdminUserDTO = {
@@ -2,6 +2,7 @@ import { IdentityAuthMethod } from "./enums";
export const identityAuthToNameMap: { [I in IdentityAuthMethod]: string } = {
[IdentityAuthMethod.UNIVERSAL_AUTH]: "Universal Auth",
[IdentityAuthMethod.AWS_AUTH]: "AWS Auth",
[IdentityAuthMethod.KUBERNETES_AUTH]: "Kubernetes Auth"
[IdentityAuthMethod.KUBERNETES_AUTH]: "Kubernetes Auth",
[IdentityAuthMethod.GCP_AUTH]: "GCP Auth",
[IdentityAuthMethod.AWS_AUTH]: "AWS Auth"
};
+3 -2
View File
@@ -1,5 +1,6 @@
export enum IdentityAuthMethod {
UNIVERSAL_AUTH = "universal-auth",
AWS_AUTH = "aws-auth",
KUBERNETES_AUTH = "kubernetes-auth"
KUBERNETES_AUTH = "kubernetes-auth",
GCP_AUTH = "gcp-auth",
AWS_AUTH = "aws-auth"
}
@@ -2,6 +2,7 @@ export { identityAuthToNameMap } from "./constants";
export { IdentityAuthMethod } from "./enums";
export {
useAddIdentityAwsAuth,
useAddIdentityGcpAuth,
useAddIdentityKubernetesAuth,
useAddIdentityUniversalAuth,
useCreateIdentity,
@@ -10,10 +11,12 @@ export {
useRevokeIdentityUniversalAuthClientSecret,
useUpdateIdentity,
useUpdateIdentityAwsAuth,
useUpdateIdentityGcpAuth,
useUpdateIdentityKubernetesAuth,
useUpdateIdentityUniversalAuth} from "./mutations";
export {
useGetIdentityAwsAuth,
useGetIdentityGcpAuth,
useGetIdentityKubernetesAuth,
useGetIdentityUniversalAuth,
useGetIdentityUniversalAuthClientSecrets
@@ -6,6 +6,7 @@ import { organizationKeys } from "../organization/queries";
import { identitiesKeys } from "./queries";
import {
AddIdentityAwsAuthDTO,
AddIdentityGcpAuthDTO,
AddIdentityKubernetesAuthDTO,
AddIdentityUniversalAuthDTO,
ClientSecretData,
@@ -16,10 +17,12 @@ import {
DeleteIdentityUniversalAuthClientSecretDTO,
Identity,
IdentityAwsAuth,
IdentityGcpAuth,
IdentityKubernetesAuth,
IdentityUniversalAuth,
UpdateIdentityAwsAuthDTO,
UpdateIdentityDTO,
UpdateIdentityGcpAuthDTO,
UpdateIdentityKubernetesAuthDTO,
UpdateIdentityUniversalAuthDTO} from "./types";
@@ -175,6 +178,82 @@ export const useRevokeIdentityUniversalAuthClientSecret = () => {
});
};
export const useAddIdentityGcpAuth = () => {
const queryClient = useQueryClient();
return useMutation<IdentityGcpAuth, {}, AddIdentityGcpAuthDTO>({
mutationFn: async ({
identityId,
type,
allowedServiceAccounts,
allowedProjects,
allowedZones,
accessTokenTTL,
accessTokenMaxTTL,
accessTokenNumUsesLimit,
accessTokenTrustedIps
}) => {
const {
data: { identityGcpAuth }
} = await apiRequest.post<{ identityGcpAuth: IdentityGcpAuth }>(
`/api/v1/auth/gcp-auth/identities/${identityId}`,
{
type,
allowedServiceAccounts,
allowedProjects,
allowedZones,
accessTokenTTL,
accessTokenMaxTTL,
accessTokenNumUsesLimit,
accessTokenTrustedIps
}
);
return identityGcpAuth;
},
onSuccess: (_, { organizationId }) => {
queryClient.invalidateQueries(organizationKeys.getOrgIdentityMemberships(organizationId));
}
});
};
export const useUpdateIdentityGcpAuth = () => {
const queryClient = useQueryClient();
return useMutation<IdentityGcpAuth, {}, UpdateIdentityGcpAuthDTO>({
mutationFn: async ({
identityId,
type,
allowedServiceAccounts,
allowedProjects,
allowedZones,
accessTokenTTL,
accessTokenMaxTTL,
accessTokenNumUsesLimit,
accessTokenTrustedIps
}) => {
const {
data: { identityGcpAuth }
} = await apiRequest.patch<{ identityGcpAuth: IdentityGcpAuth }>(
`/api/v1/auth/gcp-auth/identities/${identityId}`,
{
type,
allowedServiceAccounts,
allowedProjects,
allowedZones,
accessTokenTTL,
accessTokenMaxTTL,
accessTokenNumUsesLimit,
accessTokenTrustedIps
}
);
return identityGcpAuth;
},
onSuccess: (_, { organizationId }) => {
queryClient.invalidateQueries(organizationKeys.getOrgIdentityMemberships(organizationId));
}
});
};
export const useAddIdentityAwsAuth = () => {
const queryClient = useQueryClient();
return useMutation<IdentityAwsAuth, {}, AddIdentityAwsAuthDTO>({
@@ -238,6 +317,7 @@ export const useUpdateIdentityAwsAuth = () => {
accessTokenTrustedIps
}
);
return identityAwsAuth;
},
onSuccess: (_, { organizationId }) => {
+21 -3
View File
@@ -5,17 +5,20 @@ import { apiRequest } from "@app/config/request";
import {
ClientSecretData,
IdentityAwsAuth,
IdentityGcpAuth,
IdentityKubernetesAuth,
IdentityUniversalAuth} from "./types";
IdentityUniversalAuth
} from "./types";
export const identitiesKeys = {
getIdentityUniversalAuth: (identityId: string) =>
[{ identityId }, "identity-universal-auth"] as const,
getIdentityUniversalAuthClientSecrets: (identityId: string) =>
[{ identityId }, "identity-universal-auth-client-secrets"] as const,
getIdentityAwsAuth: (identityId: string) => [{ identityId }, "identity-aws-auth"] as const,
getIdentityKubernetesAuth: (identityId: string) =>
[{ identityId }, "identity-kubernetes-auth"] as const
[{ identityId }, "identity-kubernetes-auth"] as const,
getIdentityGcpAuth: (identityId: string) => [{ identityId }, "identity-gcp-auth"] as const,
getIdentityAwsAuth: (identityId: string) => [{ identityId }, "identity-aws-auth"] as const
};
export const useGetIdentityUniversalAuth = (identityId: string) => {
@@ -48,6 +51,21 @@ export const useGetIdentityUniversalAuthClientSecrets = (identityId: string) =>
});
};
export const useGetIdentityGcpAuth = (identityId: string) => {
return useQuery({
enabled: Boolean(identityId),
queryKey: identitiesKeys.getIdentityGcpAuth(identityId),
queryFn: async () => {
const {
data: { identityGcpAuth }
} = await apiRequest.get<{ identityGcpAuth: IdentityGcpAuth }>(
`/api/v1/auth/gcp-auth/identities/${identityId}`
);
return identityGcpAuth;
}
});
};
export const useGetIdentityAwsAuth = (identityId: string) => {
return useQuery({
enabled: Boolean(identityId),
@@ -113,6 +113,48 @@ export type UpdateIdentityUniversalAuthDTO = {
}[];
};
export type IdentityGcpAuth = {
identityId: string;
type: "iam" | "gce";
allowedServiceAccounts: string;
allowedProjects: string;
allowedZones: string;
accessTokenTTL: number;
accessTokenMaxTTL: number;
accessTokenNumUsesLimit: number;
accessTokenTrustedIps: IdentityTrustedIp[];
};
export type AddIdentityGcpAuthDTO = {
organizationId: string;
identityId: string;
type: "iam" | "gce";
allowedServiceAccounts: string;
allowedProjects: string;
allowedZones: string;
accessTokenTTL: number;
accessTokenMaxTTL: number;
accessTokenNumUsesLimit: number;
accessTokenTrustedIps: {
ipAddress: string;
}[];
};
export type UpdateIdentityGcpAuthDTO = {
organizationId: string;
identityId: string;
type?: "iam" | "gce";
allowedServiceAccounts?: string;
allowedProjects?: string;
allowedZones?: string;
accessTokenTTL?: number;
accessTokenMaxTTL?: number;
accessTokenNumUsesLimit?: number;
accessTokenTrustedIps?: {
ipAddress: string;
}[];
};
export type IdentityAwsAuth = {
identityId: string;
type: "iam";
@@ -3,8 +3,8 @@ import Head from "next/head";
import { useRouter } from "next/router";
import { OrgPermissionCan } from "@app/components/permissions";
import { Button } from "@app/components/v2";
import { OrgPermissionActions, OrgPermissionSubjects } from "@app/context";
import { Button, NoticeBanner } from "@app/components/v2";
import { OrgPermissionActions, OrgPermissionSubjects, useServerConfig } from "@app/context";
import { withPermission } from "@app/hoc";
import { SecretScanningLogsTable } from "@app/views/SecretScanning/components";
@@ -17,6 +17,7 @@ const SecretScanning = withPermission(
const router = useRouter();
const queryParams = router.query;
const [integrationEnabled, setIntegrationStatus] = useState(false);
const { config } = useServerConfig();
useEffect(() => {
const linkInstallation = async () => {
@@ -69,6 +70,11 @@ const SecretScanning = withPermission(
<div className="mb-6 text-lg text-mineshaft-300">
Automatically monitor your GitHub activity and prevent secret leaks
</div>
{config.isSecretScanningDisabled && (
<NoticeBanner title="Secret scanning is in maintenance" className="mb-4">
We are working on improving the performance of secret scanning due to increased usage.
</NoticeBanner>
)}
<div className="relative mb-6 flex justify-between rounded-md border border-mineshaft-600 bg-mineshaft-800 p-6">
<div className="flex flex-col items-start">
<div className="mb-1 flex flex-row">
@@ -110,7 +116,7 @@ const SecretScanning = withPermission(
colorSchema="primary"
onClick={generateNewIntegrationSession}
className="h-min py-2"
isDisabled={!isAllowed}
isDisabled={!isAllowed || config.isSecretScanningDisabled}
>
Integrate with GitHub
</Button>
+8
View File
@@ -45,6 +45,14 @@ html {
width: 1%;
white-space: nowrap;
}
.w-inherit {
width: inherit;
}
.h-inherit {
height: inherit;
}
}
@layer components {
@@ -15,6 +15,7 @@ import { IdentityAuthMethod } from "@app/hooks/api/identities";
import { UsePopUpState } from "@app/hooks/usePopUp";
import { IdentityAwsAuthForm } from "./IdentityAwsAuthForm";
import { IdentityGcpAuthForm } from "./IdentityGcpAuthForm";
import { IdentityKubernetesAuthForm } from "./IdentityKubernetesAuthForm";
import { IdentityUniversalAuthForm } from "./IdentityUniversalAuthForm";
@@ -29,8 +30,9 @@ type Props = {
const identityAuthMethods = [
{ label: "Universal Auth", value: IdentityAuthMethod.UNIVERSAL_AUTH },
{ label: "AWS Auth", value: IdentityAuthMethod.AWS_AUTH },
{ label: "Kubernetes Auth", value: IdentityAuthMethod.KUBERNETES_AUTH }
{ label: "Kubernetes Auth", value: IdentityAuthMethod.KUBERNETES_AUTH },
{ label: "GCP Auth", value: IdentityAuthMethod.GCP_AUTH },
{ label: "AWS Auth", value: IdentityAuthMethod.AWS_AUTH }
];
const schema = yup
@@ -86,6 +88,15 @@ export const IdentityAuthMethodModal = ({ popUp, handlePopUpOpen, handlePopUpTog
/>
);
}
case IdentityAuthMethod.GCP_AUTH: {
return (
<IdentityGcpAuthForm
handlePopUpOpen={handlePopUpOpen}
handlePopUpToggle={handlePopUpToggle}
identityAuthMethodData={identityAuthMethodData}
/>
);
}
case IdentityAuthMethod.UNIVERSAL_AUTH: {
return (
<IdentityUniversalAuthForm
@@ -0,0 +1,384 @@
import { useEffect } from "react";
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 { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, FormControl, IconButton, Input, Select, SelectItem } from "@app/components/v2";
import { useOrganization, useSubscription } from "@app/context";
import {
useAddIdentityGcpAuth,
useGetIdentityGcpAuth,
useUpdateIdentityGcpAuth
} from "@app/hooks/api";
import { IdentityAuthMethod } from "@app/hooks/api/identities";
import { IdentityTrustedIp } from "@app/hooks/api/identities/types";
import { UsePopUpState } from "@app/hooks/usePopUp";
const schema = z
.object({
type: z.enum(["iam", "gce"]),
allowedServiceAccounts: z.string(),
allowedProjects: z.string(),
allowedZones: z.string(),
accessTokenTTL: z.string(),
accessTokenMaxTTL: z.string(),
accessTokenNumUsesLimit: z.string(),
accessTokenTrustedIps: z
.array(
z.object({
ipAddress: z.string().max(50)
})
)
.min(1)
})
.required();
export type FormData = z.infer<typeof schema>;
type Props = {
handlePopUpOpen: (popUpName: keyof UsePopUpState<["upgradePlan"]>) => void;
handlePopUpToggle: (
popUpName: keyof UsePopUpState<["identityAuthMethod"]>,
state?: boolean
) => void;
identityAuthMethodData: {
identityId: string;
name: string;
authMethod?: IdentityAuthMethod;
};
};
export const IdentityGcpAuthForm = ({
handlePopUpOpen,
handlePopUpToggle,
identityAuthMethodData
}: Props) => {
const { currentOrg } = useOrganization();
const orgId = currentOrg?.id || "";
const { subscription } = useSubscription();
const { mutateAsync: addMutateAsync } = useAddIdentityGcpAuth();
const { mutateAsync: updateMutateAsync } = useUpdateIdentityGcpAuth();
const { data } = useGetIdentityGcpAuth(identityAuthMethodData?.identityId ?? "");
const {
control,
handleSubmit,
reset,
formState: { isSubmitting },
watch
} = useForm<FormData>({
resolver: zodResolver(schema),
defaultValues: {
type: "gce",
allowedServiceAccounts: "",
allowedProjects: "",
allowedZones: "",
accessTokenTTL: "2592000",
accessTokenMaxTTL: "2592000",
accessTokenNumUsesLimit: "0",
accessTokenTrustedIps: [{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }]
}
});
const watchedType = watch("type");
const {
fields: accessTokenTrustedIpsFields,
append: appendAccessTokenTrustedIp,
remove: removeAccessTokenTrustedIp
} = useFieldArray({ control, name: "accessTokenTrustedIps" });
useEffect(() => {
if (data) {
reset({
type: data.type,
allowedServiceAccounts: data.allowedServiceAccounts,
allowedProjects: data.allowedProjects,
allowedZones: data.allowedZones,
accessTokenTTL: String(data.accessTokenTTL),
accessTokenMaxTTL: String(data.accessTokenMaxTTL),
accessTokenNumUsesLimit: String(data.accessTokenNumUsesLimit),
accessTokenTrustedIps: data.accessTokenTrustedIps.map(
({ ipAddress, prefix }: IdentityTrustedIp) => {
return {
ipAddress: `${ipAddress}${prefix !== undefined ? `/${prefix}` : ""}`
};
}
)
});
} else {
reset({
type: "iam",
allowedServiceAccounts: "",
allowedProjects: "",
allowedZones: "",
accessTokenTTL: "2592000",
accessTokenMaxTTL: "2592000",
accessTokenNumUsesLimit: "0",
accessTokenTrustedIps: [{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }]
});
}
}, [data]);
const onFormSubmit = async ({
type,
allowedServiceAccounts,
allowedProjects,
allowedZones,
accessTokenTTL,
accessTokenMaxTTL,
accessTokenNumUsesLimit,
accessTokenTrustedIps
}: FormData) => {
try {
if (!identityAuthMethodData) return;
if (data) {
await updateMutateAsync({
identityId: identityAuthMethodData.identityId,
organizationId: orgId,
type,
allowedServiceAccounts,
allowedProjects,
allowedZones,
accessTokenTTL: Number(accessTokenTTL),
accessTokenMaxTTL: Number(accessTokenMaxTTL),
accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit),
accessTokenTrustedIps
});
} else {
await addMutateAsync({
identityId: identityAuthMethodData.identityId,
organizationId: orgId,
type,
allowedServiceAccounts: allowedServiceAccounts || "",
allowedProjects: allowedProjects || "",
allowedZones: allowedZones || "",
accessTokenTTL: Number(accessTokenTTL),
accessTokenMaxTTL: Number(accessTokenMaxTTL),
accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit),
accessTokenTrustedIps
});
}
handlePopUpToggle("identityAuthMethod", false);
createNotification({
text: `Successfully ${
identityAuthMethodData?.authMethod ? "updated" : "configured"
} auth method`,
type: "success"
});
reset();
} catch (err) {
createNotification({
text: `Failed to ${identityAuthMethodData?.authMethod ? "update" : "configure"} identity`,
type: "error"
});
}
};
return (
<form onSubmit={handleSubmit(onFormSubmit)}>
<Controller
control={control}
name="type"
render={({ field: { onChange, ...field }, fieldState: { error } }) => (
<FormControl label="Type" isError={Boolean(error)} errorText={error?.message}>
<Select
defaultValue={field.value}
{...field}
onValueChange={(e) => onChange(e)}
className="w-full"
>
<SelectItem value="gce" key="gcp-type-gce">
GCP ID Token Auth (Recommended)
</SelectItem>
<SelectItem value="iam" key="gcpiam">
GCP IAM Auth
</SelectItem>
</Select>
</FormControl>
)}
/>
<Controller
control={control}
defaultValue="2592000"
name="allowedServiceAccounts"
render={({ field, fieldState: { error } }) => (
<FormControl
label="Allowed Service Account Emails"
isError={Boolean(error)}
errorText={error?.message}
>
<Input
{...field}
placeholder="[email protected], [email protected]"
type="text"
/>
</FormControl>
)}
/>
{watchedType === "gce" && (
<Controller
control={control}
name="allowedProjects"
render={({ field, fieldState: { error } }) => (
<FormControl
label="Allowed Projects"
isError={Boolean(error)}
errorText={error?.message}
>
<Input {...field} placeholder="my-gcp-project, ..." />
</FormControl>
)}
/>
)}
{watchedType === "gce" && (
<Controller
control={control}
name="allowedZones"
render={({ field, fieldState: { error } }) => (
<FormControl label="Allowed Zones" isError={Boolean(error)} errorText={error?.message}>
<Input {...field} placeholder="us-west2-a, us-central1-a, ..." />
</FormControl>
)}
/>
)}
<Controller
control={control}
defaultValue="2592000"
name="accessTokenTTL"
render={({ field, fieldState: { error } }) => (
<FormControl
label="Access Token TTL (seconds)"
isError={Boolean(error)}
errorText={error?.message}
>
<Input {...field} placeholder="2592000" type="number" min="1" step="1" />
</FormControl>
)}
/>
<Controller
control={control}
defaultValue="2592000"
name="accessTokenMaxTTL"
render={({ field, fieldState: { error } }) => (
<FormControl
label="Access Token Max TTL (seconds)"
isError={Boolean(error)}
errorText={error?.message}
>
<Input {...field} placeholder="2592000" type="number" min="1" step="1" />
</FormControl>
)}
/>
<Controller
control={control}
defaultValue="0"
name="accessTokenNumUsesLimit"
render={({ field, fieldState: { error } }) => (
<FormControl
label="Access Token Max Number of Uses"
isError={Boolean(error)}
errorText={error?.message}
>
<Input {...field} placeholder="0" type="number" min="0" step="1" />
</FormControl>
)}
/>
{accessTokenTrustedIpsFields.map(({ id }, index) => (
<div className="mb-3 flex items-end space-x-2" key={id}>
<Controller
control={control}
name={`accessTokenTrustedIps.${index}.ipAddress`}
defaultValue="0.0.0.0/0"
render={({ field, fieldState: { error } }) => {
return (
<FormControl
className="mb-0 flex-grow"
label={index === 0 ? "Access Token Trusted IPs" : undefined}
isError={Boolean(error)}
errorText={error?.message}
>
<Input
value={field.value}
onChange={(e) => {
if (subscription?.ipAllowlisting) {
field.onChange(e);
return;
}
handlePopUpOpen("upgradePlan");
}}
placeholder="123.456.789.0"
/>
</FormControl>
);
}}
/>
<IconButton
onClick={() => {
if (subscription?.ipAllowlisting) {
removeAccessTokenTrustedIp(index);
return;
}
handlePopUpOpen("upgradePlan");
}}
size="lg"
colorSchema="danger"
variant="plain"
ariaLabel="update"
className="p-3"
>
<FontAwesomeIcon icon={faXmark} />
</IconButton>
</div>
))}
<div className="my-4 ml-1">
<Button
variant="outline_bg"
onClick={() => {
if (subscription?.ipAllowlisting) {
appendAccessTokenTrustedIp({
ipAddress: "0.0.0.0/0"
});
return;
}
handlePopUpOpen("upgradePlan");
}}
leftIcon={<FontAwesomeIcon icon={faPlus} />}
size="xs"
>
Add IP Address
</Button>
</div>
<div className="flex items-center">
<Button
className="mr-4"
size="sm"
type="submit"
isLoading={isSubmitting}
isDisabled={isSubmitting}
>
{identityAuthMethodData?.authMethod ? "Update" : "Configure"}
</Button>
<Button
colorSchema="secondary"
variant="plain"
onClick={() => handlePopUpToggle("identityAuthMethod", false)}
>
{identityAuthMethodData?.authMethod ? "Cancel" : "Skip"}
</Button>
</div>
</form>
);
};
@@ -8,6 +8,7 @@ import {
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuTrigger,
FontAwesomeSymbol,
FormControl,
IconButton,
Input,
@@ -19,6 +20,7 @@ import {
TextArea,
Tooltip
} from "@app/components/v2";
import { InfisicalSecretInput } from "@app/components/v2/InfisicalSecretInput";
import {
ProjectPermissionActions,
ProjectPermissionSub,
@@ -29,20 +31,6 @@ import { useToggle } from "@app/hooks";
import { DecryptedSecret } from "@app/hooks/api/secrets/types";
import { WsTag } from "@app/hooks/api/types";
import { subject } from "@casl/ability";
import { faCheckCircle } from "@fortawesome/free-regular-svg-icons";
import {
faCheck,
faClock,
faClose,
faCodeBranch,
faComment,
faCopy,
faEllipsis,
faKey,
faTag,
faTags
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod";
import { AnimatePresence, motion } from "framer-motion";
import { memo, useEffect } from "react";
@@ -50,7 +38,12 @@ import { Controller, useFieldArray, useForm } from "react-hook-form";
import { twMerge } from "tailwind-merge";
import { CreateReminderForm } from "./CreateReminderForm";
import { formSchema, SecretActionType, TFormSchema } from "./SecretListView.utils";
import {
FontAwesomeSpriteName,
formSchema,
SecretActionType,
TFormSchema
} from "./SecretListView.utils";
type Props = {
secret: DecryptedSecret;
@@ -206,7 +199,6 @@ export const SecretItem = memo(
}
}}
/>
<form onSubmit={handleSubmit(handleFormSubmit)}>
<div
className={twMerge(
@@ -227,9 +219,12 @@ export const SecretItem = memo(
onCheckedChange={() => onToggleSecretSelect(secret.id)}
className={twMerge("ml-3 hidden group-hover:flex", isSelected && "flex")}
/>
<FontAwesomeIcon
icon={faKey}
className={twMerge("ml-3 block group-hover:hidden", isSelected && "hidden")}
<FontAwesomeSymbol
className={twMerge(
"ml-3 block h-3.5 w-3.5 group-hover:hidden",
isSelected && "hidden"
)}
symbolName={FontAwesomeSpriteName.SecretKey}
/>
</div>
<div className="flex h-11 w-80 flex-shrink-0 items-center px-4 py-2">
@@ -278,10 +273,12 @@ export const SecretItem = memo(
key="secret-value"
control={control}
render={({ field }) => (
<SecretInput
<InfisicalSecretInput
isReadOnly={isReadOnly}
key="secret-value"
isVisible={isVisible}
environment={environment}
secretPath={secretPath}
{...field}
containerClassName="py-1.5 rounded-md transition-all group-hover:mr-2"
/>
@@ -297,7 +294,14 @@ export const SecretItem = memo(
className="w-0 overflow-hidden p-0 group-hover:mr-2 group-hover:w-5"
onClick={copyTokenToClipboard}
>
<FontAwesomeIcon icon={isSecValueCopied ? faCheck : faCopy} />
<FontAwesomeSymbol
className="h-3.5 w-3"
symbolName={
isSecValueCopied
? FontAwesomeSpriteName.Check
: FontAwesomeSpriteName.ClipboardCopy
}
/>
</IconButton>
</Tooltip>
<DropdownMenu>
@@ -318,7 +322,10 @@ export const SecretItem = memo(
isDisabled={!isAllowed}
>
<Tooltip content="Tags">
<FontAwesomeIcon icon={faTags} />
<FontAwesomeSymbol
className="h-3.5 w-3.5"
symbolName={FontAwesomeSpriteName.Tags}
/>
</Tooltip>
</IconButton>
</DropdownMenuTrigger>
@@ -334,7 +341,14 @@ export const SecretItem = memo(
<DropdownMenuItem
onClick={() => handleTagSelect(tag)}
key={`${secret.id}-${tagId}`}
icon={isTagSelected && <FontAwesomeIcon icon={faCheckCircle} />}
icon={
isTagSelected && (
<FontAwesomeSymbol
symbolName={FontAwesomeSpriteName.CheckedCircle}
className="h-3 w-3"
/>
)
}
iconPos="right"
>
<div className="flex items-center">
@@ -353,7 +367,12 @@ export const SecretItem = memo(
className="w-full"
colorSchema="primary"
variant="outline_bg"
leftIcon={<FontAwesomeIcon icon={faTag} />}
leftIcon={
<FontAwesomeSymbol
symbolName={FontAwesomeSpriteName.Tags}
className="h-3 w-3"
/>
}
onClick={onCreateTag}
>
Create a tag
@@ -379,7 +398,10 @@ export const SecretItem = memo(
isOverriden && "w-5 text-primary"
)}
>
<FontAwesomeIcon icon={faCodeBranch} />
<FontAwesomeSymbol
symbolName={FontAwesomeSpriteName.Override}
className="h-3.5 w-3.5"
/>
</IconButton>
)}
</ProjectPermissionCan>
@@ -393,6 +415,7 @@ export const SecretItem = memo(
variant="plain"
size="md"
ariaLabel="add-reminder"
onClick={() => setCreateReminderFormOpen.on()}
>
<Tooltip
content={
@@ -404,9 +427,9 @@ export const SecretItem = memo(
: "Reminder"
}
>
<FontAwesomeIcon
onClick={() => setCreateReminderFormOpen.on()}
icon={faClock}
<FontAwesomeSymbol
className="h-3.5 w-3.5"
symbolName={FontAwesomeSpriteName.Clock}
/>
</Tooltip>
</IconButton>
@@ -430,7 +453,10 @@ export const SecretItem = memo(
isDisabled={!isAllowed}
>
<Tooltip content="Comment">
<FontAwesomeIcon icon={faComment} />
<FontAwesomeSymbol
className="h-3.5 w-3.5"
symbolName={FontAwesomeSpriteName.Comment}
/>
</Tooltip>
</IconButton>
</PopoverTrigger>
@@ -466,10 +492,13 @@ export const SecretItem = memo(
ariaLabel="more"
variant="plain"
size="md"
className="p-0 opacity-0 group-hover:opacity-100"
className="p-0 opacity-0 group-hover:opacity-100 h-5 w-4"
onClick={() => onDetailViewSecret(secret)}
>
<FontAwesomeIcon icon={faEllipsis} size="lg" />
<FontAwesomeSymbol
symbolName={FontAwesomeSpriteName.More}
className="h-5 w-4"
/>
</IconButton>
</Tooltip>
<ProjectPermissionCan
@@ -488,7 +517,10 @@ export const SecretItem = memo(
onClick={() => onDeleteSecret(secret)}
isDisabled={!isAllowed}
>
<FontAwesomeIcon icon={faClose} size="lg" />
<FontAwesomeSymbol
symbolName={FontAwesomeSpriteName.Close}
className="h-5 w-4"
/>
</IconButton>
)}
</ProjectPermissionCan>
@@ -516,10 +548,12 @@ export const SecretItem = memo(
{isSubmitting ? (
<Spinner className="m-0 h-4 w-4 p-0" />
) : (
<FontAwesomeIcon
icon={faCheck}
size="lg"
className={twMerge("text-primary", errors.key && "text-mineshaft-300")}
<FontAwesomeSymbol
symbolName={FontAwesomeSpriteName.Check}
className={twMerge(
"h-4 w-4 text-primary",
errors.key && "text-mineshaft-300"
)}
/>
)}
</IconButton>
@@ -536,7 +570,10 @@ export const SecretItem = memo(
onClick={() => reset()}
isDisabled={isSubmitting}
>
<FontAwesomeIcon icon={faClose} size="lg" />
<FontAwesomeSymbol
symbolName={FontAwesomeSpriteName.Close}
className="h-4 w-4 text-primary"
/>
</IconButton>
</Tooltip>
</motion.div>
@@ -1,4 +1,5 @@
import { useCallback } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useQueryClient } from "@tanstack/react-query";
import { twMerge } from "tailwind-merge";
@@ -17,6 +18,7 @@ import { useSelectedSecretActions, useSelectedSecrets } from "../../SecretMainPa
import { Filter, GroupBy, SortDir } from "../../SecretMainPage.types";
import { SecretDetailSidebar } from "./SecretDetaiSidebar";
import { SecretItem } from "./SecretItem";
import { FontAwesomeSpriteSymbols } from "./SecretListView.utils";
type Props = {
secrets?: DecryptedSecret[];
@@ -89,7 +91,6 @@ export const SecretListView = ({
isVisible,
isProtectedBranch = false
}: Props) => {
const queryClient = useQueryClient();
const { popUp, handlePopUpToggle, handlePopUpOpen, handlePopUpClose } = usePopUp([
"deleteSecret",
@@ -341,6 +342,13 @@ export const SecretListView = ({
>
{namespace}
</div>
{FontAwesomeSpriteSymbols.map(({ icon, symbol }) => (
<FontAwesomeIcon
icon={icon}
symbol={symbol}
key={`font-awesome-svg-spritie-${symbol}`}
/>
))}
{filteredSecrets.map((secret) => (
<SecretItem
environment={environment}
@@ -1,4 +1,16 @@
/* eslint-disable no-nested-ternary */
import { faCheckCircle } from "@fortawesome/free-regular-svg-icons";
import {
faCheck,
faClock,
faClose,
faCodeBranch,
faComment,
faCopy,
faEllipsis,
faKey,
faTags
} from "@fortawesome/free-solid-svg-icons";
import { z } from "zod";
export enum SecretActionType {
@@ -41,3 +53,31 @@ export const formSchema = z.object({
});
export type TFormSchema = z.infer<typeof formSchema>;
export enum FontAwesomeSpriteName {
SecretKey = "secret-key",
Check = "check",
ClipboardCopy = "clipboard-copy",
Tags = "secret-tags",
Clock = "reminder-clock",
Comment = "comment",
More = "more",
Override = "secret-override",
Close = "close",
CheckedCircle = "check-circle"
}
// this is an optimization technique
// https://docs.fontawesome.com/web/add-icons/svg-symbols
export const FontAwesomeSpriteSymbols = [
{ icon: faKey, symbol: FontAwesomeSpriteName.SecretKey },
{ icon: faCheck, symbol: FontAwesomeSpriteName.Check },
{ icon: faCopy, symbol: FontAwesomeSpriteName.ClipboardCopy },
{ icon: faTags, symbol: FontAwesomeSpriteName.Tags },
{ icon: faClock, symbol: FontAwesomeSpriteName.Clock },
{ icon: faComment, symbol: FontAwesomeSpriteName.Comment },
{ icon: faEllipsis, symbol: FontAwesomeSpriteName.More },
{ icon: faCodeBranch, symbol: FontAwesomeSpriteName.Override },
{ icon: faClose, symbol: FontAwesomeSpriteName.Close },
{ icon: faCheckCircle, symbol: FontAwesomeSpriteName.CheckedCircle }
];