Finish basic scaffolding for service token v3

This commit is contained in:
Tuan Dang
2023-09-20 17:32:33 +01:00
parent 1cdd840485
commit 1896442168
25 changed files with 756 additions and 101 deletions
@@ -1 +1,8 @@
export { useCreateServiceToken, useDeleteServiceToken, useGetUserWsServiceTokens } from "./queries";
export {
useCreateServiceToken,
useDeleteServiceToken,
useGetUserWsServiceTokens,
useCreateServiceTokenV3,
useUpdateServiceTokenV3,
useDeleteServiceTokenV3
} from "./queries";
@@ -6,8 +6,14 @@ import {
CreateServiceTokenDTO,
CreateServiceTokenRes,
DeleteServiceTokenRes,
ServiceToken
ServiceToken,
ServiceTokenDataV3,
CreateServiceTokenDataV3DTO,
CreateServiceTokenDataV3Res,
UpdateServiceTokenDataV3DTO,
DeleteServiceTokenDataV3DTO
} from "./types";
import { workspaceKeys } from "../workspace/queries";
const serviceTokenKeys = {
getAllWorkspaceServiceToken: (workspaceID: string) => [{ workspaceID }, "service-tokens"] as const
@@ -32,12 +38,11 @@ export const useGetUserWsServiceTokens = ({ workspaceID }: UseGetWorkspaceServic
}
// mutation
export const useCreateServiceToken = () => {
export const useCreateServiceToken = () => { // TODO: deprecate
const queryClient = useQueryClient();
return useMutation<CreateServiceTokenRes, {}, CreateServiceTokenDTO>({
mutationFn: async (body) => {
console.log("useCreateServiceToken");
const { data } = await apiRequest.post("/api/v2/service-token/", body);
data.serviceToken += `.${body.randomBytes}`;
return data;
@@ -62,3 +67,55 @@ export const useDeleteServiceToken = () => {
}
});
};
export const useCreateServiceTokenV3 = () => {
const queryClient = useQueryClient();
return useMutation<CreateServiceTokenDataV3Res, {}, CreateServiceTokenDataV3DTO>({
mutationFn: async (body) => {
const { data } = await apiRequest.post("/api/v3/service-token/", body);
return data;
},
onSuccess: ({ serviceTokenData }) => {
queryClient.invalidateQueries(workspaceKeys.getWorkspaceServiceTokenDataV3(serviceTokenData.workspace));
}
});
};
export const useUpdateServiceTokenV3 = () => {
const queryClient = useQueryClient();
return useMutation<ServiceTokenDataV3, {}, UpdateServiceTokenDataV3DTO>({
mutationFn: async ({
serviceTokenDataId,
name,
isActive
}) => {
const { data: { serviceTokenData } } = await apiRequest.patch(`/api/v3/service-token/${serviceTokenDataId}`, {
name,
isActive
});
return serviceTokenData;
},
onSuccess: ({ workspace }) => {
queryClient.invalidateQueries(workspaceKeys.getWorkspaceServiceTokenDataV3(workspace));
}
});
};
export const useDeleteServiceTokenV3 = () => {
const queryClient = useQueryClient();
return useMutation<ServiceTokenDataV3, {}, DeleteServiceTokenDataV3DTO>({
mutationFn: async ({
serviceTokenDataId
}) => {
console.log("useDeleteServiceTokenV3");
const { data: { serviceTokenData } } = await apiRequest.delete(`/api/v3/service-token/${serviceTokenDataId}`);
console.log("useDeleteServiceTokenV3 serviceTokenData: ", serviceTokenData);
return serviceTokenData;
},
onSuccess: ({ workspace }) => {
console.log("useDeleteServiceTokenV3 onSuccess: ", workspace);
queryClient.invalidateQueries(workspaceKeys.getWorkspaceServiceTokenDataV3(workspace));
}
});
};
@@ -33,3 +33,38 @@ export type CreateServiceTokenRes = {
};
export type DeleteServiceTokenRes = { serviceTokenData: ServiceToken };
// --- v3
export type ServiceTokenDataV3 = {
_id: string;
name: string;
workspace: string;
isActive: boolean;
lastUsed?: string;
createdAt: string;
updatedAt: string;
};
// TODO: add scopes
// TODO: encrypted key info
export type CreateServiceTokenDataV3DTO = {
name: string;
workspaceId: string;
publicKey: string;
}
export type CreateServiceTokenDataV3Res = {
serviceToken: string;
serviceTokenData: ServiceTokenDataV3;
}
export type UpdateServiceTokenDataV3DTO = {
serviceTokenDataId: string;
name?: string;
isActive?: boolean;
}
export type DeleteServiceTokenDataV3DTO = {
serviceTokenDataId: string;
}
+3 -1
View File
@@ -19,4 +19,6 @@ export {
useReorderWsEnvironment,
useToggleAutoCapitalization,
useUpdateUserWorkspaceRole,
useUpdateWsEnvironment} from "./queries";
useUpdateWsEnvironment,
useGetWorkspaceServiceTokenDataV3
} from "./queries";
+19 -1
View File
@@ -6,6 +6,7 @@ import { IntegrationAuth } from "../integrationAuth/types";
import { TIntegration } from "../integrations/types";
import { EncryptedSecret } from "../secrets/types";
import { TWorkspaceUser } from "../users/types";
import { ServiceTokenDataV3 } from "../serviceTokens/types";
import {
CreateEnvironmentDTO,
CreateWorkspaceDTO,
@@ -32,7 +33,8 @@ export const workspaceKeys = {
getAllUserWorkspace: ["workspaces"] as const,
getUserWsEnvironments: (workspaceId: string) => ["workspace-env", { workspaceId }] as const,
getWorkspaceAuditLogs: (workspaceId: string) => [{ workspaceId }] as const,
getWorkspaceUsers: (workspaceId: string) => [{ workspaceId }] as const
getWorkspaceUsers: (workspaceId: string) => [{ workspaceId }] as const,
getWorkspaceServiceTokenDataV3: (workspaceId: string) => [{ workspaceId }, "workspace-service-token-data-v3"] as const
};
const fetchWorkspaceById = async (workspaceId: string) => {
@@ -361,3 +363,19 @@ export const useUpdateUserWorkspaceRole = () => {
}
});
};
export const useGetWorkspaceServiceTokenDataV3 = (workspaceId: string) => {
return useQuery({
queryKey: workspaceKeys.getWorkspaceServiceTokenDataV3(workspaceId),
queryFn: async () => {
const {
data: { serviceTokenData }
} = await apiRequest.get<{ serviceTokenData: ServiceTokenDataV3[] }>(
`/api/v3/workspaces/${workspaceId}/service-token`
);
return serviceTokenData;
},
enabled: true
});
};
@@ -49,56 +49,54 @@ export const APIKeyTable = () => {
};
return (
<div>
<TableContainer className="">
<Table>
<THead>
<TableContainer>
<Table>
<THead>
<Tr>
<Th className="flex-1">Name</Th>
<Th className="flex-1">Last active</Th>
<Th className="flex-1">Created</Th>
<Th className="flex-1">Expiration</Th>
<Th className="w-5" />
</Tr>
</THead>
<TBody>
{isLoading && <TableSkeleton columns={4} innerKey="api-keys" />}
{!isLoading &&
data &&
data.length > 0 &&
data.map(({ _id, name, createdAt, expiresAt, lastUsed }) => {
return (
<Tr className="h-10" key={`api-key-${_id}`}>
<Td>{name}</Td>
<Td>{formatDate(lastUsed)}</Td>
<Td>{formatDate(createdAt)}</Td>
<Td>{formatDate(expiresAt)}</Td>
<Td>
<IconButton
onClick={async () => {
await handleDeleteAPIKeyDataClick(_id);
}}
size="lg"
colorSchema="danger"
variant="plain"
ariaLabel="update"
>
<FontAwesomeIcon icon={faXmark} />
</IconButton>
</Td>
</Tr>
);
})}
{!isLoading && data && data?.length === 0 && (
<Tr>
<Th className="flex-1">Name</Th>
<Th className="flex-1">Last active</Th>
<Th className="flex-1">Created</Th>
<Th className="flex-1">Expiration</Th>
<Th className="w-5" />
<Td colSpan={5}>
<EmptyState title="No API Keys on file" icon={faKey} />
</Td>
</Tr>
</THead>
<TBody>
{isLoading && <TableSkeleton columns={4} innerKey="api-keys" />}
{!isLoading &&
data &&
data.length > 0 &&
data.map(({ _id, name, createdAt, expiresAt, lastUsed }) => {
return (
<Tr className="h-10" key={`api-key-${_id}`}>
<Td>{name}</Td>
<Td>{formatDate(lastUsed)}</Td>
<Td>{formatDate(createdAt)}</Td>
<Td>{formatDate(expiresAt)}</Td>
<Td>
<IconButton
onClick={async () => {
await handleDeleteAPIKeyDataClick(_id);
}}
size="lg"
colorSchema="danger"
variant="plain"
ariaLabel="update"
>
<FontAwesomeIcon icon={faXmark} />
</IconButton>
</Td>
</Tr>
);
})}
{!isLoading && data && data?.length === 0 && (
<Tr>
<Td colSpan={5}>
<EmptyState title="No API Keys on file" icon={faKey} />
</Td>
</Tr>
)}
</TBody>
</Table>
</TableContainer>
</div>
)}
</TBody>
</Table>
</TableContainer>
);
};
@@ -161,18 +161,18 @@ export const AddAPIKeyModal = ({
)}
/>
<div className="mt-8 flex items-center">
<Button
className="mr-4"
size="sm"
type="submit"
isLoading={isLoading}
isDisabled={isLoading}
>
Add
</Button>
<Button colorSchema="secondary" variant="plain">
Cancel
</Button>
<Button
className="mr-4"
size="sm"
type="submit"
isLoading={isLoading}
isDisabled={isLoading}
>
Add
</Button>
<Button colorSchema="secondary" variant="plain">
Cancel
</Button>
</div>
</form>
) : (
@@ -2,8 +2,6 @@ import { Fragment } from "react";
import { useTranslation } from "react-i18next";
import { Tab } from "@headlessui/react";
import NavHeader from "@app/components/navigation/NavHeader";
import { ProjectGeneralTab } from "./components/ProjectGeneralTab";
import { ProjectServiceTokensTab } from "./components/ProjectServiceTokensTab";
import { WebhooksTab } from "./components/WebhooksTab";
@@ -17,12 +15,9 @@ const tabs = [
export const ProjectSettingsPage = () => {
const { t } = useTranslation();
return (
<div className="flex w-full justify-center bg-bunker-800 px-6 text-white">
<div className="w-full max-w-screen-lg">
<div className="relative right-5 ml-4">
<NavHeader pageName={t("settings.project.title")} isProjectRelated />
</div>
<div className="my-8">
<div className="flex justify-center w-full h-full bg-bunker-800 text-white">
<div className="max-w-7xl px-6 w-full">
<div className="my-6">
<p className="text-3xl font-semibold text-gray-200">{t("settings.project.title")}</p>
</div>
<Tab.Group>
@@ -1,7 +1,185 @@
export const AddServiceTokenV3Modal = () => {
import nacl from "tweetnacl";
import { encodeBase64 } from "tweetnacl-util";
import { UsePopUpState } from "@app/hooks/usePopUp";
import { Controller, useForm } from "react-hook-form";
import { useWorkspace } from "@app/context";
import {
Modal,
ModalContent,
FormControl,
Select,
SelectItem,
Input,
Button
} from "@app/components/v2";
import { useNotificationContext } from "@app/components/context/Notifications/NotificationProvider";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { useCreateServiceTokenV3 } from "@app/hooks/api";
const expirations = [
{ label: "1 day", value: "86400" },
{ label: "7 days", value: "604800" },
{ label: "1 month", value: "2592000" },
{ label: "6 months", value: "15552000" },
{ label: "12 months", value: "31104000" }
];
const schema = yup.object({
name: yup.string().required("ST V3 name is required"),
expiresIn: yup.string().required("ST V3 expiration window is required")
}).required();
export type FormData = yup.InferType<typeof schema>;
type Props = {
popUp: UsePopUpState<["createServiceTokenV3"]>;
handlePopUpToggle: (popUpName: keyof UsePopUpState<["createServiceTokenV3"]>, state?: boolean) => void;
};
// Will download a JSON
// Maybe you can set a timer at which point service token is no longer active!
// Maybe you can also set IP allowlist for it too
export const AddServiceTokenV3Modal = ({
popUp,
handlePopUpToggle
}: Props) => {
const { currentWorkspace } = useWorkspace();
const { mutateAsync } = useCreateServiceTokenV3();
const { createNotification } = useNotificationContext();
const {
control,
handleSubmit,
reset
} = useForm<FormData>({
resolver: yupResolver(schema)
});
const onFormSubmit = async ({
name,
expiresIn
}: FormData) => {
try {
if (!currentWorkspace?._id) return;
console.log("onFormSubmit name: ", name);
console.log("onFormSubmit expiresIn: ", expiresIn);
const pair = nacl.box.keyPair();
const secretKeyUint8Array = pair.secretKey;
const publicKeyUint8Array = pair.publicKey;
const privateKey = encodeBase64(secretKeyUint8Array);
const publicKey = encodeBase64(publicKeyUint8Array);
console.log("pair: ", pair);
console.log("privateKey: ", privateKey);
console.log("publicKey: ", publicKey );
const { serviceToken } = await mutateAsync({
name,
workspaceId: currentWorkspace._id,
publicKey
});
const downloadData = {
publicKey,
privateKey,
serviceToken
};
const blob = new Blob([JSON.stringify(downloadData, null, 2)], { type: 'application/json' });
const href = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = href;
link.download = `infisical_${name}.json`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
createNotification({
text: "Successfully created ST V3",
type: "success"
});
reset();
handlePopUpToggle("createServiceTokenV3", false);
} catch (err) {
console.error(err);
createNotification({
text: "Failed to create ST V3",
type: "error"
});
}
}
return (
<div>
AddServiceTokenV3Modal
</div>
<Modal
isOpen={popUp?.createServiceTokenV3?.isOpen}
onOpenChange={(isOpen) => {
handlePopUpToggle("createServiceTokenV3", isOpen);
reset();
}}
>
<ModalContent title="Create Service Token V3">
<form onSubmit={handleSubmit(onFormSubmit)}>
<Controller
control={control}
defaultValue=""
name="name"
render={({ field, fieldState: { error } }) => (
<FormControl
label="Name"
isError={Boolean(error)}
errorText={error?.message}
>
<Input
{...field}
placeholder="My ST V3"
/>
</FormControl>
)}
/>
<Controller
control={control}
name="expiresIn"
defaultValue="15552000"
render={({ field: { onChange, ...field }, fieldState: { error } }) => (
<FormControl
label="Expiration"
errorText={error?.message}
isError={Boolean(error)}
>
<Select
defaultValue={field.value}
{...field}
onValueChange={(e) => onChange(e)}
className="w-full"
>
{expirations.map(({ label, value }) => (
<SelectItem value={String(value || "")} key={`api-key-expiration-${label}`}>
{label}
</SelectItem>
))}
</Select>
</FormControl>
)}
/>
<div className="mt-8 flex items-center">
<Button
className="mr-4"
size="sm"
type="submit"
// isLoading={isLoading}
// isDisabled={isLoading}
>
Create
</Button>
<Button colorSchema="secondary" variant="plain">
Cancel
</Button>
</div>
</form>
</ModalContent>
</Modal>
);
}
@@ -1,14 +1,34 @@
import { faPlus } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { AddServiceTokenV3Modal } from "./AddServiceTokenV3Modal";
import { ServiceTokenV3Table } from "./ServiceTokenV3Table";
import { Button } from "@app/components/v2";
import { usePopUp } from "@app/hooks/usePopUp";
export const ServiceTokenV3Section = () => {
const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp([
"createServiceTokenV3"
] as const);
return (
<div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
<p className="text-xl font-semibold text-mineshaft-100">
Service Tokens 2.0
</p>
<div className="flex justify-between mb-8">
<p className="text-xl font-semibold text-mineshaft-100">
Service Tokens 2.0
</p>
<Button
colorSchema="secondary"
type="submit"
leftIcon={<FontAwesomeIcon icon={faPlus} />}
onClick={() => handlePopUpOpen("createServiceTokenV3")}
>
Create ST V3
</Button>
</div>
<ServiceTokenV3Table />
<AddServiceTokenV3Modal />
<AddServiceTokenV3Modal
popUp={popUp}
handlePopUpToggle={handlePopUpToggle}
/>
</div>
);
}
@@ -1,7 +1,170 @@
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faKey, faXmark, faPencil } from "@fortawesome/free-solid-svg-icons";
import { useWorkspace } from "@app/context";
import { useNotificationContext } from "@app/components/context/Notifications/NotificationProvider";
import {
EmptyState,
IconButton,
Switch,
Table,
TableContainer,
TableSkeleton,
TBody,
Td,
Th,
THead,
Tr
} from "@app/components/v2";
import {
useGetWorkspaceServiceTokenDataV3,
useUpdateServiceTokenV3,
useDeleteServiceTokenV3
} from "@app/hooks/api";
export const ServiceTokenV3Table = () => {
const { createNotification } = useNotificationContext();
const { currentWorkspace } = useWorkspace();
const { data, isLoading } = useGetWorkspaceServiceTokenDataV3(currentWorkspace?._id || "");
const { mutateAsync: updateMutateAsync } = useUpdateServiceTokenV3();
const { mutateAsync: deleteMutateAsync } = useDeleteServiceTokenV3();
console.log("data1: ", data);
const handleDeleteServiceTokenData = async (serviceTokenDataId: string) => {
try {
await deleteMutateAsync({
serviceTokenDataId
});
createNotification({
text: "Successfully deleted service token v3",
type: "success"
});
} catch (err) {
console.error(err);
createNotification({
text: "Failed to delete service token v3",
type: "error"
});
}
}
const handleToggleServiceTokenDataStatus = async ({
serviceTokenDataId,
isActive
}: {
serviceTokenDataId: string;
isActive: boolean;
}) => {
try {
await updateMutateAsync({
serviceTokenDataId,
isActive
});
createNotification({
text: `Successfully ${isActive ? "enabled" : "disabled"} service token v3`,
type: "success"
});
} catch (err) {
console.log(err);
createNotification({
text: `Failed to ${isActive ? "enable" : "disable"} service token v3`,
type: "error"
});
}
}
const formatDate = (dateToFormat: string) => {
const date = new Date(dateToFormat);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const formattedDate = `${day}/${month}/${year}`;
return formattedDate;
};
return (
<div>
ServiceTokenV3Table
</div>
<TableContainer>
<Table>
<THead>
<Tr>
<Th>Name</Th>
<Th>Status</Th>
<Th>Last Active</Th>
<Th>Created</Th>
<Th>Expiration</Th>
<Th className="w-5"></Th>
</Tr>
</THead>
<TBody>
{isLoading && <TableSkeleton columns={5} innerKey="service-tokens" />}
{!isLoading &&
data &&
data.length > 0 &&
data.map(({
_id,
name,
isActive,
lastUsed,
createdAt,
// expiresAt
}) => {
return (
<Tr className="h-10" key={`st-v3-${_id}`}>
<Td>{name}</Td>
<Td>
<Switch
id="test"
// id={`enable-${authMethodOpt.value}-auth`}
onCheckedChange={(value) => handleToggleServiceTokenDataStatus({
serviceTokenDataId: _id,
isActive: value
})}
isChecked={isActive}
>
<p className="w-12 mr-4">{isActive ? "Active" : "Inactive"}</p>
</Switch>
</Td>
<Td>{lastUsed ? formatDate(lastUsed) : "-"}</Td>
<Td>{formatDate(createdAt)}</Td>
<Td>{formatDate(createdAt)}</Td>
<Td className="flex justify-end">
<IconButton
onClick={async () => {
console.log("edit");
}}
size="lg"
colorSchema="primary"
variant="plain"
ariaLabel="update"
>
<FontAwesomeIcon icon={faPencil} />
</IconButton>
<IconButton
onClick={() => handleDeleteServiceTokenData(_id)}
size="lg"
colorSchema="danger"
variant="plain"
ariaLabel="update"
className="ml-4"
>
<FontAwesomeIcon icon={faXmark} />
</IconButton>
</Td>
</Tr>
);
})}
{!isLoading && data && data?.length === 0 && (
<Tr>
<Td colSpan={5}>
<EmptyState title="No service token v3 on file" icon={faKey} />
</Td>
</Tr>
)}
</TBody>
</Table>
</TableContainer>
);
}