feat(identities): Universal Auth Login Lockout

This commit is contained in:
x032205
2025-08-18 23:57:31 +08:00
parent ca2825ba95
commit 6d5bed756a
25 changed files with 644 additions and 108 deletions
+1 -1
View File
@@ -204,7 +204,7 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
{leftIcon && (
<div
className={twMerge(
"inline-flex shrink-0 cursor-pointer items-center justify-center transition-all",
"pointer-events-none inline-flex shrink-0 items-center justify-center transition-all",
loadingToggleClass,
size === "xs" ? "mr-1" : "mr-2"
)}
@@ -40,6 +40,7 @@ export const eventToNameMap: { [K in EventType]: string } = {
[EventType.GET_IDENTITY_UNIVERSAL_AUTH]: "Get universal auth",
[EventType.CREATE_IDENTITY_UNIVERSAL_AUTH_CLIENT_SECRET]: "Create universal auth client secret",
[EventType.REVOKE_IDENTITY_UNIVERSAL_AUTH_CLIENT_SECRET]: "Revoke universal auth client secret",
[EventType.CLEAR_IDENTITY_UNIVERSAL_AUTH_LOCKOUTS]: "Clear universal auth lockouts",
[EventType.GET_IDENTITY_UNIVERSAL_AUTH_CLIENT_SECRETS]: "Get universal auth client secrets",
[EventType.CREATE_ENVIRONMENT]: "Create environment",
[EventType.UPDATE_ENVIRONMENT]: "Update environment",
@@ -46,6 +46,7 @@ export enum EventType {
GET_IDENTITY_UNIVERSAL_AUTH = "get-identity-universal-auth",
CREATE_IDENTITY_UNIVERSAL_AUTH_CLIENT_SECRET = "create-identity-universal-auth-client-secret",
REVOKE_IDENTITY_UNIVERSAL_AUTH_CLIENT_SECRET = "revoke-identity-universal-auth-client-secret",
CLEAR_IDENTITY_UNIVERSAL_AUTH_LOCKOUTS = "clear-identity-universal-auth-lockouts",
GET_IDENTITY_UNIVERSAL_AUTH_CLIENT_SECRETS = "get-identity-universal-auth-client-secret",
LOGIN_IDENTITY_LDAP_AUTH = "login-identity-ldap-auth",
@@ -326,6 +326,14 @@ interface RevokeIdentityUniversalAuthClientSecretEvent {
};
}
interface ClearIdentityUniversalAuthLockoutsEvent {
type: EventType.CLEAR_IDENTITY_UNIVERSAL_AUTH_LOCKOUTS;
metadata: {
identityId: string;
clientSecretId: string;
};
}
interface CreateEnvironmentEvent {
type: EventType.CREATE_ENVIRONMENT;
metadata: {
@@ -892,6 +900,7 @@ export type Event =
| CreateIdentityUniversalAuthClientSecretEvent
| GetIdentityUniversalAuthClientSecretsEvent
| RevokeIdentityUniversalAuthClientSecretEvent
| ClearIdentityUniversalAuthLockoutsEvent
| CreateEnvironmentEvent
| UpdateEnvironmentEvent
| DeleteEnvironmentEvent
@@ -18,6 +18,7 @@ import {
AddIdentityTlsCertAuthDTO,
AddIdentityTokenAuthDTO,
AddIdentityUniversalAuthDTO,
ClearIdentityUniversalAuthLockoutsDTO,
ClientSecretData,
CreateIdentityDTO,
CreateIdentityUniversalAuthClientSecretDTO,
@@ -148,7 +149,11 @@ export const useAddIdentityUniversalAuth = () => {
accessTokenTTL,
accessTokenMaxTTL,
accessTokenNumUsesLimit,
accessTokenTrustedIps
accessTokenTrustedIps,
lockoutEnabled,
lockoutThreshold,
lockoutDuration,
lockoutCounterReset
}) => {
const {
data: { identityUniversalAuth }
@@ -157,7 +162,11 @@ export const useAddIdentityUniversalAuth = () => {
accessTokenTTL,
accessTokenMaxTTL,
accessTokenNumUsesLimit,
accessTokenTrustedIps
accessTokenTrustedIps,
lockoutEnabled,
lockoutThreshold,
lockoutDuration,
lockoutCounterReset
});
return identityUniversalAuth;
},
@@ -183,7 +192,11 @@ export const useUpdateIdentityUniversalAuth = () => {
accessTokenMaxTTL,
accessTokenNumUsesLimit,
accessTokenTrustedIps,
accessTokenPeriod
accessTokenPeriod,
lockoutEnabled,
lockoutThreshold,
lockoutDuration,
lockoutCounterReset
}) => {
const {
data: { identityUniversalAuth }
@@ -193,7 +206,11 @@ export const useUpdateIdentityUniversalAuth = () => {
accessTokenMaxTTL,
accessTokenNumUsesLimit,
accessTokenTrustedIps,
accessTokenPeriod
accessTokenPeriod,
lockoutEnabled,
lockoutThreshold,
lockoutDuration,
lockoutCounterReset
});
return identityUniversalAuth;
},
@@ -275,6 +292,25 @@ export const useRevokeIdentityUniversalAuthClientSecret = () => {
});
};
export const useClearIdentityUniversalAuthLockouts = () => {
const queryClient = useQueryClient();
return useMutation<number, object, ClearIdentityUniversalAuthLockoutsDTO>({
mutationFn: async ({ identityId }) => {
const {
data: { deleted }
} = await apiRequest.post<{ deleted: number }>(
`/api/v1/auth/universal-auth/identities/${identityId}/clear-lockouts`
);
return deleted;
},
onSuccess: (_, { identityId }) => {
queryClient.invalidateQueries({
queryKey: identitiesKeys.clearIdentityUniversalAuthLockouts(identityId)
});
}
});
};
export const useAddIdentityGcpAuth = () => {
const queryClient = useQueryClient();
return useMutation<IdentityGcpAuth, object, AddIdentityGcpAuthDTO>({
@@ -49,7 +49,9 @@ export const identitiesKeys = {
getIdentityTokensTokenAuth: (identityId: string) =>
[{ identityId }, "identity-tokens-token-auth"] as const,
getIdentityProjectMemberships: (identityId: string) =>
[{ identityId }, "identity-project-memberships"] as const
[{ identityId }, "identity-project-memberships"] as const,
clearIdentityUniversalAuthLockouts: (identityId: string) =>
[{ identityId }, "clear-identity-universal-auth-lockouts"] as const
};
export const useGetIdentityById = (identityId: string) => {
@@ -16,6 +16,7 @@ export type Identity = {
name: string;
hasDeleteProtection: boolean;
authMethods: IdentityAuthMethod[];
activeLockoutAuthMethods: IdentityAuthMethod[];
createdAt: string;
updatedAt: string;
isInstanceAdmin?: boolean;
@@ -113,6 +114,10 @@ export type IdentityUniversalAuth = {
accessTokenNumUsesLimit: number;
accessTokenTrustedIps: IdentityTrustedIp[];
accessTokenPeriod: number;
lockoutEnabled: boolean;
lockoutThreshold: number;
lockoutDuration: number;
lockoutCounterReset: number;
};
export type AddIdentityUniversalAuthDTO = {
@@ -128,6 +133,10 @@ export type AddIdentityUniversalAuthDTO = {
accessTokenTrustedIps: {
ipAddress: string;
}[];
lockoutEnabled: boolean;
lockoutThreshold: number;
lockoutDuration: number;
lockoutCounterReset: number;
};
export type UpdateIdentityUniversalAuthDTO = {
@@ -143,6 +152,10 @@ export type UpdateIdentityUniversalAuthDTO = {
accessTokenTrustedIps?: {
ipAddress: string;
}[];
lockoutEnabled?: boolean;
lockoutThreshold?: number;
lockoutDuration?: number;
lockoutCounterReset?: number;
};
export type DeleteIdentityUniversalAuthDTO = {
@@ -558,6 +571,10 @@ export type DeleteIdentityUniversalAuthClientSecretDTO = {
clientSecretId: string;
};
export type ClearIdentityUniversalAuthLockoutsDTO = {
identityId: string;
};
export type IdentityTokenAuth = {
identityId: string;
accessTokenTTL: number;
@@ -11,6 +11,7 @@ import {
FormControl,
IconButton,
Input,
Switch,
Tab,
TabList,
TabPanel,
@@ -60,7 +61,26 @@ const schema = z
ipAddress: z.string().max(50)
})
.array()
.min(1)
.min(1),
lockoutEnabled: z.boolean().default(true),
lockoutThreshold: z
.string()
.refine(
(value) => Number(value) <= 30 && Number(value) >= 1,
"Lockout threshold must be between 1 and 30"
),
lockoutDuration: z
.string()
.refine(
(value) => Number(value) <= 86400 && Number(value) >= 30,
"Lockout duration must be between 30 seconds and 1 day"
),
lockoutCounterReset: z
.string()
.refine(
(value) => Number(value) <= 3600 && Number(value) >= 5,
"Lockout counter reset must be between 5 seconds and 1 hour"
)
})
.required();
@@ -107,12 +127,21 @@ export const IdentityUniversalAuthForm = ({
accessTokenNumUsesLimit: "0",
clientSecretTrustedIps: [{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }],
accessTokenTrustedIps: [{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }],
accessTokenPeriod: "0"
accessTokenPeriod: "0",
lockoutEnabled: true,
lockoutThreshold: "3",
lockoutDuration: "300",
lockoutCounterReset: "30"
}
});
const accessTokenPeriodValue = Number(watch("accessTokenPeriod"));
const lockoutEnabled = watch("lockoutEnabled");
const lockoutThreshold = watch("lockoutThreshold");
const lockoutDuration = watch("lockoutDuration");
const lockoutCounterReset = watch("lockoutCounterReset");
const {
fields: clientSecretTrustedIpsFields,
append: appendClientSecretTrustedIp,
@@ -144,7 +173,11 @@ export const IdentityUniversalAuthForm = ({
ipAddress: `${ipAddress}${prefix !== undefined ? `/${prefix}` : ""}`
};
}
)
),
lockoutEnabled: data.lockoutEnabled,
lockoutThreshold: String(data.lockoutThreshold),
lockoutDuration: String(data.lockoutDuration),
lockoutCounterReset: String(data.lockoutCounterReset)
});
} else {
reset({
@@ -153,7 +186,11 @@ export const IdentityUniversalAuthForm = ({
accessTokenNumUsesLimit: "0",
accessTokenPeriod: "0",
clientSecretTrustedIps: [{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }],
accessTokenTrustedIps: [{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }]
accessTokenTrustedIps: [{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }],
lockoutEnabled: true,
lockoutThreshold: "3",
lockoutDuration: "300",
lockoutCounterReset: "30"
});
}
}, [data]);
@@ -164,7 +201,11 @@ export const IdentityUniversalAuthForm = ({
accessTokenNumUsesLimit,
clientSecretTrustedIps,
accessTokenTrustedIps,
accessTokenPeriod
accessTokenPeriod,
lockoutEnabled,
lockoutThreshold,
lockoutDuration,
lockoutCounterReset
}: FormData) => {
try {
if (!identityId) return;
@@ -179,7 +220,11 @@ export const IdentityUniversalAuthForm = ({
accessTokenMaxTTL: Number(accessTokenMaxTTL),
accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit),
accessTokenTrustedIps,
accessTokenPeriod: Number(accessTokenPeriod)
accessTokenPeriod: Number(accessTokenPeriod),
lockoutEnabled,
lockoutThreshold: Number(lockoutThreshold),
lockoutDuration: Number(lockoutDuration),
lockoutCounterReset: Number(lockoutCounterReset)
});
} else {
// create new universal auth configuration
@@ -192,7 +237,11 @@ export const IdentityUniversalAuthForm = ({
accessTokenMaxTTL: Number(accessTokenMaxTTL),
accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit),
accessTokenTrustedIps,
accessTokenPeriod: Number(accessTokenPeriod)
accessTokenPeriod: Number(accessTokenPeriod),
lockoutEnabled,
lockoutThreshold: Number(lockoutThreshold),
lockoutDuration: Number(lockoutDuration),
lockoutCounterReset: Number(lockoutCounterReset)
});
}
@@ -220,13 +269,21 @@ export const IdentityUniversalAuthForm = ({
setTabValue(
["accessTokenTrustedIps", "clientSecretTrustedIps"].includes(Object.keys(fields)[0])
? IdentityFormTab.Advanced
: IdentityFormTab.Configuration
: [
"lockoutEnabled",
"lockoutThreshold",
"lockoutDuration",
"lockoutCounterReset"
].includes(Object.keys(fields)[0])
? IdentityFormTab.Lockout
: IdentityFormTab.Configuration
);
})}
>
<Tabs value={tabValue} onValueChange={(value) => setTabValue(value as IdentityFormTab)}>
<TabList>
<Tab value={IdentityFormTab.Configuration}>Configuration</Tab>
<Tab value={IdentityFormTab.Lockout}>Lockout</Tab>
<Tab value={IdentityFormTab.Advanced}>Advanced</Tab>
</TabList>
<TabPanel value={IdentityFormTab.Configuration}>
@@ -296,6 +353,84 @@ export const IdentityUniversalAuthForm = ({
)}
/>
</TabPanel>
<TabPanel value={IdentityFormTab.Lockout}>
<div className="mb-3 flex flex-col">
<Controller
control={control}
name="lockoutEnabled"
defaultValue={true}
render={({ field: { value, onChange }, fieldState: { error } }) => {
return (
<FormControl
helperText={`The lockout feature will prevent login attempts for ${lockoutDuration || 300} seconds after ${lockoutThreshold || 3} consecutive login failures. If ${lockoutCounterReset || 30} seconds pass after the most recent failure, the lockout counter resets.`}
isError={Boolean(error)}
errorText={error?.message}
>
<Switch
className="ml-0 mr-3 bg-mineshaft-400/80 shadow-inner data-[state=checked]:bg-green/80"
containerClassName="flex-row-reverse w-fit"
id="lockout-enabled"
thumbClassName="bg-mineshaft-800"
onCheckedChange={onChange}
isChecked={value}
>
Lockout {value ? "Enabled" : "Disabled"}
</Switch>
</FormControl>
);
}}
/>
<Controller
control={control}
name="lockoutThreshold"
render={({ field, fieldState: { error } }) => {
return (
<FormControl
className={`mb-0 flex-grow ${lockoutEnabled ? "" : "opacity-70"}`}
label="Lockout Threshold"
isError={Boolean(error)}
errorText={error?.message}
>
<Input {...field} placeholder="3" isDisabled={!lockoutEnabled} />
</FormControl>
);
}}
/>
<Controller
control={control}
name="lockoutDuration"
render={({ field, fieldState: { error } }) => {
return (
<FormControl
className={`mb-0 flex-grow ${lockoutEnabled ? "" : "opacity-70"}`}
label="Lockout Duration (seconds)"
isError={Boolean(error)}
errorText={error?.message}
>
<Input {...field} placeholder="300" isDisabled={!lockoutEnabled} />
</FormControl>
);
}}
/>
<Controller
control={control}
name="lockoutCounterReset"
render={({ field, fieldState: { error } }) => {
return (
<FormControl
className={`mb-0 flex-grow ${lockoutEnabled ? "" : "opacity-70"}`}
label="Lockout Counter Reset (seconds)"
isError={Boolean(error)}
errorText={error?.message}
>
<Input {...field} placeholder="30" isDisabled={!lockoutEnabled} />
</FormControl>
);
}}
/>
</div>
</TabPanel>
<TabPanel value={IdentityFormTab.Advanced}>
{clientSecretTrustedIpsFields.map(({ id }, index) => (
<div className="mb-3 flex items-end space-x-2" key={id}>
@@ -1,4 +1,5 @@
export enum IdentityFormTab {
Advanced = "advanced",
Lockout = "lockout",
Configuration = "configuration"
}
@@ -115,7 +115,8 @@ const Page = () => {
<ViewIdentityAuthModal
isOpen={popUp.viewAuthMethod.isOpen}
onOpenChange={(isOpen) => handlePopUpToggle("viewAuthMethod", isOpen)}
authMethod={popUp.viewAuthMethod.data}
authMethod={popUp.viewAuthMethod.data?.authMethod}
lockedOut={popUp.viewAuthMethod.data?.lockedOut || false}
identityId={identityId}
/>
</div>
@@ -1,4 +1,4 @@
import { faCog, faPlus } from "@fortawesome/free-solid-svg-icons";
import { faCog, faLock, faPlus } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { OrgPermissionCan } from "@app/components/permissions";
@@ -28,12 +28,22 @@ export const IdentityAuthenticationSection = ({ identityId, handlePopUpOpen }: P
{data.identity.authMethods.map((authMethod) => (
<button
key={authMethod}
onClick={() => handlePopUpOpen("viewAuthMethod", authMethod)}
onClick={() =>
handlePopUpOpen("viewAuthMethod", {
authMethod,
lockedOut: data.identity.activeLockoutAuthMethods.includes(authMethod)
})
}
type="button"
className="flex w-full items-center justify-between bg-mineshaft-900 px-4 py-2 text-sm hover:bg-mineshaft-700 data-[state=open]:bg-mineshaft-600"
>
<span>{identityAuthToNameMap[authMethod]}</span>
<FontAwesomeIcon icon={faCog} size="xs" className="text-mineshaft-400" />
<div className="flex gap-2">
{data.identity.activeLockoutAuthMethods.includes(authMethod) && (
<FontAwesomeIcon icon={faLock} size="xs" className="text-red-400/50" />
)}
<FontAwesomeIcon icon={faCog} size="xs" className="text-mineshaft-400" />
</div>
</button>
))}
</div>
@@ -37,6 +37,7 @@ import { ViewIdentityUniversalAuthContent } from "./ViewIdentityUniversalAuthCon
type Props = {
identityId: string;
authMethod?: IdentityAuthMethod;
lockedOut: boolean;
isOpen: boolean;
onOpenChange: (isOpen: boolean) => void;
onDeleteAuthMethod: () => void;
@@ -50,8 +51,9 @@ type TRevokeOptions = {
export const Content = ({
identityId,
authMethod,
lockedOut,
onDeleteAuthMethod
}: Pick<Props, "authMethod" | "identityId" | "onDeleteAuthMethod">) => {
}: Pick<Props, "authMethod" | "lockedOut" | "identityId" | "onDeleteAuthMethod">) => {
const { currentOrg } = useOrganization();
const orgId = currentOrg?.id || "";
@@ -162,6 +164,7 @@ export const Content = ({
popUp={popUp}
handlePopUpOpen={handlePopUpOpen}
handlePopUpToggle={handlePopUpToggle}
lockedOut={lockedOut}
/>
<DeleteActionModal
isOpen={popUp?.revokeAuthMethod?.isOpen}
@@ -184,7 +187,8 @@ export const ViewIdentityAuthModal = ({
isOpen,
onOpenChange,
authMethod,
identityId
identityId,
lockedOut
}: Omit<Props, "onDeleteAuthMethod">) => {
if (!identityId || !authMethod) return null;
@@ -194,6 +198,7 @@ export const ViewIdentityAuthModal = ({
<Content
identityId={identityId}
authMethod={authMethod}
lockedOut={lockedOut}
onDeleteAuthMethod={() => onOpenChange(false)}
/>
</ModalContent>
@@ -1,9 +1,10 @@
import { faBan, faCheck, faCopy } from "@fortawesome/free-solid-svg-icons";
import { faArrowsRotate, faBan, faCheck, faCopy, faFire } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { EmptyState, IconButton, Spinner, Tooltip } from "@app/components/v2";
import { Button, EmptyState, IconButton, Spinner, Tooltip } from "@app/components/v2";
import { useTimedReset } from "@app/hooks";
import {
useClearIdentityUniversalAuthLockouts,
useGetIdentityUniversalAuth,
useGetIdentityUniversalAuthClientSecrets
} from "@app/hooks/api";
@@ -13,22 +14,42 @@ import { IdentityAuthFieldDisplay } from "./IdentityAuthFieldDisplay";
import { IdentityUniversalAuthClientSecretsTable } from "./IdentityUniversalAuthClientSecretsTable";
import { ViewAuthMethodProps } from "./types";
import { ViewIdentityContentWrapper } from "./ViewIdentityContentWrapper";
import { OrgPermissionIdentityActions, OrgPermissionSubjects } from "@app/context";
import { OrgPermissionCan } from "@app/components/permissions";
import { createNotification } from "@app/components/notifications";
import { useState } from "react";
export const ViewIdentityUniversalAuthContent = ({
identityId,
handlePopUpToggle,
handlePopUpOpen,
onDelete,
popUp
popUp,
lockedOut
}: ViewAuthMethodProps) => {
const { data, isPending } = useGetIdentityUniversalAuth(identityId);
const { data: clientSecrets = [], isPending: clientSecretsPending } =
useGetIdentityUniversalAuthClientSecrets(identityId);
const { mutateAsync: clearLockoutsFn, isPending: isClearLockoutsPending } =
useClearIdentityUniversalAuthLockouts();
const [lockedOutState, setLockedOutState] = useState(lockedOut);
const [copyTextClientId, isCopyingClientId, setCopyTextClientId] = useTimedReset<string>({
initialState: "Copy Client ID to clipboard"
});
async function clearLockouts() {
const deleted = await clearLockoutsFn({ identityId });
createNotification({
text: `Successfully cleared ${deleted} lockout${deleted === 1 ? "" : "s"}`,
type: "success"
});
setLockedOutState(false);
}
if (isPending || clientSecretsPending) {
return (
<div className="flex w-full items-center justify-center">
@@ -85,6 +106,40 @@ export const ViewIdentityUniversalAuthContent = ({
<IdentityAuthFieldDisplay label="Client Secret Trusted IPs">
{data.clientSecretTrustedIps.map((ip) => ip.ipAddress).join(", ")}
</IdentityAuthFieldDisplay>
<div className="col-span-2 mt-3 flex justify-between border-b border-mineshaft-500 pb-2">
<span className="text-bunker-300">Lockout Options</span>
<OrgPermissionCan I={OrgPermissionIdentityActions.Edit} a={OrgPermissionSubjects.Identity}>
{(isAllowed) => (
<Button
isDisabled={!isAllowed || !lockedOutState || isClearLockoutsPending}
size="xs"
onClick={clearLockouts}
leftIcon={
isClearLockoutsPending ? (
<FontAwesomeIcon icon={faArrowsRotate} className="animate-spin" />
) : (
<FontAwesomeIcon icon={faFire} />
)
}
colorSchema="secondary"
>
Clear All Lockouts
</Button>
)}
</OrgPermissionCan>
</div>
<IdentityAuthFieldDisplay label="Lockout">
{data.lockoutEnabled ? "Enabled" : "Disabled"}
</IdentityAuthFieldDisplay>
<IdentityAuthFieldDisplay label="Lockout Threshold">
{data.lockoutThreshold}
</IdentityAuthFieldDisplay>
<IdentityAuthFieldDisplay label="Lockout Duration">
{data.lockoutDuration} seconds
</IdentityAuthFieldDisplay>
<IdentityAuthFieldDisplay label="Lockout Counter Reset">
{data.lockoutCounterReset} seconds
</IdentityAuthFieldDisplay>
<div className="col-span-2 my-3">
<div className="mb-3 border-b border-mineshaft-500 pb-2">
<span className="text-bunker-300">Client ID</span>
@@ -9,4 +9,5 @@ export type ViewAuthMethodProps = {
state?: boolean
) => void;
popUp: UsePopUpState<["revokeAuthMethod", "upgradePlan", "identityAuthMethod"]>;
lockedOut: boolean;
};