Merge pull request #76 from prowler-cloud/PRWLR-5109-Set-Up-Providers-Credentials-Workflow

Set up providers credentials workflow
This commit is contained in:
Pablo Lara
2024-11-06 14:33:38 +01:00
committed by GitHub
51 changed files with 2416 additions and 420 deletions
-4
View File
@@ -1,7 +1,3 @@
### Motivation
Why it this PR useful for the project?
### Description
What was done in this PR
+128 -5
View File
@@ -4,7 +4,7 @@ import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { auth } from "@/auth.config";
import { getErrorMessage, parseStringify } from "@/lib";
import { getErrorMessage, parseStringify, wait } from "@/lib";
export const getProviders = async ({
page = 1,
@@ -114,7 +114,7 @@ export const addProvider = async (formData: FormData) => {
const keyServer = process.env.API_BASE_URL;
const providerType = formData.get("providerType");
const providerId = formData.get("providerId");
const providerUid = formData.get("providerUid");
const providerAlias = formData.get("providerAlias");
const url = new URL(`${keyServer}/providers`);
@@ -132,7 +132,7 @@ export const addProvider = async (formData: FormData) => {
type: "Provider",
attributes: {
provider: providerType,
uid: providerId,
uid: providerUid,
alias: providerAlias,
},
},
@@ -149,11 +149,109 @@ export const addProvider = async (formData: FormData) => {
}
};
export const addCredentialsProvider = async (formData: FormData) => {
const session = await auth();
const keyServer = process.env.API_BASE_URL;
const url = new URL(`${keyServer}/providers/secrets`);
const secretName = formData.get("secretName");
const providerId = formData.get("providerId");
const providerType = formData.get("providerType");
const isRole = formData.get("role_arn") !== null;
let secret = {};
let secretType = "static"; // Default to static credentials
if (providerType === "aws") {
if (isRole) {
// Role-based configuration for AWS
secretType = "role";
secret = {
role_arn: formData.get("role_arn"),
aws_access_key_id: formData.get("aws_access_key_id") || undefined,
aws_secret_access_key:
formData.get("aws_secret_access_key") || undefined,
aws_session_token: formData.get("aws_session_token") || undefined,
session_duration:
parseInt(formData.get("session_duration") as string, 10) || 3600,
external_id: formData.get("external_id") || undefined,
role_session_name: formData.get("role_session_name") || undefined,
};
} else {
// Static credentials configuration for AWS
secret = {
aws_access_key_id: formData.get("aws_access_key_id"),
aws_secret_access_key: formData.get("aws_secret_access_key"),
aws_session_token: formData.get("aws_session_token") || undefined,
};
}
} else if (providerType === "azure") {
// Static credentials configuration for Azure
secret = {
client_id: formData.get("client_id"),
client_secret: formData.get("client_secret"),
tenant_id: formData.get("tenant_id"),
};
} else if (providerType === "gcp") {
// Static credentials configuration for GCP
secret = {
client_id: formData.get("client_id"),
client_secret: formData.get("client_secret"),
refresh_token: formData.get("refresh_token"),
};
} else if (providerType === "kubernetes") {
// Static credentials configuration for Kubernetes
secret = {
kubeconfig_content: formData.get("kubeconfig_content"),
};
}
const bodyData = {
data: {
type: "ProviderSecret",
attributes: {
secret_type: secretType,
secret,
name: secretName,
},
relationships: {
provider: {
data: {
id: providerId,
type: "Provider",
},
},
},
},
};
try {
const response = await fetch(url.toString(), {
method: "POST",
headers: {
"Content-Type": "application/vnd.api+json",
Accept: "application/vnd.api+json",
Authorization: `Bearer ${session?.accessToken}`,
},
body: JSON.stringify(bodyData),
});
const data = await response.json();
revalidatePath("/providers");
return parseStringify(data);
} catch (error) {
console.error(error);
return {
error: getErrorMessage(error),
};
}
};
export const checkConnectionProvider = async (formData: FormData) => {
// const session = await auth();
const session = await auth();
const keyServer = process.env.API_BASE_URL;
const providerId = formData.get("id");
const providerId = formData.get("providerId");
const url = new URL(`${keyServer}/providers/${providerId}/connection`);
@@ -162,6 +260,30 @@ export const checkConnectionProvider = async (formData: FormData) => {
method: "POST",
headers: {
Accept: "application/vnd.api+json",
Authorization: `Bearer ${session?.accessToken}`,
},
});
const data = await response.json();
await wait(1000);
revalidatePath("/providers");
return parseStringify(data);
} catch (error) {
return {
error: getErrorMessage(error),
};
}
};
export const deleteCredentials = async (secretId: string) => {
const session = await auth();
const keyServer = process.env.API_BASE_URL;
const url = new URL(`${keyServer}/providers/secrets/${secretId}`);
try {
const response = await fetch(url.toString(), {
method: "DELETE",
headers: {
Authorization: `Bearer ${session?.accessToken}`,
},
});
const data = await response.json();
@@ -190,6 +312,7 @@ export const deleteProvider = async (formData: FormData) => {
},
});
const data = await response.json();
await wait(1000);
revalidatePath("/providers");
return parseStringify(data);
} catch (error) {
+1
View File
@@ -0,0 +1 @@
export * from "./tasks";
+24
View File
@@ -0,0 +1,24 @@
"use server";
import { auth } from "@/auth.config";
import { getErrorMessage, parseStringify } from "@/lib";
export const getTask = async (taskId: string) => {
const session = await auth();
const keyServer = process.env.API_BASE_URL;
const url = new URL(`${keyServer}/tasks/${taskId}`);
try {
const response = await fetch(url.toString(), {
headers: {
Accept: "application/vnd.api+json",
Authorization: `Bearer ${session?.accessToken}`,
},
});
const data = await response.json();
return parseStringify(data);
} catch (error) {
return { error: getErrorMessage(error) };
}
};
+3 -1
View File
@@ -18,6 +18,8 @@ export default async function Findings({
}: {
searchParams: SearchParamsProps;
}) {
const searchParamsKey = JSON.stringify(searchParams || {});
return (
<>
<Header title="Findings" icon="ph:list-checks-duotone" />
@@ -25,7 +27,7 @@ export default async function Findings({
<Spacer y={4} />
<FilterControls search providers date />
<Spacer y={4} />
<Suspense fallback={<SkeletonTableFindings />}>
<Suspense key={searchParamsKey} fallback={<SkeletonTableFindings />}>
<SSRDataTable searchParams={searchParams} />
</Suspense>
</>
+3 -7
View File
@@ -1,17 +1,13 @@
import { Spacer } from "@nextui-org/react";
import { SeverityChart, StatusChart } from "@/components/charts";
import { AttackSurface } from "@/components/overview";
import { Header } from "@/components/ui";
import { CustomBox } from "@/components/ui/custom";
export default function Home() {
return (
<>
<Header title="Scan Overview" icon="solar:pie-chart-2-outline" />
<Spacer y={4} />
<Spacer y={10} />
<div className="grid grid-cols-12 gap-4">
<Spacer y={14} />
{/* <div className="grid grid-cols-12 gap-4">
<CustomBox
preTitle={"Findings by Status"}
className="col-span-12 md:col-span-8 xl:col-span-5"
@@ -30,7 +26,7 @@ export default function Home() {
>
<AttackSurface />
</CustomBox>
</div>
</div> */}
</>
);
}
@@ -0,0 +1,35 @@
import { redirect } from "next/navigation";
import React from "react";
import {
ViaCredentialsForm,
ViaRoleForm,
} from "@/components/providers/workflow/forms";
interface Props {
searchParams: { type: string; id: string; via?: string };
}
export default function AddCredentialsPage({ searchParams }: Props) {
if (
!searchParams.type ||
!searchParams.id ||
(searchParams.type === "aws" && !searchParams.via)
) {
redirect("/providers/connect-account");
}
const useCredentialsForm =
(searchParams.type === "aws" && searchParams.via === "credentials") ||
(searchParams.type !== "aws" && !searchParams.via);
const useRoleForm =
searchParams.type === "aws" && searchParams.via === "role";
return (
<>
{useCredentialsForm && <ViaCredentialsForm searchParams={searchParams} />}
{useRoleForm && <ViaRoleForm searchParams={searchParams} />}
</>
);
}
@@ -0,0 +1,9 @@
"use client";
import React from "react";
import { ConnectAccountForm } from "@/components/providers/workflow/forms";
export default function ConnectAccountPage() {
return <ConnectAccountForm />;
}
@@ -0,0 +1,32 @@
import { redirect } from "next/navigation";
import React from "react";
import { getProvider } from "@/actions/providers";
import { LaunchScanForm } from "@/components/providers/workflow/forms";
interface Props {
searchParams: { type: string; id: string };
}
export default async function LaunchScanPage({ searchParams }: Props) {
const providerId = searchParams.id;
if (!providerId) {
redirect("/providers/connect-account");
}
const formData = new FormData();
formData.append("id", providerId);
const providerData = await getProvider(formData);
const isConnected = providerData?.data?.attributes?.connection?.connected;
if (!isConnected) {
redirect("/providers/connect-account");
}
return (
<LaunchScanForm searchParams={searchParams} providerData={providerData} />
);
}
@@ -0,0 +1,32 @@
import "@/styles/globals.css";
import { Spacer } from "@nextui-org/react";
import React from "react";
import { Workflow } from "@/components/providers/workflow";
import { NavigationHeader } from "@/components/ui";
interface ProviderLayoutProps {
children: React.ReactNode;
}
export default function ProviderLayout({ children }: ProviderLayoutProps) {
return (
<>
<NavigationHeader
title="Connect your cloud account"
icon="icon-park-outline:close-small"
href="/providers"
/>
<Spacer y={16} />
<div className="grid grid-cols-1 gap-8 lg:grid-cols-12">
<div className="order-1 my-auto hidden h-full lg:col-span-4 lg:col-start-2 lg:block">
<Workflow />
</div>
<div className="order-2 my-auto lg:col-span-5 lg:col-start-6">
{children}
</div>
</div>
</>
);
}
@@ -0,0 +1,44 @@
import { redirect } from "next/navigation";
import React, { Suspense } from "react";
import { getProvider } from "@/actions/providers";
import { TestConnectionForm } from "@/components/providers/workflow/forms";
interface Props {
searchParams: { type: string; id: string };
}
export default async function TestConnectionPage({ searchParams }: Props) {
const providerId = searchParams.id;
if (!providerId) {
redirect("/providers/connect-account");
}
return (
<Suspense fallback={<p>Loading...</p>}>
<SSRTestConnection searchParams={searchParams} />
</Suspense>
);
}
async function SSRTestConnection({
searchParams,
}: {
searchParams: { type: string; id: string };
}) {
const formData = new FormData();
formData.append("id", searchParams.id);
const providerData = await getProvider(formData);
if (providerData.errors) {
redirect("/providers/connect-account");
}
return (
<TestConnectionForm
searchParams={searchParams}
providerData={providerData}
/>
);
}
-1
View File
@@ -26,7 +26,6 @@ export default async function Providers({
<Spacer y={4} />
<FilterControls search providers />
<Spacer y={4} />
<AddProvider />
<Spacer y={4} />
@@ -2,12 +2,7 @@
import { ColumnDef } from "@tanstack/react-table";
import {
DataTableColumnHeader,
SeverityBadge,
Status,
StatusBadge,
} from "@/components/ui/table";
import { SeverityBadge, Status, StatusBadge } from "@/components/ui/table";
import { FindingProps } from "@/types";
import { DataTableRowActions } from "./data-table-row-actions";
@@ -20,7 +15,6 @@ const statusMap: Record<"PASS" | "FAIL" | "MANUAL" | "MUTED", Status> = {
};
const getFindingsData = (row: { original: FindingProps }) => {
console.log(row.original);
return row.original;
};
@@ -94,7 +88,7 @@ export const ColumnFindings: ColumnDef<FindingProps>[] = [
},
{
accessorKey: "status",
header: "Scan Status",
header: "Status",
cell: ({ row }) => {
const {
attributes: { status },
@@ -10,7 +10,6 @@ import {
} from "@nextui-org/react";
import {
// AddNoteBulkIcon,
DeleteDocumentBulkIcon,
EditDocumentBulkIcon,
} from "@nextui-org/shared-icons";
import { Row } from "@tanstack/react-table";
@@ -31,10 +30,8 @@ const iconClasses =
export function DataTableRowActions<FindingProps>({
row,
}: DataTableRowActionsProps<FindingProps>) {
// const [isEditOpen, setIsEditOpen] = useState(false);
// const [isDeleteOpen, setIsDeleteOpen] = useState(false);
// const providerId = (row.original as { id: string }).id;
// const providerAlias = (row.original as any).attributes?.alias;
const findingId = (row.original as { id: string }).id;
console.log(findingId);
return (
<>
{/* <CustomAlertModal
+27 -102
View File
@@ -201,108 +201,6 @@ export const VerticalDotsIcon: React.FC<IconSvgProps> = ({
</g>
</svg>
);
export const WifiIcon: React.FC<IconSvgProps> = ({
size = 24,
width,
height,
...props
}) => (
<svg
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
fill="none"
focusable="false"
height={size || height}
role="presentation"
viewBox="0 0 48 48"
width={size || width}
{...props}
>
<g fill="none">
<path
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="4"
d="M4 18.965a29.355 29.355 0 0 1 1.817-1.586C17.037 8.374 33.382 8.903 44 18.965"
/>
<path
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="4"
d="M38 25.799c-7.732-7.732-20.268-7.732-28 0m22 6.515c-4.418-4.419-11.582-4.419-16 0"
/>
<path
fill="currentColor"
fillRule="evenodd"
d="M24 40a2.5 2.5 0 1 0 0-5a2.5 2.5 0 0 0 0 5"
clipRule="evenodd"
/>
</g>
</svg>
);
export const WifiOffIcon: React.FC<IconSvgProps> = ({
size = 24,
width,
height,
...props
}) => (
<svg
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
fill="none"
focusable="false"
height={size || height}
role="presentation"
viewBox="0 0 24 24"
width={size || width}
{...props}
>
<path
fill="none"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M17.85 11.544a8 8 0 0 0-2.88-1.972m5.806-.756a12 12 0 0 0-9.488-3.795m-2.945 9.57a5 5 0 0 1 4.902-1.434m-7.096-1.613A8 8 0 0 1 9.623 9.36m-6.4-.545a12 12 0 0 1 3.11-2.393M4.413 4l14.142 14.142M12 19a1 1 0 1 1 0-2a1 1 0 0 1 0 2"
/>
</svg>
);
export const WifiPendingIcon: React.FC<IconSvgProps> = ({
size = 24,
width,
height,
...props
}) => (
<svg
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
fill="none"
focusable="false"
height={size || height}
role="presentation"
viewBox="0 0 24 24"
width={size || width}
{...props}
>
<path
fill="currentColor"
d="M22.59 10.39L24 8.98A16.88 16.88 0 0 0 12 4C7.31 4 3.07 5.9 0 8.98L12 21l1.41-1.42L2.93 9.08C5.45 7.16 8.59 6 12 6c4.13 0 7.88 1.68 10.59 4.39"
/>
<path
fill="currentColor"
d="m23 18.59-2.56-2.56c.35-.59.56-1.28.56-2.03c0-2.24-1.76-4-4-4s-4 1.76-4 4s1.76 4 4 4c.75 0 1.44-.21 2.03-.56L21.59 20zM15 14c0-1.12.88-2 2-2s2 .88 2 2s-.88 2-2 2s-2-.88-2-2"
/>
<path
fill="currentColor"
d="M22.59 10.39A14.943 14.943 0 0 0 12 6C8.59 6 5.45 7.16 2.93 9.08l2.26 2.26l8.24 8.24l.46-.46C12.15 18.09 11 16.21 11 14c0-1.62.62-3.13 1.75-4.25S15.38 8 17 8c2.21 0 4.09 1.15 5.13 2.89l.49-.49l-.02-.02z"
opacity="0.3"
/>
</svg>
);
export const DeleteIcon: React.FC<IconSvgProps> = ({
size,
@@ -860,3 +758,30 @@ export const AddIcon: React.FC<IconSvgProps> = ({
</svg>
);
};
export const ScheduleIcon: React.FC<IconSvgProps> = ({
size,
height,
width,
...props
}) => {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width={size || width || 24}
height={size || height || 24}
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
{...props}
>
<path d="M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5" />
<path d="M16 2v4M8 2v4M3 10h5" />
<path d="M17.5 17.5L16 16.3V14" />
<circle cx="16" cy="16" r="6" />
</svg>
);
};
@@ -1,42 +0,0 @@
"use client";
import { useRef } from "react";
import { checkConnectionProvider } from "@/actions/providers";
import { CustomButtonClientAction } from "../ui/custom";
import { useToast } from "../ui/toast";
export const CheckConnectionProvider = ({ id }: { id: string }) => {
const ref = useRef<HTMLFormElement>(null);
const { toast } = useToast();
async function clientAction(formData: FormData) {
// reset the form
ref.current?.reset();
// client-side validation
const data = await checkConnectionProvider(formData);
if (data?.errors && data.errors.length > 0) {
const error = data.errors[0];
const errorMessage = `${error.detail}`;
// show error
toast({
variant: "destructive",
title: "Oops! Something went wrong",
description: errorMessage,
});
} else {
toast({
title: "Checking",
description: "The task was launched successfully",
});
}
}
return (
<form ref={ref} action={clientAction} className="flex gap-x-2">
<input type="hidden" name="id" value={id} />
<CustomButtonClientAction buttonLabel="Check connection" />
</form>
);
};
+12 -30
View File
@@ -1,39 +1,21 @@
"use client";
import { useState } from "react";
import { AddIcon } from "../icons";
import { CustomAlertModal, CustomButton } from "../ui/custom";
import { AddForm } from "./forms";
import { CustomButton } from "../ui/custom";
export const AddProvider = () => {
const [isAddOpen, setIsAddOpen] = useState(false);
return (
<>
<CustomAlertModal
isOpen={isAddOpen}
onOpenChange={setIsAddOpen}
title="Add Cloud Provider"
description={
"You must manually deploy a new read-only IAM role for each account you want to add. The following links will provide detailed instructions how to do this:"
}
<div className="flex w-full items-center justify-end">
<CustomButton
asLink="/providers/connect-account"
ariaLabel="Add Account"
variant="solid"
color="action"
size="md"
endContent={<AddIcon size={20} />}
>
<AddForm setIsOpen={setIsAddOpen} />
</CustomAlertModal>
<div className="flex w-full items-center justify-end">
<CustomButton
ariaLabel="Add Account"
variant="solid"
color="action"
size="md"
onPress={() => setIsAddOpen(true)}
endContent={<AddIcon size={20} />}
>
Add Account
</CustomButton>
</div>
</>
Add Account
</CustomButton>
</div>
);
};
-127
View File
@@ -1,127 +0,0 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { Dispatch, SetStateAction } from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { addProvider } from "@/actions/providers";
import { SaveIcon } from "@/components/icons";
import { useToast } from "@/components/ui";
import { CustomButton, CustomInput } from "@/components/ui/custom";
import { Form } from "@/components/ui/form";
import { addProviderFormSchema } from "@/types";
import { RadioGroupProvider } from "../radio-group-provider";
export const AddForm = ({
setIsOpen,
}: {
setIsOpen: Dispatch<SetStateAction<boolean>>;
}) => {
const formSchema = addProviderFormSchema;
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
providerType: "",
providerId: "",
providerAlias: "",
},
});
const { toast } = useToast();
const isLoading = form.formState.isSubmitting;
const onSubmitClient = async (values: z.infer<typeof formSchema>) => {
const formData = new FormData();
Object.entries(values).forEach(
([key, value]) => value !== undefined && formData.append(key, value),
);
const data = await addProvider(formData);
if (data?.errors && data.errors.length > 0) {
const error = data.errors[0];
const errorMessage = `${error.detail}`;
// show error
toast({
variant: "destructive",
title: "Oops! Something went wrong",
description: errorMessage,
});
} else {
toast({
title: "Success!",
description: "The provider was updated successfully.",
});
setIsOpen(false); // Close the modal on success
}
};
return (
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmitClient)}
className="flex flex-col space-y-4"
>
<RadioGroupProvider
control={form.control}
isInvalid={!!form.formState.errors.providerType}
/>
<CustomInput
control={form.control}
name="providerId"
type="text"
label="Provider ID"
labelPlacement="inside"
placeholder={"Enter the provider ID"}
variant="bordered"
isRequired
isInvalid={!!form.formState.errors.providerId}
/>
<CustomInput
control={form.control}
name="providerAlias"
type="text"
label="Alias"
labelPlacement="inside"
placeholder={"Enter the provider alias"}
variant="bordered"
isRequired={false}
isInvalid={!!form.formState.errors.providerAlias}
/>
<div className="flex w-full justify-center sm:space-x-6">
<CustomButton
type="button"
ariaLabel="Cancel"
className="w-full bg-transparent"
variant="faded"
size="lg"
radius="lg"
onPress={() => setIsOpen(false)}
isDisabled={isLoading}
>
<span>Cancel</span>
</CustomButton>
<CustomButton
type="submit"
ariaLabel="Confirm"
className="w-full"
variant="solid"
color="action"
size="lg"
isLoading={isLoading}
startContent={!isLoading && <SaveIcon size={24} />}
>
{isLoading ? <>Loading</> : <span>Confirm</span>}
</CustomButton>
</div>
</form>
</Form>
);
};
-1
View File
@@ -1,3 +1,2 @@
export * from "./add-form";
export * from "./delete-form";
export * from "./edit-form";
-1
View File
@@ -1,5 +1,4 @@
export * from "./add-provider";
export * from "./CheckConnectionProvider";
export * from "./forms/delete-form";
export * from "./provider-info";
export * from "./radio-group-provider";
+14 -53
View File
@@ -1,7 +1,6 @@
"use client";
import { UseRadioProps } from "@nextui-org/radio/dist/use-radio";
import { cn, RadioGroup, useRadio, VisuallyHidden } from "@nextui-org/react";
import { RadioGroup } from "@nextui-org/react";
import React from "react";
import { Control, Controller } from "react-hook-form";
import { z } from "zod";
@@ -11,61 +10,19 @@ import { addProviderFormSchema } from "@/types";
import { AWSProviderBadge, AzureProviderBadge } from "../icons/providers-badge";
import { GCPProviderBadge } from "../icons/providers-badge/GCPProviderBadge";
import { KS8ProviderBadge } from "../icons/providers-badge/KS8ProviderBadge";
import { CustomRadio } from "../ui/custom";
import { FormMessage } from "../ui/form";
interface CustomRadioProps extends UseRadioProps {
description?: string;
children?: React.ReactNode;
}
export const CustomRadio: React.FC<CustomRadioProps> = (props) => {
const {
Component,
children,
// description,
getBaseProps,
getWrapperProps,
getInputProps,
getLabelProps,
getLabelWrapperProps,
getControlProps,
} = useRadio(props);
return (
<Component
{...getBaseProps()}
className={cn(
"group inline-flex flex-row-reverse items-center justify-between tap-highlight-transparent hover:opacity-70 active:opacity-50",
"max-w-full cursor-pointer gap-4 rounded-lg border-2 border-default p-4",
"data-[selected=true]:border-primar w-full",
)}
>
<VisuallyHidden>
<input {...getInputProps()} />
</VisuallyHidden>
<span {...getWrapperProps()}>
<span {...getControlProps()} />
</span>
<div {...getLabelWrapperProps()}>
{children && <span {...getLabelProps()}>{children}</span>}
{/* {description && (
<span className="text-small text-foreground opacity-70">
{description}
</span>
)} */}
</div>
</Component>
);
};
interface RadioGroupProviderProps {
control: Control<z.infer<typeof addProviderFormSchema>>;
isInvalid: boolean;
errorMessage?: string;
}
export const RadioGroupProvider: React.FC<RadioGroupProviderProps> = ({
control,
isInvalid,
errorMessage,
}) => {
return (
<Controller
@@ -75,27 +32,27 @@ export const RadioGroupProvider: React.FC<RadioGroupProviderProps> = ({
<>
<RadioGroup
className="flex flex-wrap"
label="Select one provider"
isInvalid={isInvalid}
{...field}
value={field.value || ""}
>
<div className="grid grid-cols-2 gap-4">
<div className="flex flex-col gap-4">
<CustomRadio description="Amazon Web Services" value="aws">
<div className="flex items-center">
<AWSProviderBadge size={26} />
<span className="ml-2">AWS</span>
<span className="ml-2">Amazon Web Services</span>
</div>
</CustomRadio>
<CustomRadio description="Google Cloud Platform" value="gcp">
<div className="flex items-center">
<GCPProviderBadge size={26} />
<span className="ml-2">GCP</span>
<span className="ml-2">Google Cloud Platform</span>
</div>
</CustomRadio>
<CustomRadio description="Microsoft Azure" value="azure">
<div className="flex items-center">
<AzureProviderBadge size={26} />
<span className="ml-2">Azure</span>
<span className="ml-2">Microsoft Azure</span>
</div>
</CustomRadio>
<CustomRadio description="Kubernetes" value="kubernetes">
@@ -106,7 +63,11 @@ export const RadioGroupProvider: React.FC<RadioGroupProviderProps> = ({
</CustomRadio>
</div>
</RadioGroup>
<FormMessage className="text-system-error dark:text-system-error" />
{errorMessage && (
<FormMessage className="text-system-error dark:text-system-error">
{errorMessage}
</FormMessage>
)}
</>
)}
/>
@@ -20,7 +20,6 @@ import { useState } from "react";
import { VerticalDotsIcon } from "@/components/icons";
import { CustomAlertModal } from "@/components/ui/custom";
import { CheckConnectionProvider } from "../CheckConnectionProvider";
import { EditForm } from "../forms";
import { DeleteForm } from "../forms/delete-form";
@@ -36,6 +35,7 @@ export function DataTableRowActions<ProviderProps>({
const [isEditOpen, setIsEditOpen] = useState(false);
const [isDeleteOpen, setIsDeleteOpen] = useState(false);
const providerId = (row.original as { id: string }).id;
const providerType = (row.original as any).attributes?.provider;
const providerAlias = (row.original as any).attributes?.alias;
return (
<>
@@ -75,12 +75,13 @@ export function DataTableRowActions<ProviderProps>({
>
<DropdownSection title="Actions">
<DropdownItem
href={`/providers/test-connection?type=${providerType}&id=${providerId}`}
key="new"
description="Check the connection to the provider"
textValue="Check Connection"
startContent={<AddNoteBulkIcon className={iconClasses} />}
>
<CheckConnectionProvider id={providerId} />
Test Connection
</DropdownItem>
<DropdownItem
key="edit"
@@ -0,0 +1,224 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { ChevronLeftIcon, ChevronRightIcon, SaveIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { useToast } from "@/components/ui";
import { CustomButton, CustomInput } from "@/components/ui/custom";
import { Form } from "@/components/ui/form";
import { addProvider } from "../../../../actions/providers/providers";
import { addProviderFormSchema, ApiError } from "../../../../types";
import { RadioGroupProvider } from "../../radio-group-provider";
import { RadioGroupAWSViaCredentialsForm } from "./radio-group-aws-via-credentials-form";
export type FormValues = z.infer<typeof addProviderFormSchema>;
export const ConnectAccountForm = () => {
const { toast } = useToast();
const [prevStep, setPrevStep] = useState(1);
const router = useRouter();
const formSchema = addProviderFormSchema;
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
defaultValues: {
providerType: undefined,
providerUid: "",
providerAlias: "",
awsCredentialsType: "",
},
});
const providerType = form.watch("providerType");
const isLoading = form.formState.isSubmitting;
const onSubmitClient = async (values: FormValues) => {
const formValues = { ...values };
// If providerAlias is empty, set default value
if (!formValues.providerAlias.trim()) {
const date = new Date();
const month = (date.getMonth() + 1).toString().padStart(2, "0");
const day = date.getDate().toString().padStart(2, "0");
const year = date.getFullYear();
formValues.providerAlias = `${formValues.providerType}:${month}/${day}/${year}`;
}
const formData = new FormData();
Object.entries(formValues).forEach(
([key, value]) => value !== undefined && formData.append(key, value),
);
const data = await addProvider(formData);
if (data?.errors && data.errors.length > 0) {
data.errors.forEach((error: ApiError) => {
const errorMessage = error.detail;
switch (error.source.pointer) {
case "/data/attributes/provider":
form.setError("providerType", {
type: "server",
message: errorMessage,
});
break;
case "/data/attributes/uid":
case "/data/attributes/__all__":
form.setError("providerUid", {
type: "server",
message: errorMessage,
});
break;
case "/data/attributes/alias":
form.setError("providerAlias", {
type: "server",
message: errorMessage,
});
break;
default:
toast({
variant: "destructive",
title: "Oops! Something went wrong",
description: errorMessage,
});
}
});
setPrevStep(1);
} else {
const {
id,
attributes: { provider: providerType },
} = data.data;
const credentialsParam = values.awsCredentialsType
? `&via=${values.awsCredentialsType}`
: "";
router.push(
`/providers/add-credentials?type=${providerType}&id=${id}${credentialsParam}`,
);
}
};
const handleNextStep = () => {
setPrevStep((prev) => prev + 1);
};
const handleBackStep = () => {
setPrevStep((prev) => prev - 1);
};
return (
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmitClient)}
className="flex flex-col space-y-4"
>
{prevStep === 1 && (
<>
{/* Select a provider */}
<RadioGroupProvider
control={form.control}
isInvalid={!!form.formState.errors.providerType}
errorMessage={form.formState.errors.providerType?.message}
/>
{/* Provider UID */}
<CustomInput
control={form.control}
name="providerUid"
type="text"
label="Provider UID"
labelPlacement="inside"
placeholder={"Enter the provider UID"}
variant="bordered"
isRequired
isInvalid={!!form.formState.errors.providerUid}
/>
{/* Provider alias */}
<CustomInput
control={form.control}
name="providerAlias"
type="text"
label="Provider alias (optional)"
labelPlacement="inside"
placeholder={"Enter the provider alias"}
variant="bordered"
isRequired={false}
isInvalid={!!form.formState.errors.providerAlias}
/>
</>
)}
{prevStep === 2 && (
<>
{/* Select AWS credentials type */}
<RadioGroupAWSViaCredentialsForm
control={form.control}
isInvalid={!!form.formState.errors.awsCredentialsType}
errorMessage={form.formState.errors.awsCredentialsType?.message}
/>
</>
)}
<div className="flex w-full justify-end sm:space-x-6">
{prevStep === 2 && (
<CustomButton
type="button"
ariaLabel="Back"
className="w-1/2 bg-transparent"
variant="faded"
size="lg"
radius="lg"
onPress={handleBackStep}
startContent={!isLoading && <ChevronLeftIcon size={24} />}
isDisabled={isLoading}
>
<span>Back</span>
</CustomButton>
)}
<CustomButton
type="button"
ariaLabel={
prevStep === 1 && providerType === "aws" ? "Next" : "Save"
}
className="w-1/2"
variant="solid"
color="action"
size="lg"
isLoading={isLoading}
startContent={
!isLoading &&
!(prevStep === 1 && providerType === "aws") && (
<SaveIcon size={24} />
)
}
endContent={
!isLoading &&
prevStep === 1 &&
providerType === "aws" && <ChevronRightIcon size={24} />
}
onPress={() => {
if (prevStep === 1 && providerType === "aws") {
handleNextStep();
} else {
form.handleSubmit(onSubmitClient)();
}
}}
>
{isLoading ? (
<>Loading</>
) : (
<span>
{prevStep === 1 && providerType === "aws" ? "Next" : "Save"}
</span>
)}
</CustomButton>
</div>
</form>
</Form>
);
};
@@ -0,0 +1,6 @@
export * from "./connect-account-form";
export * from "./launch-scan-form";
export * from "./radio-group-aws-via-credentials-form";
export * from "./test-connection-form";
export * from "./via-credentials-form";
export * from "./via-role-form";
@@ -0,0 +1,149 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { scanOnDemand } from "@/actions/scans/scans";
import { RocketIcon, ScheduleIcon } from "@/components/icons";
import { CustomButton } from "@/components/ui/custom";
import { Form } from "@/components/ui/form";
import { ProviderProps } from "@/types"; // Asegúrate de importar la interfaz correcta
import { launchScanFormSchema } from "@/types/formSchemas";
import { ProviderInfo } from "../../provider-info";
type FormValues = z.infer<ReturnType<typeof launchScanFormSchema>>;
interface LaunchScanFormProps {
searchParams: { type: string; id: string };
providerData: {
data: {
type: string;
id: string;
attributes: ProviderProps["attributes"];
};
};
}
export const LaunchScanForm = ({
searchParams,
providerData,
}: LaunchScanFormProps) => {
const providerType = searchParams.type;
const providerId = searchParams.id;
const [apiErrorMessage, setApiErrorMessage] = useState<string | null>(null);
const router = useRouter();
const formSchema = launchScanFormSchema();
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
defaultValues: {
providerId,
providerType,
scannerArgs: {
checksToExecute: [],
},
},
});
const isLoading = form.formState.isSubmitting;
const onSubmitClient = async (values: FormValues) => {
const formData = new FormData();
formData.append("providerId", values.providerId);
// Generate default scan name using provider type and current date
const date = new Date();
const month = (date.getMonth() + 1).toString().padStart(2, "0");
const day = date.getDate().toString().padStart(2, "0");
const year = date.getFullYear();
const defaultScanName = `${providerType}:${month}/${day}/${year}`;
formData.append("scanName", defaultScanName);
try {
const data = await scanOnDemand(formData);
if (data.error) {
setApiErrorMessage(data.error);
form.setError("providerId", {
type: "server",
message: data.error,
});
} else {
router.push("/scans");
}
} catch (error) {
form.setError("providerId", {
type: "server",
message: "An unexpected error occurred. Please try again.",
});
}
};
return (
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmitClient)}
className="flex flex-col space-y-4"
>
<div className="text-left">
<div className="text-2xl font-bold leading-9 text-default-foreground">
Launch scan
</div>
<div className="py-2 text-default-500">
Launch the scan now or schedule it for a later date and time.
</div>
</div>
{apiErrorMessage && (
<div className="mt-4 rounded-md bg-red-100 p-3 text-red-700">
<p>{apiErrorMessage.toLowerCase()}</p>
</div>
)}
<ProviderInfo
connected={providerData.data.attributes.connection.connected}
provider={providerData.data.attributes.provider}
providerAlias={providerData.data.attributes.alias}
/>
<input type="hidden" name="providerId" value={providerId} />
<input type="hidden" name="providerType" value={providerType} />
<div className="flex w-full justify-end sm:space-x-6">
<CustomButton
type="submit"
ariaLabel={"Save"}
className="w-1/2"
variant="solid"
color="action"
size="lg"
isLoading={isLoading}
startContent={!isLoading && <ScheduleIcon size={24} />}
isDisabled={true}
>
<span>Schedule</span>
</CustomButton>
<CustomButton
type="submit"
ariaLabel={"Save"}
className="w-1/2"
variant="solid"
color="action"
size="lg"
isLoading={isLoading}
endContent={!isLoading && <RocketIcon size={24} />}
>
{isLoading ? <>Loading</> : <span>Start now</span>}
</CustomButton>
</div>
</form>
</Form>
);
};
@@ -0,0 +1,64 @@
"use client";
import { RadioGroup } from "@nextui-org/react";
import React from "react";
import { Control, Controller } from "react-hook-form";
import { CustomRadio } from "@/components/ui/custom";
import { FormMessage } from "@/components/ui/form";
import { FormValues } from "./connect-account-form";
type RadioGroupAWSViaCredentialsFormProps = {
control: Control<FormValues>;
isInvalid: boolean;
errorMessage?: string;
};
export const RadioGroupAWSViaCredentialsForm = ({
control,
isInvalid,
errorMessage,
}: RadioGroupAWSViaCredentialsFormProps) => {
return (
<Controller
name="awsCredentialsType"
control={control}
render={({ field }) => (
<>
<RadioGroup
className="flex flex-wrap"
isInvalid={isInvalid}
{...field}
value={field.value || ""}
>
<div className="flex flex-col gap-4">
<span className="text-sm text-default-500">Using IAM Role</span>
<CustomRadio description="Connect assuming IAM Role" value="role">
<div className="flex items-center">
<span className="ml-2">Connect assuming IAM Role</span>
</div>
</CustomRadio>
<span className="text-sm text-default-500">
Using Credentials
</span>
<CustomRadio
description="Connect via Credentials"
value="credentials"
>
<div className="flex items-center">
<span className="ml-2">Connect via Credentials</span>
</div>
</CustomRadio>
</div>
</RadioGroup>
{errorMessage && (
<FormMessage className="text-system-error dark:text-system-error">
{errorMessage}
</FormMessage>
)}
</>
)}
/>
);
};
@@ -0,0 +1,268 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { Icon } from "@iconify/react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import {
checkConnectionProvider,
deleteCredentials,
} from "@/actions/providers";
import { getTask } from "@/actions/task/tasks";
import { CheckIcon, SaveIcon } from "@/components/icons";
import { useToast } from "@/components/ui";
import { CustomButton } from "@/components/ui/custom";
import { Form } from "@/components/ui/form";
import { checkTaskStatus } from "@/lib/helper";
import { ApiError, testConnectionFormSchema } from "@/types";
import { ProviderInfo } from "../..";
type FormValues = z.infer<typeof testConnectionFormSchema>;
export const TestConnectionForm = ({
searchParams,
providerData,
}: {
searchParams: { type: string; id: string };
providerData: {
data: {
id: string;
type: string;
attributes: {
connection: {
connected: boolean | null;
last_checked_at: string | null;
};
provider: "aws" | "azure" | "gcp" | "kubernetes";
alias: string;
scanner_args: Record<string, any>;
};
relationships: {
secret: {
data: {
type: string;
id: string;
} | null;
};
};
};
};
}) => {
const { toast } = useToast();
const router = useRouter();
const providerType = searchParams.type;
const providerId = searchParams.id;
console.log({ providerData }, "providerData from test connection form");
const formSchema = testConnectionFormSchema;
const [apiErrorMessage, setApiErrorMessage] = useState<string | null>(null);
const [connectionStatus, setConnectionStatus] = useState<{
connected: boolean;
error: string | null;
} | null>(null);
const [isResettingCredentials, setIsResettingCredentials] = useState(false);
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
defaultValues: {
providerId,
},
});
const isLoading = form.formState.isSubmitting;
const onSubmitClient = async (values: FormValues) => {
console.log({ values }, "values from test connection form");
const formData = new FormData();
formData.append("providerId", values.providerId);
const data = await checkConnectionProvider(formData);
if (data?.errors && data.errors.length > 0) {
data.errors.forEach((error: ApiError) => {
const errorMessage = error.detail;
switch (errorMessage) {
case "Not found.":
setApiErrorMessage(errorMessage);
break;
default:
toast({
variant: "destructive",
title: `Error ${error.status}`,
description: errorMessage,
});
}
});
} else {
const taskId = data.data.id;
setApiErrorMessage(null);
// Use the helper function to check the task status
const taskResult = await checkTaskStatus(taskId);
if (taskResult.completed) {
const task = await getTask(taskId);
const { connected, error } = task.data.attributes.result;
setConnectionStatus({
connected,
error: connected ? null : error || "Unknown error",
});
if (connected) {
router.push(
`/providers/launch-scan?type=${providerType}&id=${providerId}`,
);
} else {
setConnectionStatus({
connected: false,
error: error || "Connection failed, please review credentials.",
});
}
} else {
setConnectionStatus({
connected: false,
error: taskResult.error || "Unknown error",
});
}
}
};
const onResetCredentials = async () => {
setIsResettingCredentials(true);
// Check if provider the provider has no credentials
const providerSecretId =
providerData?.data?.relationships?.secret?.data?.id;
const hasNoCredentials = !providerSecretId;
if (hasNoCredentials) {
// If no credentials, redirect to add credentials page
router.push(
`/providers/add-credentials?type=${providerType}&id=${providerId}`,
);
return;
}
// If provider has credentials, delete them first
try {
await deleteCredentials(providerSecretId);
// After successful deletion, redirect to add credentials page
router.push(
`/providers/add-credentials?type=${providerType}&id=${providerId}`,
);
} catch (error) {
console.error("Failed to delete credentials:", error);
} finally {
setIsResettingCredentials(false);
}
};
return (
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmitClient)}
className="flex flex-col space-y-4"
>
<div className="text-left">
<div className="text-2xl font-bold leading-9 text-default-foreground">
Test connection
</div>
<p className="py-2 text-default-500">
Ensure all required credentials and configurations are completed
accurately. A successful connection will enable the option to
initiate a scan in the following step.
</p>
</div>
{apiErrorMessage && (
<div className="mt-4 rounded-md bg-red-100 p-3 text-danger">
<p>{`Provider ID ${apiErrorMessage.toLowerCase()}. Please check and try again.`}</p>
</div>
)}
{connectionStatus && !connectionStatus.connected && (
<>
<div className="flex items-center gap-4 rounded-lg border border-red-200 bg-red-50 p-4">
<div className="flex items-center">
<Icon
icon="heroicons:exclamation-circle"
className="h-5 w-5 text-danger"
/>
</div>
<div className="flex items-center">
<p className="text-danger">
{connectionStatus.error || "Unknown error"}
</p>
</div>
</div>
<p className="text-md text-danger">
It seems there was an issue with your credentials. Please review
your credentials and try again.
</p>
</>
)}
<ProviderInfo
connected={providerData.data.attributes.connection.connected}
provider={providerData.data.attributes.provider}
providerAlias={providerData.data.attributes.alias}
/>
<input type="hidden" name="providerId" value={providerId} />
<div className="flex w-full justify-end sm:space-x-6">
{apiErrorMessage ? (
<Link
href="/providers"
className="mr-3 flex w-fit items-center justify-center space-x-2 rounded-lg border border-solid border-gray-200 px-4 py-2 hover:bg-gray-200 dark:hover:bg-gray-700"
>
<Icon
icon="icon-park-outline:close-small"
className="h-5 w-5 text-gray-600 dark:text-gray-400"
/>
<span>Back to providers</span>
</Link>
) : connectionStatus?.error ? (
<CustomButton
onPress={onResetCredentials}
type="button"
ariaLabel={"Save"}
className="w-1/2"
variant="solid"
color="warning"
size="lg"
isLoading={isResettingCredentials}
startContent={!isResettingCredentials && <CheckIcon size={24} />}
isDisabled={isResettingCredentials}
>
{isResettingCredentials ? (
<>Loading</>
) : (
<span>Reset credentials</span>
)}
</CustomButton>
) : (
<CustomButton
type="submit"
ariaLabel={"Save"}
className="w-1/2"
variant="solid"
color="action"
size="lg"
isLoading={isLoading}
startContent={!isLoading && <SaveIcon size={24} />}
>
{isLoading ? <>Loading</> : <span>Test connection</span>}
</CustomButton>
)}
</div>
</form>
</Form>
);
};
@@ -0,0 +1,207 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { SaveIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { Control, useForm } from "react-hook-form";
import * as z from "zod";
import { addCredentialsProvider } from "@/actions/providers/providers";
import { useToast } from "@/components/ui";
import { CustomButton } from "@/components/ui/custom";
import { Form } from "@/components/ui/form";
import {
addCredentialsFormSchema,
ApiError,
AWSCredentials,
AzureCredentials,
GCPCredentials,
KubernetesCredentials,
} from "@/types";
import { AWScredentialsForm } from "./via-credentials/aws-credentials-form";
import { AzureCredentialsForm } from "./via-credentials/azure-credentials-form";
import { GCPcredentialsForm } from "./via-credentials/gcp-credentials-form";
import { KubernetesCredentialsForm } from "./via-credentials/k8s-credentials-form";
type CredentialsFormSchema = z.infer<
ReturnType<typeof addCredentialsFormSchema>
>;
// Add this type intersection to include all fields
type FormType = CredentialsFormSchema &
AWSCredentials &
AzureCredentials &
GCPCredentials &
KubernetesCredentials;
export const ViaCredentialsForm = ({
searchParams,
}: {
searchParams: { type: string; id: string };
}) => {
const router = useRouter();
const { toast } = useToast();
const providerType = searchParams.type;
const providerId = searchParams.id;
const formSchema = addCredentialsFormSchema(providerType);
const form = useForm<FormType>({
resolver: zodResolver(formSchema),
defaultValues: {
providerId,
providerType,
...(providerType === "aws"
? {
aws_access_key_id: "",
aws_secret_access_key: "",
aws_session_token: "",
}
: providerType === "azure"
? {
client_id: "",
client_secret: "",
tenant_id: "",
}
: providerType === "gcp"
? {
client_id: "",
client_secret: "",
refresh_token: "",
}
: providerType === "kubernetes"
? {
kubeconfig_content: "",
}
: {}),
},
});
const isLoading = form.formState.isSubmitting;
const onSubmitClient = async (values: FormType) => {
console.log("via credentials form", values);
const formData = new FormData();
Object.entries(values).forEach(
([key, value]) => value !== undefined && formData.append(key, value),
);
const data = await addCredentialsProvider(formData);
if (data?.errors && data.errors.length > 0) {
data.errors.forEach((error: ApiError) => {
const errorMessage = error.detail;
switch (error.source.pointer) {
case "/data/attributes/secret/aws_access_key_id":
form.setError("aws_access_key_id", {
type: "server",
message: errorMessage,
});
break;
case "/data/attributes/secret/aws_secret_access_key":
form.setError("aws_secret_access_key", {
type: "server",
message: errorMessage,
});
break;
case "/data/attributes/secret/aws_session_token":
form.setError("aws_session_token", {
type: "server",
message: errorMessage,
});
break;
case "/data/attributes/secret/client_id":
form.setError("client_id", {
type: "server",
message: errorMessage,
});
break;
case "/data/attributes/secret/client_secret":
form.setError("client_secret", {
type: "server",
message: errorMessage,
});
break;
case "/data/attributes/secret/tenant_id":
form.setError("tenant_id", {
type: "server",
message: errorMessage,
});
break;
case "/data/attributes/secret/kubeconfig_content":
form.setError("kubeconfig_content", {
type: "server",
message: errorMessage,
});
break;
case "/data/attributes/name":
form.setError("secretName", {
type: "server",
message: errorMessage,
});
break;
default:
toast({
variant: "destructive",
title: "Oops! Something went wrong",
description: errorMessage,
});
}
});
} else {
router.push(
`/providers/test-connection?type=${providerType}&id=${providerId}`,
);
}
};
return (
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmitClient)}
className="flex flex-col space-y-4"
>
<input type="hidden" name="providerId" value={providerId} />
<input type="hidden" name="providerType" value={providerType} />
{providerType === "aws" && (
<AWScredentialsForm
control={form.control as unknown as Control<AWSCredentials>}
/>
)}
{providerType === "azure" && (
<AzureCredentialsForm
control={form.control as unknown as Control<AzureCredentials>}
/>
)}
{providerType === "gcp" && (
<GCPcredentialsForm
control={form.control as unknown as Control<GCPCredentials>}
/>
)}
{providerType === "kubernetes" && (
<KubernetesCredentialsForm
control={form.control as unknown as Control<KubernetesCredentials>}
/>
)}
<div className="flex w-full justify-end sm:space-x-6">
<CustomButton
type="submit"
ariaLabel={"Save"}
className="w-1/2"
variant="solid"
color="action"
size="lg"
isLoading={isLoading}
startContent={!isLoading && <SaveIcon size={24} />}
>
{isLoading ? <>Loading</> : <span>Save</span>}
</CustomButton>
</div>
</form>
</Form>
);
};
@@ -0,0 +1,56 @@
import { Control } from "react-hook-form";
import { CustomInput } from "@/components/ui/custom";
import { AWSCredentials } from "@/types";
export const AWScredentialsForm = ({
control,
}: {
control: Control<AWSCredentials>;
}) => {
return (
<>
<div className="text-left">
<div className="text-2xl font-bold leading-9 text-default-foreground">
Connect via Credentials
</div>
<div className="py-2 text-default-500">
Please provide the information for your AWS credentials.
</div>
</div>
<CustomInput
control={control}
name="aws_access_key_id"
type="password"
label="AWS Access Key ID"
labelPlacement="inside"
placeholder="Enter the AWS Access Key ID"
variant="bordered"
isRequired
isInvalid={!!control._formState.errors.aws_access_key_id}
/>
<CustomInput
control={control}
name="aws_secret_access_key"
type="password"
label="AWS Secret Access Key"
labelPlacement="inside"
placeholder="Enter the AWS Secret Access Key"
variant="bordered"
isRequired
isInvalid={!!control._formState.errors.aws_secret_access_key}
/>
<CustomInput
control={control}
name="aws_session_token"
type="password"
label="AWS Session Token"
labelPlacement="inside"
placeholder="Enter the AWS Session Token"
variant="bordered"
isRequired={false}
isInvalid={!!control._formState.errors.aws_session_token}
/>
</>
);
};
@@ -0,0 +1,56 @@
import { Control } from "react-hook-form";
import { CustomInput } from "@/components/ui/custom";
import { AzureCredentials } from "@/types";
export const AzureCredentialsForm = ({
control,
}: {
control: Control<AzureCredentials>;
}) => {
return (
<>
<div className="text-left">
<div className="text-2xl font-bold leading-9 text-default-foreground">
Connect via Credentials
</div>
<div className="py-2 text-default-500">
Please provide the information for your Azure credentials.
</div>
</div>
<CustomInput
control={control}
name="client_id"
type="text"
label="Client ID"
labelPlacement="inside"
placeholder="Enter the Client ID"
variant="bordered"
isRequired
isInvalid={!!control._formState.errors.client_id}
/>
<CustomInput
control={control}
name="client_secret"
type="password"
label="Client Secret"
labelPlacement="inside"
placeholder="Enter the Client Secret"
variant="bordered"
isRequired
isInvalid={!!control._formState.errors.client_secret}
/>
<CustomInput
control={control}
name="tenant_id"
type="text"
label="Tenant ID"
labelPlacement="inside"
placeholder="Enter the Tenant ID"
variant="bordered"
isRequired
isInvalid={!!control._formState.errors.tenant_id}
/>
</>
);
};
@@ -0,0 +1,56 @@
import { Control } from "react-hook-form";
import { CustomInput } from "@/components/ui/custom";
import { GCPCredentials } from "@/types";
export const GCPcredentialsForm = ({
control,
}: {
control: Control<GCPCredentials>;
}) => {
return (
<>
<div className="text-left">
<div className="text-2xl font-bold leading-9 text-default-foreground">
Connect via Credentials
</div>
<div className="py-2 text-default-500">
Please provide the information for your GCP credentials.
</div>
</div>
<CustomInput
control={control}
name="client_id"
type="text"
label="Client ID"
labelPlacement="inside"
placeholder="Enter the Client ID"
variant="bordered"
isRequired
isInvalid={!!control._formState.errors.client_id}
/>
<CustomInput
control={control}
name="client_secret"
type="password"
label="Client Secret"
labelPlacement="inside"
placeholder="Enter the Client Secret"
variant="bordered"
isRequired
isInvalid={!!control._formState.errors.client_secret}
/>
<CustomInput
control={control}
name="refresh_token"
type="password"
label="Refresh Token"
labelPlacement="inside"
placeholder="Enter the Refresh Token"
variant="bordered"
isRequired
isInvalid={!!control._formState.errors.refresh_token}
/>
</>
);
};
@@ -0,0 +1,4 @@
export * from "./aws-credentials-form";
export * from "./azure-credentials-form";
export * from "./gcp-credentials-form";
export * from "./k8s-credentials-form";
@@ -0,0 +1,34 @@
import { Control } from "react-hook-form";
import { CustomInput } from "@/components/ui/custom";
import { KubernetesCredentials } from "@/types";
export const KubernetesCredentialsForm = ({
control,
}: {
control: Control<KubernetesCredentials>;
}) => {
return (
<>
<div className="text-left">
<div className="text-2xl font-bold leading-9 text-default-foreground">
Connect via Credentials
</div>
<div className="py-2 text-default-500">
Please provide the information for your Kubernetes credentials.
</div>
</div>
<CustomInput
control={control}
name="kubeconfig_content"
type="text"
label="Kubeconfig Content"
labelPlacement="inside"
placeholder="Enter the Kubeconfig Content"
variant="bordered"
isRequired
isInvalid={!!control._formState.errors.kubeconfig_content}
/>
</>
);
};
@@ -0,0 +1,125 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { SaveIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { Control, useForm } from "react-hook-form";
import * as z from "zod";
import { addCredentialsProvider } from "@/actions/providers/providers";
import { useToast } from "@/components/ui";
import { CustomButton } from "@/components/ui/custom";
import { Form } from "@/components/ui/form";
import {
addCredentialsRoleFormSchema,
ApiError,
AWSCredentialsRole,
} from "@/types";
import { AWSCredentialsRoleForm } from "./via-role/aws-role-form";
export const ViaRoleForm = ({
searchParams,
}: {
searchParams: { type: string; id: string };
}) => {
const router = useRouter();
const { toast } = useToast();
const providerType = searchParams.type;
const providerId = searchParams.id;
const formSchema = addCredentialsRoleFormSchema(providerType);
type FormSchemaType = z.infer<typeof formSchema>;
const form = useForm<FormSchemaType>({
resolver: zodResolver(formSchema),
defaultValues: {
providerId,
providerType,
...(providerType === "aws"
? {
role_arn: "",
aws_access_key_id: "",
aws_secret_access_key: "",
aws_session_token: "",
session_duration: 3600,
external_id: "",
role_session_name: "",
}
: {}),
},
});
const isLoading = form.formState.isSubmitting;
const onSubmitClient = async (values: FormSchemaType) => {
console.log("via ROLE form", values);
const formData = new FormData();
Object.entries(values).forEach(
([key, value]) =>
value !== undefined && formData.append(key, String(value)),
);
const data = await addCredentialsProvider(formData);
if (data?.errors && data.errors.length > 0) {
data.errors.forEach((error: ApiError) => {
const errorMessage = error.detail;
switch (error.source.pointer) {
case "/data/attributes/secret/role_arn":
form.setError("role_arn" as keyof FormSchemaType, {
type: "server",
message: errorMessage,
});
break;
default:
toast({
variant: "destructive",
title: "Oops! Something went wrong",
description: errorMessage,
});
}
});
} else {
router.push(
`/providers/test-connection?type=${providerType}&id=${providerId}`,
);
}
};
return (
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmitClient)}
className="flex flex-col space-y-4"
>
<input type="hidden" name="providerId" value={providerId} />
<input type="hidden" name="providerType" value={providerType} />
{providerType === "aws" && (
<AWSCredentialsRoleForm
control={form.control as unknown as Control<AWSCredentialsRole>}
/>
)}
<div className="flex w-full justify-end sm:space-x-6">
<CustomButton
type="submit"
ariaLabel={"Save"}
className="w-1/2"
variant="solid"
color="action"
size="lg"
isLoading={isLoading}
startContent={!isLoading && <SaveIcon size={24} />}
>
{isLoading ? <>Loading</> : <span>Save</span>}
</CustomButton>
</div>
</form>
</Form>
);
};
@@ -0,0 +1,105 @@
import { Control } from "react-hook-form";
import { CustomInput } from "@/components/ui/custom";
import { AWSCredentialsRole } from "@/types";
export const AWSCredentialsRoleForm = ({
control,
}: {
control: Control<AWSCredentialsRole>;
}) => {
return (
<>
<div className="mb-4 text-left">
<div className="text-2xl font-bold leading-9 text-default-foreground">
Connect assuming IAM Role
</div>
<div className="py-2 text-default-500">
Please provide the information for your AWS credentials.
</div>
</div>
<CustomInput
control={control}
name="role_arn"
type="text"
label="Role ARN"
labelPlacement="inside"
placeholder="Enter the Role ARN"
variant="bordered"
isRequired
isInvalid={!!control._formState.errors.role_arn}
/>
<span className="text-sm text-default-500">Optional fields</span>
<CustomInput
control={control}
name="aws_access_key_id"
type="password"
label="AWS Access Key ID"
labelPlacement="inside"
placeholder="Enter the AWS Access Key ID"
variant="bordered"
isRequired={false}
isInvalid={!!control._formState.errors.aws_access_key_id}
/>
<CustomInput
control={control}
name="aws_secret_access_key"
type="password"
label="AWS Secret Access Key"
labelPlacement="inside"
placeholder="Enter the AWS Secret Access Key"
variant="bordered"
isRequired={false}
isInvalid={!!control._formState.errors.aws_secret_access_key}
/>
<CustomInput
control={control}
name="aws_session_token"
type="password"
label="AWS Session Token"
labelPlacement="inside"
placeholder="Enter the AWS Session Token"
variant="bordered"
isRequired={false}
isInvalid={!!control._formState.errors.aws_session_token}
/>
<CustomInput
control={control}
name="external_id"
type="text"
label="External ID"
labelPlacement="inside"
placeholder="Enter the External ID"
variant="bordered"
isRequired={false}
isInvalid={!!control._formState.errors.external_id}
/>
<div className="mt-4 grid grid-cols-1 gap-4 md:grid-cols-2">
<CustomInput
control={control}
name="role_session_name"
type="text"
label="Role Session Name"
labelPlacement="inside"
placeholder="Enter the Role Session Name"
variant="bordered"
isRequired={false}
isInvalid={!!control._formState.errors.role_session_name}
/>
<CustomInput
control={control}
name="session_duration"
type="number"
label="Session Duration (seconds)"
labelPlacement="inside"
placeholder="Enter the session duration (default: 3600)"
variant="bordered"
isRequired={false}
isInvalid={!!control._formState.errors.session_duration}
/>
</div>
</>
);
};
@@ -0,0 +1 @@
export * from "./aws-role-form";
+2
View File
@@ -0,0 +1,2 @@
export * from "./vertical-steps";
export * from "./workflow";
@@ -0,0 +1,291 @@
"use client";
import type { ButtonProps } from "@nextui-org/react";
import { cn } from "@nextui-org/react";
import { useControlledState } from "@react-stately/utils";
import { domAnimation, LazyMotion, m } from "framer-motion";
import type { ComponentProps } from "react";
import React from "react";
export type VerticalStepProps = {
className?: string;
description?: React.ReactNode;
title?: React.ReactNode;
};
export interface VerticalStepsProps
extends React.HTMLAttributes<HTMLButtonElement> {
/**
* An array of steps.
*
* @default []
*/
steps?: VerticalStepProps[];
/**
* The color of the steps.
*
* @default "primary"
*/
color?: ButtonProps["color"];
/**
* The current step index.
*/
currentStep?: number;
/**
* The default step index.
*
* @default 0
*/
defaultStep?: number;
/**
* Whether to hide the progress bars.
*
* @default false
*/
hideProgressBars?: boolean;
/**
* The custom class for the steps wrapper.
*/
className?: string;
/**
* The custom class for the step.
*/
stepClassName?: string;
/**
* Callback function when the step index changes.
*/
onStepChange?: (stepIndex: number) => void;
}
function CheckIcon(props: ComponentProps<"svg">) {
return (
<svg
{...props}
fill="none"
stroke="currentColor"
strokeWidth={2}
viewBox="0 0 24 24"
>
<m.path
animate={{ pathLength: 1 }}
d="M5 13l4 4L19 7"
initial={{ pathLength: 0 }}
strokeLinecap="round"
strokeLinejoin="round"
transition={{
delay: 0.2,
type: "tween",
ease: "easeOut",
duration: 0.3,
}}
/>
</svg>
);
}
export const VerticalSteps = React.forwardRef<
HTMLButtonElement,
VerticalStepsProps
>(
(
{
color = "primary",
steps = [],
defaultStep = 0,
onStepChange,
currentStep: currentStepProp,
hideProgressBars = false,
stepClassName,
className,
...props
},
ref,
) => {
const [currentStep, setCurrentStep] = useControlledState(
currentStepProp,
defaultStep,
onStepChange,
);
const colors = React.useMemo(() => {
let userColor;
let fgColor;
const colorsVars = [
"[--active-fg-color:var(--step-fg-color)]",
"[--active-border-color:var(--step-color)]",
"[--active-color:var(--step-color)]",
"[--complete-background-color:var(--step-color)]",
"[--complete-border-color:var(--step-color)]",
"[--inactive-border-color:hsl(var(--nextui-default-300))]",
"[--inactive-color:hsl(var(--nextui-default-300))]",
];
switch (color) {
case "primary":
userColor = "[--step-color:hsl(var(--nextui-primary))]";
fgColor = "[--step-fg-color:hsl(var(--nextui-primary-foreground))]";
break;
case "secondary":
userColor = "[--step-color:hsl(var(--nextui-secondary))]";
fgColor = "[--step-fg-color:hsl(var(--nextui-secondary-foreground))]";
break;
case "success":
userColor = "[--step-color:hsl(var(--nextui-success))]";
fgColor = "[--step-fg-color:hsl(var(--nextui-success-foreground))]";
break;
case "warning":
userColor = "[--step-color:hsl(var(--nextui-warning))]";
fgColor = "[--step-fg-color:hsl(var(--nextui-warning-foreground))]";
break;
case "danger":
userColor = "[--step-color:hsl(var(--nextui-error))]";
fgColor = "[--step-fg-color:hsl(var(--nextui-error-foreground))]";
break;
case "default":
userColor = "[--step-color:hsl(var(--nextui-default))]";
fgColor = "[--step-fg-color:hsl(var(--nextui-default-foreground))]";
break;
default:
userColor = "[--step-color:hsl(var(--nextui-primary))]";
fgColor = "[--step-fg-color:hsl(var(--nextui-primary-foreground))]";
break;
}
if (!className?.includes("--step-fg-color")) colorsVars.unshift(fgColor);
if (!className?.includes("--step-color")) colorsVars.unshift(userColor);
if (!className?.includes("--inactive-bar-color"))
colorsVars.push(
"[--inactive-bar-color:hsl(var(--nextui-default-300))]",
);
return colorsVars;
}, [color, className]);
return (
<nav aria-label="Progress" className="max-w-fit">
<ol className={cn("flex flex-col gap-y-3", colors, className)}>
{steps?.map((step, stepIdx) => {
const status =
currentStep === stepIdx
? "active"
: currentStep < stepIdx
? "inactive"
: "complete";
return (
<li key={stepIdx} className="relative">
<div className="flex w-full max-w-full items-center">
<button
key={stepIdx}
ref={ref}
aria-current={status === "active" ? "step" : undefined}
className={cn(
"group flex w-full cursor-pointer items-center justify-center gap-4 rounded-large px-3 py-2.5",
stepClassName,
)}
onClick={() => setCurrentStep(stepIdx)}
{...props}
>
<div className="flex h-full items-center">
<LazyMotion features={domAnimation}>
<div className="relative">
<m.div
animate={status}
className={cn(
"relative flex h-[34px] w-[34px] items-center justify-center rounded-full border-medium text-large font-semibold text-default-foreground",
{
"shadow-lg": status === "complete",
},
)}
data-status={status}
initial={false}
transition={{ duration: 0.25 }}
variants={{
inactive: {
backgroundColor: "transparent",
borderColor: "var(--inactive-border-color)",
color: "var(--inactive-color)",
},
active: {
backgroundColor: "transparent",
borderColor: "var(--active-border-color)",
color: "var(--active-color)",
},
complete: {
backgroundColor:
"var(--complete-background-color)",
borderColor: "var(--complete-border-color)",
},
}}
>
<div className="flex items-center justify-center">
{status === "complete" ? (
<CheckIcon className="h-6 w-6 text-[var(--active-fg-color)]" />
) : (
<span>{stepIdx + 1}</span>
)}
</div>
</m.div>
</div>
</LazyMotion>
</div>
<div className="flex-1 text-left">
<div>
<div
className={cn(
"text-medium font-medium text-default-foreground transition-[color,opacity] duration-300 group-active:opacity-70",
{
"text-default-500": status === "inactive",
},
)}
>
{step.title}
</div>
<div
className={cn(
"text-tiny text-default-600 transition-[color,opacity] duration-300 group-active:opacity-70 lg:text-small",
{
"text-default-500": status === "inactive",
},
)}
>
{step.description}
</div>
</div>
</div>
</button>
</div>
{stepIdx < steps.length - 1 && !hideProgressBars && (
<div
aria-hidden="true"
className={cn(
"pointer-events-none absolute left-3 top-[calc(64px_*_var(--idx)_+_1)] flex h-1/2 -translate-y-1/3 items-center px-4",
)}
style={{
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
"--idx": stepIdx,
}}
>
<div
className={cn(
"relative h-full w-0.5 bg-[var(--inactive-bar-color)] transition-colors duration-300",
"after:absolute after:block after:h-0 after:w-full after:bg-[var(--active-border-color)] after:transition-[height] after:duration-300 after:content-['']",
{
"after:h-full": stepIdx < currentStep,
},
)}
/>
</div>
)}
</li>
);
})}
</ol>
</nav>
);
},
);
VerticalSteps.displayName = "VerticalSteps";
@@ -0,0 +1,76 @@
"use client";
import { Progress, Spacer } from "@nextui-org/react";
import { usePathname } from "next/navigation";
import React from "react";
import { VerticalSteps } from "./vertical-steps";
const steps = [
{
title: "Add your cloud account",
description:
"Select the cloud provider of the account you want to connect and choose whether to use IAM role or credentials for access.",
href: "/providers/connect-account",
},
{
title: "Add credentials to your cloud account",
description: "Add the credentials needed to connect to your cloud account.",
href: "/providers/add-credentials",
},
{
title: "Test connection",
description:
"Test your connection to verify that the credentials provided are valid for accessing your cloud account.",
href: "/providers/test-connection",
},
{
title: "Launch scan",
description:
"Launch the scan now or schedule it for a later date and time.",
href: "/providers/launch-scan",
},
];
export const Workflow = () => {
const pathname = usePathname();
// Calculate current step based on pathname
const currentStepIndex = steps.findIndex((step) =>
pathname.endsWith(step.href),
);
const currentStep = currentStepIndex === -1 ? 0 : currentStepIndex;
return (
<section className="max-w-sm">
<h1 className="mb-2 text-xl font-medium" id="getting-started">
Add a cloud account
</h1>
<p className="mb-5 text-small text-default-500">
Follow the steps to configure your cloud account. This allows you to
launch the first scan when the process is complete.
</p>
<Progress
classNames={{
base: "px-0.5 mb-5",
label: "text-small",
value: "text-small text-default-400",
}}
label="Steps"
maxValue={steps.length - 1}
minValue={0}
showValueLabel={true}
size="md"
value={currentStep}
valueLabel={`${currentStep + 1} of ${steps.length}`}
/>
<VerticalSteps
hideProgressBars
currentStep={currentStep}
stepClassName="border border-default-200 dark:border-default-50 aria-[current]:bg-default-100 dark:aria-[current]:bg-default-50 cursor-default"
steps={steps}
/>
<Spacer y={4} />
</section>
);
};
+5
View File
@@ -1,6 +1,7 @@
import { Button, CircularProgress } from "@nextui-org/react";
import type { PressEvent } from "@react-types/shared";
import clsx from "clsx";
import Link from "next/link";
import React from "react";
import { NextUIColors, NextUIVariants } from "@/types";
@@ -50,6 +51,7 @@ interface CustomButtonProps {
isLoading?: boolean;
isIconOnly?: boolean;
ref?: React.RefObject<HTMLButtonElement>;
asLink?: string;
}
export const CustomButton = React.forwardRef<
@@ -73,11 +75,14 @@ export const CustomButton = React.forwardRef<
isDisabled = false,
isLoading = false,
isIconOnly,
asLink,
...props
},
ref,
) => (
<Button
as={asLink ? Link : undefined}
href={asLink}
type={type}
aria-label={ariaLabel}
aria-disabled={ariaDisabled}
+3
View File
@@ -13,6 +13,7 @@ interface CustomInputProps<T extends FieldValues> {
label?: string;
labelPlacement?: "inside" | "outside";
variant?: "flat" | "bordered" | "underlined" | "faded";
size?: "sm" | "md" | "lg";
type?: string;
placeholder?: string;
password?: boolean;
@@ -29,6 +30,7 @@ export const CustomInput = <T extends FieldValues>({
labelPlacement = "inside",
placeholder,
variant = "bordered",
size = "md",
confirmPassword = false,
password = false,
isRequired = true,
@@ -95,6 +97,7 @@ export const CustomInput = <T extends FieldValues>({
placeholder={inputPlaceholder}
type={inputType}
variant={variant}
size={size}
isInvalid={isInvalid}
endContent={endContent}
{...field}
+48
View File
@@ -0,0 +1,48 @@
import { UseRadioProps } from "@nextui-org/radio/dist/use-radio";
import { cn, useRadio, VisuallyHidden } from "@nextui-org/react";
import React from "react";
interface CustomRadioProps extends UseRadioProps {
description?: string;
children?: React.ReactNode;
}
export const CustomRadio: React.FC<CustomRadioProps> = (props) => {
const {
Component,
children,
// description,
getBaseProps,
getWrapperProps,
getInputProps,
getLabelProps,
getLabelWrapperProps,
getControlProps,
} = useRadio(props);
return (
<Component
{...getBaseProps()}
className={cn(
"group inline-flex flex-row-reverse items-center justify-between tap-highlight-transparent hover:opacity-70 active:opacity-50",
"max-w-full cursor-pointer gap-4 rounded-lg border-2 border-default p-4",
"w-full hover:border-action data-[selected=true]:border-action",
)}
>
<VisuallyHidden>
<input {...getInputProps()} />
</VisuallyHidden>
<span {...getWrapperProps()}>
<span {...getControlProps()} />
</span>
<div {...getLabelWrapperProps()}>
{children && <span {...getLabelProps()}>{children}</span>}
{/* {description && (
<span className="text-small text-foreground opacity-70">
{description}
</span>
)} */}
</div>
</Component>
);
};
+1
View File
@@ -4,4 +4,5 @@ export * from "./custom-button";
export * from "./custom-dropdown-filter";
export * from "./custom-input";
export * from "./custom-loader";
export * from "./custom-radio";
export * from "./CustomButtonClientAction";
@@ -12,7 +12,7 @@ export const Header: React.FC<HeaderProps> = ({ title, icon }) => {
<>
<header className="flex items-center gap-3 py-4">
<Icon className="text-default-500" height={40} icon={icon} width={40} />
<h1 className="text-2xl font-bold text-default-700">{title}</h1>
<h1 className="text-2xl font-light text-default-700">{title}</h1>
</header>
<Divider className="mb-4" />
</>
@@ -0,0 +1,36 @@
import { Icon } from "@iconify/react";
import { Divider } from "@nextui-org/react";
import React from "react";
import { CustomButton } from "@/components/ui/custom/custom-button";
interface NavigationHeaderProps {
title: string;
icon: string;
href?: string;
}
export const NavigationHeader: React.FC<NavigationHeaderProps> = ({
title,
icon,
href,
}) => {
return (
<>
<header className="flex items-center gap-3 border-b border-gray-200 px-6 py-4 dark:border-gray-800">
<CustomButton
asLink={href || ""}
className="border-gray-200 bg-transparent p-0"
ariaLabel="Navigation button"
variant="bordered"
isIconOnly
radius="lg"
>
<Icon icon={icon} className="text-gray-600 dark:text-gray-400" />
</CustomButton>
<Divider orientation="vertical" className="h-6" />
<h1 className="text-xl font-light text-default-700">{title}</h1>
</header>
</>
);
};
+2 -1
View File
@@ -4,7 +4,8 @@ export * from "./alert-dialog/AlertDialog";
export * from "./chart/Chart";
export * from "./dialog/dialog";
export * from "./dropdown/Dropdown";
export * from "./header/Header";
export * from "./headers/header";
export * from "./headers/navigation-header";
export * from "./label/Label";
export * from "./select/Select";
export * from "./sidebar";
+11 -13
View File
@@ -91,19 +91,17 @@ export const SidebarWrap = () => {
"w-full": !isCompact,
})}
>
{/* TODO: Create a custom-link component and use it here */}
<Link href={"/scans"}>
<CustomButton
className="w-full"
ariaLabel="Launch Scan"
variant="solid"
color="action"
size="md"
endContent={<AddIcon size={20} />}
>
Launch Scan
</CustomButton>
</Link>
<CustomButton
asLink="/scans"
className="w-full"
ariaLabel="Launch Scan"
variant="solid"
color="action"
size="md"
endContent={<AddIcon size={20} />}
>
Launch Scan
</CustomButton>
</div>
</div>
+53 -9
View File
@@ -1,17 +1,61 @@
import { getTask } from "@/actions/task";
import { MetaDataProps } from "@/types";
export async function checkTaskStatus(
taskId: string,
): Promise<{ completed: boolean; error?: string }> {
const MAX_RETRIES = 20; // Define the maximum number of attempts before stopping the polling
const RETRY_DELAY = 1000; // Delay time between each poll (in milliseconds)
for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
const task = await getTask(taskId);
if (task.error) {
// eslint-disable-next-line no-console
console.error(`Error retrieving task: ${task.error}`);
return { completed: false, error: task.error };
}
const state = task.data.attributes.state;
switch (state) {
case "completed":
return { completed: true };
case "failed":
return { completed: false, error: task.data.attributes.result.error };
case "available":
case "scheduled":
case "executing":
// Continue waiting if the task is still in progress
await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY));
break;
default:
console.warn(`Unexpected task state: ${state}`);
return { completed: false, error: "Unexpected task state" };
}
}
return { completed: false, error: "Max retries exceeded" };
}
export const wait = (ms: number) =>
new Promise((resolve) => setTimeout(resolve, ms));
// Helper function to create dictionaries by type
export const createDict = (
type: string,
data: any,
includedField: string = "included",
) =>
Object.fromEntries(
data[includedField]
.filter((item: { type: string }) => item.type === type)
.map((item: { id: string }) => [item.id, item]),
export function createDict(type: string, data: any) {
const includedField = data?.included?.filter(
(item: { type: string }) => item.type === type,
);
if (!includedField || includedField.length === 0) {
return {};
}
return Object.fromEntries(
includedField.map((item: { id: string }) => [item.id, item]),
);
}
export const parseStringify = (value: any) => JSON.parse(JSON.stringify(value));
export const convertFileToUrl = (file: File) => URL.createObjectURL(file);
+12 -4
View File
@@ -23,7 +23,7 @@ module.exports = {
theme: {
midnight: "#030921",
pale: "#f3fcff",
green: "#6af400",
green: "#8ce112",
purple: "#5001d0",
coral: "#ff5356",
orange: "#f69000",
@@ -83,7 +83,7 @@ module.exports = {
},
},
danger: "#E11D48",
action: "#6af400",
action: "#9FD655",
},
fontFamily: {
sans: ["var(--font-sans)"],
@@ -177,13 +177,21 @@ module.exports = {
dark: {
colors: {
primary: {
DEFAULT: "#6af400",
DEFAULT: "#9FD655",
foreground: "#000000",
},
focus: "#6af400",
focus: "#9FD655",
background: "#030921",
},
},
light: {
colors: {
primary: {
DEFAULT: "#9FD655",
foreground: "#000000",
},
},
},
},
}),
],
+46
View File
@@ -26,6 +26,52 @@ export type NextUIColors =
| "danger"
| "default";
export type AWSCredentials = {
aws_access_key_id: string;
aws_secret_access_key: string;
aws_session_token: string;
secretName: string;
providerId: string;
};
export type AWSCredentialsRole = {
role_arn: string;
aws_access_key_id?: string;
aws_secret_access_key?: string;
aws_session_token?: string;
external_id?: string;
role_session_name?: string;
session_duration?: number;
};
export type AzureCredentials = {
client_id: string;
client_secret: string;
tenant_id: string;
secretName: string;
providerId: string;
};
export type GCPCredentials = {
client_id: string;
client_secret: string;
refresh_token: string;
secretName: string;
providerId: string;
};
export type KubernetesCredentials = {
kubeconfig_content: string;
secretName: string;
providerId: string;
};
export type CredentialsFormSchema =
| AWSCredentials
| AzureCredentials
| GCPCredentials
| KubernetesCredentials;
export interface SearchParamsProps {
[key: string]: string | string[] | undefined;
}
+103 -3
View File
@@ -31,12 +31,112 @@ export const scheduleScanFormSchema = () =>
scheduleDate: z.string(),
});
export const addProviderFormSchema = z.object({
providerType: z.string(),
providerAlias: z.string(),
export const addProviderFormSchema = z
.object({
providerType: z.enum(["aws", "azure", "gcp", "kubernetes"], {
required_error: "Please select a provider type",
}),
})
.and(
z.discriminatedUnion("providerType", [
z.object({
providerType: z.literal("aws"),
providerAlias: z.string(),
providerUid: z.string(),
awsCredentialsType: z.string().min(1, {
message: "Please select the type of credentials you want to use",
}),
}),
z.object({
providerType: z.literal("azure"),
providerAlias: z.string(),
providerUid: z.string(),
awsCredentialsType: z.string().optional(),
}),
z.object({
providerType: z.literal("gcp"),
providerAlias: z.string(),
providerUid: z.string(),
awsCredentialsType: z.string().optional(),
}),
z.object({
providerType: z.literal("kubernetes"),
providerAlias: z.string(),
providerUid: z.string(),
awsCredentialsType: z.string().optional(),
}),
]),
);
export const addCredentialsFormSchema = (providerType: string) =>
z.object({
secretName: z.string().optional(),
providerId: z.string(),
providerType: z.string(),
...(providerType === "aws"
? {
aws_access_key_id: z
.string()
.nonempty("AWS Access Key ID is required"),
aws_secret_access_key: z
.string()
.nonempty("AWS Secret Access Key is required"),
aws_session_token: z.string().optional(),
}
: providerType === "azure"
? {
client_id: z.string().nonempty("Client ID is required"),
client_secret: z.string().nonempty("Client Secret is required"),
tenant_id: z.string().nonempty("Tenant ID is required"),
}
: providerType === "gcp"
? {
client_id: z.string().nonempty("Client ID is required"),
client_secret: z.string().nonempty("Client Secret is required"),
refresh_token: z.string().nonempty("Refresh Token is required"),
}
: providerType === "kubernetes"
? {
kubeconfig_content: z
.string()
.nonempty("Kubeconfig Content is required"),
}
: {}),
});
export const addCredentialsRoleFormSchema = (providerType: string) =>
providerType === "aws"
? z.object({
providerId: z.string(),
providerType: z.string(),
role_arn: z.string().optional(),
aws_access_key_id: z.string().optional(),
aws_secret_access_key: z.string().optional(),
aws_session_token: z.string().optional(),
session_duration: z.number().optional(),
external_id: z.string().optional(),
role_session_name: z.string().optional(),
})
: z.object({
providerId: z.string(),
providerType: z.string(),
});
export const testConnectionFormSchema = z.object({
providerId: z.string(),
});
export const launchScanFormSchema = () =>
z.object({
providerId: z.string(),
providerType: z.string(),
scannerArgs: z
.object({
checksToExecute: z.array(z.string()).optional(),
})
.optional(),
});
export const editProviderFormSchema = (currentAlias: string) =>
z.object({
alias: z