mirror of
https://github.com/awatertrevi/infisical.git
synced 2026-09-22 13:39:35 +00:00
Merge pull request #4417 from Infisical/ENG-3506-LDAP
feat(machine-identities): LDAP Auth Lockout
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
import { Knex } from "knex";
|
||||
|
||||
import { TableName } from "../schemas";
|
||||
|
||||
export async function up(knex: Knex): Promise<void> {
|
||||
if (await knex.schema.hasTable(TableName.IdentityLdapAuth)) {
|
||||
const hasLockoutEnabled = await knex.schema.hasColumn(TableName.IdentityLdapAuth, "lockoutEnabled");
|
||||
const hasLockoutThreshold = await knex.schema.hasColumn(TableName.IdentityLdapAuth, "lockoutThreshold");
|
||||
const hasLockoutDuration = await knex.schema.hasColumn(TableName.IdentityLdapAuth, "lockoutDurationSeconds");
|
||||
const hasLockoutCounterReset = await knex.schema.hasColumn(
|
||||
TableName.IdentityLdapAuth,
|
||||
"lockoutCounterResetSeconds"
|
||||
);
|
||||
|
||||
await knex.schema.alterTable(TableName.IdentityLdapAuth, (t) => {
|
||||
if (!hasLockoutEnabled) {
|
||||
t.boolean("lockoutEnabled").notNullable().defaultTo(true);
|
||||
}
|
||||
if (!hasLockoutThreshold) {
|
||||
t.integer("lockoutThreshold").notNullable().defaultTo(3);
|
||||
}
|
||||
if (!hasLockoutDuration) {
|
||||
t.integer("lockoutDurationSeconds").notNullable().defaultTo(300); // 5 minutes
|
||||
}
|
||||
if (!hasLockoutCounterReset) {
|
||||
t.integer("lockoutCounterResetSeconds").notNullable().defaultTo(30); // 30 seconds
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function down(knex: Knex): Promise<void> {
|
||||
if (await knex.schema.hasTable(TableName.IdentityLdapAuth)) {
|
||||
const hasLockoutEnabled = await knex.schema.hasColumn(TableName.IdentityLdapAuth, "lockoutEnabled");
|
||||
const hasLockoutThreshold = await knex.schema.hasColumn(TableName.IdentityLdapAuth, "lockoutThreshold");
|
||||
const hasLockoutDuration = await knex.schema.hasColumn(TableName.IdentityLdapAuth, "lockoutDurationSeconds");
|
||||
const hasLockoutCounterReset = await knex.schema.hasColumn(
|
||||
TableName.IdentityLdapAuth,
|
||||
"lockoutCounterResetSeconds"
|
||||
);
|
||||
|
||||
await knex.schema.alterTable(TableName.IdentityLdapAuth, (t) => {
|
||||
if (hasLockoutEnabled) {
|
||||
t.dropColumn("lockoutEnabled");
|
||||
}
|
||||
if (hasLockoutThreshold) {
|
||||
t.dropColumn("lockoutThreshold");
|
||||
}
|
||||
if (hasLockoutDuration) {
|
||||
t.dropColumn("lockoutDurationSeconds");
|
||||
}
|
||||
if (hasLockoutCounterReset) {
|
||||
t.dropColumn("lockoutCounterResetSeconds");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,11 @@ export const IdentityLdapAuthsSchema = z.object({
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date(),
|
||||
accessTokenPeriod: z.coerce.number().default(0),
|
||||
templateId: z.string().uuid().nullable().optional()
|
||||
templateId: z.string().uuid().nullable().optional(),
|
||||
lockoutEnabled: z.boolean().default(true),
|
||||
lockoutThreshold: z.number().default(3),
|
||||
lockoutDurationSeconds: z.number().default(300),
|
||||
lockoutCounterResetSeconds: z.number().default(30)
|
||||
});
|
||||
|
||||
export type TIdentityLdapAuths = z.infer<typeof IdentityLdapAuthsSchema>;
|
||||
|
||||
@@ -199,6 +199,7 @@ export enum EventType {
|
||||
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",
|
||||
CLEAR_IDENTITY_LDAP_AUTH_LOCKOUTS = "clear-identity-ldap-auth-lockouts",
|
||||
|
||||
GET_IDENTITY_UNIVERSAL_AUTH_CLIENT_SECRETS = "get-identity-universal-auth-client-secret",
|
||||
GET_IDENTITY_UNIVERSAL_AUTH_CLIENT_SECRET_BY_ID = "get-identity-universal-auth-client-secret-by-id",
|
||||
@@ -1372,6 +1373,10 @@ interface AddIdentityLdapAuthEvent {
|
||||
allowedFields?: TAllowedFields[];
|
||||
url: string;
|
||||
templateId?: string | null;
|
||||
lockoutEnabled: boolean;
|
||||
lockoutThreshold: number;
|
||||
lockoutDurationSeconds: number;
|
||||
lockoutCounterResetSeconds: number;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1386,6 +1391,10 @@ interface UpdateIdentityLdapAuthEvent {
|
||||
allowedFields?: TAllowedFields[];
|
||||
url?: string;
|
||||
templateId?: string | null;
|
||||
lockoutEnabled?: boolean;
|
||||
lockoutThreshold?: number;
|
||||
lockoutDurationSeconds?: number;
|
||||
lockoutCounterResetSeconds?: number;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1403,6 +1412,13 @@ interface RevokeIdentityLdapAuthEvent {
|
||||
};
|
||||
}
|
||||
|
||||
interface ClearIdentityLdapAuthLockoutsEvent {
|
||||
type: EventType.CLEAR_IDENTITY_LDAP_AUTH_LOCKOUTS;
|
||||
metadata: {
|
||||
identityId: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface LoginIdentityOidcAuthEvent {
|
||||
type: EventType.LOGIN_IDENTITY_OIDC_AUTH;
|
||||
metadata: {
|
||||
@@ -3581,6 +3597,7 @@ export type Event =
|
||||
| UpdateIdentityLdapAuthEvent
|
||||
| GetIdentityLdapAuthEvent
|
||||
| RevokeIdentityLdapAuthEvent
|
||||
| ClearIdentityLdapAuthLockoutsEvent
|
||||
| CreateEnvironmentEvent
|
||||
| GetEnvironmentEvent
|
||||
| UpdateEnvironmentEvent
|
||||
|
||||
@@ -242,7 +242,12 @@ export const LDAP_AUTH = {
|
||||
accessTokenTTL: "The lifetime for an access token in seconds.",
|
||||
accessTokenMaxTTL: "The maximum lifetime for an access token in seconds.",
|
||||
accessTokenNumUsesLimit: "The maximum number of times that an access token can be used.",
|
||||
accessTokenTrustedIps: "The IPs or CIDR ranges that access tokens can be used from."
|
||||
accessTokenTrustedIps: "The IPs or CIDR ranges that access tokens can be used from.",
|
||||
lockoutEnabled: "Whether the lockout feature is enabled.",
|
||||
lockoutThreshold: "The amount of times login must fail before locking the identity auth method.",
|
||||
lockoutDurationSeconds: "How long an identity auth method lockout lasts.",
|
||||
lockoutCounterResetSeconds:
|
||||
"How long to wait from the most recent failed login until resetting the lockout counter."
|
||||
},
|
||||
UPDATE: {
|
||||
identityId: "The ID of the identity to update the configuration for.",
|
||||
@@ -257,13 +262,21 @@ export const LDAP_AUTH = {
|
||||
accessTokenMaxTTL: "The new maximum lifetime for an access token in seconds.",
|
||||
accessTokenNumUsesLimit: "The new maximum number of times that an access token can be used.",
|
||||
accessTokenTrustedIps: "The new IPs or CIDR ranges that access tokens can be used from.",
|
||||
templateId: "The ID of the identity auth template to update the configuration to."
|
||||
templateId: "The ID of the identity auth template to update the configuration to.",
|
||||
lockoutEnabled: "Whether the lockout feature is enabled.",
|
||||
lockoutThreshold: "The amount of times login must fail before locking the identity auth method.",
|
||||
lockoutDurationSeconds: "How long an identity auth method lockout lasts.",
|
||||
lockoutCounterResetSeconds:
|
||||
"How long to wait from the most recent failed login until resetting the lockout counter."
|
||||
},
|
||||
RETRIEVE: {
|
||||
identityId: "The ID of the identity to retrieve the configuration for."
|
||||
},
|
||||
REVOKE: {
|
||||
identityId: "The ID of the identity to revoke the configuration for."
|
||||
},
|
||||
CLEAR_CLIENT_LOCKOUTS: {
|
||||
identityId: "The ID of the identity to clear the client lockouts from."
|
||||
}
|
||||
} as const;
|
||||
|
||||
|
||||
@@ -1681,7 +1681,8 @@ export const registerRoutes = async (
|
||||
identityOrgMembershipDAL,
|
||||
licenseService,
|
||||
identityDAL,
|
||||
identityAuthTemplateDAL
|
||||
identityAuthTemplateDAL,
|
||||
keyStore
|
||||
});
|
||||
|
||||
const dynamicSecretProviders = buildDynamicSecretProviders({
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
import { Authenticator } from "@fastify/passport";
|
||||
import fastifySession from "@fastify/session";
|
||||
import { FastifyRequest } from "fastify";
|
||||
import { FastifyReply, FastifyRequest } from "fastify";
|
||||
import { IncomingMessage } from "http";
|
||||
import LdapStrategy from "passport-ldapauth";
|
||||
import { z } from "zod";
|
||||
@@ -135,19 +135,26 @@ export const registerIdentityLdapAuthRouter = async (server: FastifyZodProvider)
|
||||
})
|
||||
}
|
||||
},
|
||||
preValidation: passport.authenticate("ldapauth", {
|
||||
failWithError: true,
|
||||
session: false
|
||||
}) as any,
|
||||
preValidation: [
|
||||
(req, res) => {
|
||||
const passportAuth = (request: FastifyRequest, reply: FastifyReply) =>
|
||||
(
|
||||
passport.authenticate("ldapauth", {
|
||||
failWithError: true,
|
||||
session: false
|
||||
}) as any
|
||||
)(request, reply);
|
||||
|
||||
errorHandler: (error) => {
|
||||
if (error.name === "AuthenticationError") {
|
||||
throw new UnauthorizedError({ message: "Invalid credentials" });
|
||||
const { identityId, username } = req.body;
|
||||
return server.services.identityLdapAuth.withLdapLockout(
|
||||
{
|
||||
identityId,
|
||||
username
|
||||
},
|
||||
() => passportAuth(req, res)
|
||||
);
|
||||
}
|
||||
|
||||
throw error;
|
||||
},
|
||||
|
||||
],
|
||||
handler: async (req) => {
|
||||
if (!req.passportMachineIdentity?.identityId) {
|
||||
throw new UnauthorizedError({ message: "Invalid request. Missing identity ID or LDAP entry details." });
|
||||
@@ -241,7 +248,21 @@ export const registerIdentityLdapAuthRouter = async (server: FastifyZodProvider)
|
||||
.int()
|
||||
.min(0)
|
||||
.default(0)
|
||||
.describe(LDAP_AUTH.ATTACH.accessTokenNumUsesLimit)
|
||||
.describe(LDAP_AUTH.ATTACH.accessTokenNumUsesLimit),
|
||||
lockoutEnabled: z.boolean().default(true).describe(LDAP_AUTH.ATTACH.lockoutEnabled),
|
||||
lockoutThreshold: z.number().min(1).max(30).default(3).describe(LDAP_AUTH.ATTACH.lockoutThreshold),
|
||||
lockoutDurationSeconds: z
|
||||
.number()
|
||||
.min(30)
|
||||
.max(86400)
|
||||
.default(300)
|
||||
.describe(LDAP_AUTH.ATTACH.lockoutDurationSeconds),
|
||||
lockoutCounterResetSeconds: z
|
||||
.number()
|
||||
.min(5)
|
||||
.max(3600)
|
||||
.default(30)
|
||||
.describe(LDAP_AUTH.ATTACH.lockoutCounterResetSeconds)
|
||||
})
|
||||
.refine(
|
||||
(val) => val.accessTokenTTL <= val.accessTokenMaxTTL,
|
||||
@@ -291,7 +312,21 @@ export const registerIdentityLdapAuthRouter = async (server: FastifyZodProvider)
|
||||
.int()
|
||||
.min(0)
|
||||
.default(0)
|
||||
.describe(LDAP_AUTH.ATTACH.accessTokenNumUsesLimit)
|
||||
.describe(LDAP_AUTH.ATTACH.accessTokenNumUsesLimit),
|
||||
lockoutEnabled: z.boolean().default(true).describe(LDAP_AUTH.ATTACH.lockoutEnabled),
|
||||
lockoutThreshold: z.number().min(1).max(30).default(3).describe(LDAP_AUTH.ATTACH.lockoutThreshold),
|
||||
lockoutDurationSeconds: z
|
||||
.number()
|
||||
.min(30)
|
||||
.max(86400)
|
||||
.default(300)
|
||||
.describe(LDAP_AUTH.ATTACH.lockoutDurationSeconds),
|
||||
lockoutCounterResetSeconds: z
|
||||
.number()
|
||||
.min(5)
|
||||
.max(3600)
|
||||
.default(30)
|
||||
.describe(LDAP_AUTH.ATTACH.lockoutCounterResetSeconds)
|
||||
})
|
||||
.refine(
|
||||
(val) => val.accessTokenTTL <= val.accessTokenMaxTTL,
|
||||
@@ -331,7 +366,11 @@ export const registerIdentityLdapAuthRouter = async (server: FastifyZodProvider)
|
||||
accessTokenTTL: identityLdapAuth.accessTokenTTL,
|
||||
accessTokenNumUsesLimit: identityLdapAuth.accessTokenNumUsesLimit,
|
||||
allowedFields: req.body.allowedFields,
|
||||
templateId: identityLdapAuth.templateId
|
||||
templateId: identityLdapAuth.templateId,
|
||||
lockoutEnabled: identityLdapAuth.lockoutEnabled,
|
||||
lockoutThreshold: identityLdapAuth.lockoutThreshold,
|
||||
lockoutDurationSeconds: identityLdapAuth.lockoutDurationSeconds,
|
||||
lockoutCounterResetSeconds: identityLdapAuth.lockoutCounterResetSeconds
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -395,7 +434,21 @@ export const registerIdentityLdapAuthRouter = async (server: FastifyZodProvider)
|
||||
.max(315360000)
|
||||
.min(0)
|
||||
.optional()
|
||||
.describe(LDAP_AUTH.UPDATE.accessTokenMaxTTL)
|
||||
.describe(LDAP_AUTH.UPDATE.accessTokenMaxTTL),
|
||||
lockoutEnabled: z.boolean().optional().describe(LDAP_AUTH.UPDATE.lockoutEnabled),
|
||||
lockoutThreshold: z.number().min(1).max(30).optional().describe(LDAP_AUTH.UPDATE.lockoutThreshold),
|
||||
lockoutDurationSeconds: z
|
||||
.number()
|
||||
.min(30)
|
||||
.max(86400)
|
||||
.optional()
|
||||
.describe(LDAP_AUTH.UPDATE.lockoutDurationSeconds),
|
||||
lockoutCounterResetSeconds: z
|
||||
.number()
|
||||
.min(5)
|
||||
.max(3600)
|
||||
.optional()
|
||||
.describe(LDAP_AUTH.UPDATE.lockoutCounterResetSeconds)
|
||||
})
|
||||
.refine(
|
||||
(val) => (val.accessTokenMaxTTL && val.accessTokenTTL ? val.accessTokenTTL <= val.accessTokenMaxTTL : true),
|
||||
@@ -434,7 +487,11 @@ export const registerIdentityLdapAuthRouter = async (server: FastifyZodProvider)
|
||||
accessTokenNumUsesLimit: identityLdapAuth.accessTokenNumUsesLimit,
|
||||
accessTokenTrustedIps: identityLdapAuth.accessTokenTrustedIps as TIdentityTrustedIp[],
|
||||
allowedFields: req.body.allowedFields,
|
||||
templateId: identityLdapAuth.templateId
|
||||
templateId: identityLdapAuth.templateId,
|
||||
lockoutEnabled: identityLdapAuth.lockoutEnabled,
|
||||
lockoutThreshold: identityLdapAuth.lockoutThreshold,
|
||||
lockoutDurationSeconds: identityLdapAuth.lockoutDurationSeconds,
|
||||
lockoutCounterResetSeconds: identityLdapAuth.lockoutCounterResetSeconds
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -553,4 +610,53 @@ export const registerIdentityLdapAuthRouter = async (server: FastifyZodProvider)
|
||||
return { identityLdapAuth };
|
||||
}
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: "POST",
|
||||
url: "/ldap-auth/identities/:identityId/clear-lockouts",
|
||||
config: {
|
||||
rateLimit: writeLimit
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
schema: {
|
||||
hide: false,
|
||||
tags: [ApiDocsTags.LdapAuth],
|
||||
description: "Clear LDAP Auth Lockouts for identity",
|
||||
security: [
|
||||
{
|
||||
bearerAuth: []
|
||||
}
|
||||
],
|
||||
params: z.object({
|
||||
identityId: z.string().describe(LDAP_AUTH.CLEAR_CLIENT_LOCKOUTS.identityId)
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
deleted: z.number()
|
||||
})
|
||||
}
|
||||
},
|
||||
handler: async (req) => {
|
||||
const clearLockoutsData = await server.services.identityLdapAuth.clearLdapAuthLockouts({
|
||||
actor: req.permission.type,
|
||||
actorId: req.permission.id,
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorOrgId: req.permission.orgId,
|
||||
identityId: req.params.identityId
|
||||
});
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: clearLockoutsData.orgId,
|
||||
event: {
|
||||
type: EventType.CLEAR_IDENTITY_LDAP_AUTH_LOCKOUTS,
|
||||
metadata: {
|
||||
identityId: clearLockoutsData.identityId
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return clearLockoutsData;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
|
||||
import { ForbiddenError } from "@casl/ability";
|
||||
import slugify from "@sindresorhus/slugify";
|
||||
|
||||
import { IdentityAuthMethod } from "@app/db/schemas";
|
||||
import { TIdentityAuthTemplateDALFactory } from "@app/ee/services/identity-auth-template";
|
||||
@@ -15,10 +16,18 @@ import {
|
||||
validatePrivilegeChangeOperation
|
||||
} from "@app/ee/services/permission/permission-fns";
|
||||
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
|
||||
import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
|
||||
import { getConfig } from "@app/lib/config/env";
|
||||
import { crypto } from "@app/lib/crypto";
|
||||
import { BadRequestError, NotFoundError, PermissionBoundaryError } from "@app/lib/errors";
|
||||
import {
|
||||
BadRequestError,
|
||||
NotFoundError,
|
||||
PermissionBoundaryError,
|
||||
RateLimitError,
|
||||
UnauthorizedError
|
||||
} from "@app/lib/errors";
|
||||
import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip";
|
||||
import { logger } from "@app/lib/logger";
|
||||
|
||||
import { ActorType, AuthTokenType } from "../auth/auth-type";
|
||||
import { TIdentityDALFactory } from "../identity/identity-dal";
|
||||
@@ -32,6 +41,8 @@ import { TIdentityLdapAuthDALFactory } from "./identity-ldap-auth-dal";
|
||||
import {
|
||||
AllowedFieldsSchema,
|
||||
TAttachLdapAuthDTO,
|
||||
TCheckLdapAuthLockoutDTO,
|
||||
TClearLdapAuthLockoutsDTO,
|
||||
TGetLdapAuthDTO,
|
||||
TLoginLdapAuthDTO,
|
||||
TRevokeLdapAuthDTO,
|
||||
@@ -50,10 +61,19 @@ type TIdentityLdapAuthServiceFactoryDep = {
|
||||
kmsService: TKmsServiceFactory;
|
||||
identityDAL: TIdentityDALFactory;
|
||||
identityAuthTemplateDAL: TIdentityAuthTemplateDALFactory;
|
||||
keyStore: Pick<
|
||||
TKeyStoreFactory,
|
||||
"setItemWithExpiry" | "getItem" | "deleteItem" | "getKeysByPattern" | "deleteItems" | "acquireLock"
|
||||
>;
|
||||
};
|
||||
|
||||
export type TIdentityLdapAuthServiceFactory = ReturnType<typeof identityLdapAuthServiceFactory>;
|
||||
|
||||
type LockoutObject = {
|
||||
lockedOut: boolean;
|
||||
failedAttempts: number;
|
||||
};
|
||||
|
||||
export const identityLdapAuthServiceFactory = ({
|
||||
identityAccessTokenDAL,
|
||||
identityDAL,
|
||||
@@ -62,7 +82,8 @@ export const identityLdapAuthServiceFactory = ({
|
||||
licenseService,
|
||||
permissionService,
|
||||
kmsService,
|
||||
identityAuthTemplateDAL
|
||||
identityAuthTemplateDAL,
|
||||
keyStore
|
||||
}: TIdentityLdapAuthServiceFactoryDep) => {
|
||||
const getLdapConfig = async (identityId: string) => {
|
||||
const identity = await identityDAL.findOne({ id: identityId });
|
||||
@@ -126,13 +147,17 @@ export const identityLdapAuthServiceFactory = ({
|
||||
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
|
||||
|
||||
if (!identityMembershipOrg) {
|
||||
throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
|
||||
throw new UnauthorizedError({
|
||||
message: "Invalid credentials"
|
||||
});
|
||||
}
|
||||
|
||||
const identityLdapAuth = await identityLdapAuthDAL.findOne({ identityId });
|
||||
|
||||
if (!identityLdapAuth) {
|
||||
throw new NotFoundError({ message: `Failed to find LDAP auth for identity with ID ${identityId}` });
|
||||
throw new UnauthorizedError({
|
||||
message: "Invalid credentials"
|
||||
});
|
||||
}
|
||||
|
||||
const plan = await licenseService.getPlan(identityMembershipOrg.orgId);
|
||||
@@ -204,7 +229,11 @@ export const identityLdapAuthServiceFactory = ({
|
||||
actor,
|
||||
actorOrgId,
|
||||
isActorSuperAdmin,
|
||||
allowedFields
|
||||
allowedFields,
|
||||
lockoutEnabled,
|
||||
lockoutThreshold,
|
||||
lockoutDurationSeconds,
|
||||
lockoutCounterResetSeconds
|
||||
}: TAttachLdapAuthDTO) => {
|
||||
await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);
|
||||
|
||||
@@ -337,7 +366,11 @@ export const identityLdapAuthServiceFactory = ({
|
||||
accessTokenNumUsesLimit,
|
||||
accessTokenTrustedIps: JSON.stringify(reformattedAccessTokenTrustedIps),
|
||||
allowedFields: allowedFields ? JSON.stringify(allowedFields) : undefined,
|
||||
templateId
|
||||
templateId,
|
||||
lockoutEnabled,
|
||||
lockoutThreshold,
|
||||
lockoutDurationSeconds,
|
||||
lockoutCounterResetSeconds
|
||||
},
|
||||
tx
|
||||
);
|
||||
@@ -363,7 +396,11 @@ export const identityLdapAuthServiceFactory = ({
|
||||
actorId,
|
||||
actorAuthMethod,
|
||||
actor,
|
||||
actorOrgId
|
||||
actorOrgId,
|
||||
lockoutEnabled,
|
||||
lockoutThreshold,
|
||||
lockoutDurationSeconds,
|
||||
lockoutCounterResetSeconds
|
||||
}: TUpdateLdapAuthDTO) => {
|
||||
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
|
||||
if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
|
||||
@@ -511,7 +548,11 @@ export const identityLdapAuthServiceFactory = ({
|
||||
accessTokenNumUsesLimit,
|
||||
accessTokenTrustedIps: reformattedAccessTokenTrustedIps
|
||||
? JSON.stringify(reformattedAccessTokenTrustedIps)
|
||||
: undefined
|
||||
: undefined,
|
||||
lockoutEnabled,
|
||||
lockoutThreshold,
|
||||
lockoutDurationSeconds,
|
||||
lockoutCounterResetSeconds
|
||||
});
|
||||
|
||||
return { ...updatedLdapAuth, orgId: identityMembershipOrg.orgId };
|
||||
@@ -611,12 +652,123 @@ export const identityLdapAuthServiceFactory = ({
|
||||
return revokedIdentityLdapAuth;
|
||||
};
|
||||
|
||||
const withLdapLockout = async <T>(
|
||||
{ identityId, username }: TCheckLdapAuthLockoutDTO,
|
||||
authFn: () => Promise<T>
|
||||
): Promise<T> => {
|
||||
const usernameSlug = slugify(username.trim().toLowerCase());
|
||||
|
||||
const LOCKOUT_KEY = `lockout:identity:${identityId}:${IdentityAuthMethod.LDAP_AUTH}:${usernameSlug}`;
|
||||
|
||||
let lock: Awaited<ReturnType<typeof keyStore.acquireLock>>;
|
||||
try {
|
||||
lock = await keyStore.acquireLock([KeyStorePrefixes.IdentityLockoutLock(LOCKOUT_KEY)], 3000, {
|
||||
retryCount: 3,
|
||||
retryDelay: 1500,
|
||||
retryJitter: 100
|
||||
});
|
||||
} catch (e) {
|
||||
logger.info(
|
||||
`identity login failed to acquire lock [identityId=${identityId}] [authMethod=${IdentityAuthMethod.LDAP_AUTH}]`
|
||||
);
|
||||
throw new RateLimitError({ message: "Failed to acquire lock: rate limit exceeded" });
|
||||
}
|
||||
|
||||
try {
|
||||
const lockoutRaw = await keyStore.getItem(LOCKOUT_KEY);
|
||||
if (lockoutRaw) {
|
||||
const lockout = JSON.parse(lockoutRaw) as LockoutObject;
|
||||
if (lockout.lockedOut) {
|
||||
throw new UnauthorizedError({
|
||||
message: "This identity auth method is temporarily locked, please try again later"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const result = await authFn();
|
||||
|
||||
await keyStore.deleteItem(LOCKOUT_KEY);
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
|
||||
if ((error as any).status === 401) {
|
||||
const identityLdapAuth = await identityLdapAuthDAL.findOne({ identityId });
|
||||
if (!identityLdapAuth) {
|
||||
throw new UnauthorizedError({ message: "Invalid credentials" });
|
||||
}
|
||||
|
||||
if (identityLdapAuth.lockoutEnabled) {
|
||||
let lockout: LockoutObject = {
|
||||
lockedOut: false,
|
||||
failedAttempts: 0
|
||||
};
|
||||
|
||||
const lockoutRaw = await keyStore.getItem(LOCKOUT_KEY);
|
||||
if (lockoutRaw) {
|
||||
lockout = JSON.parse(lockoutRaw) as LockoutObject;
|
||||
}
|
||||
|
||||
lockout.failedAttempts += 1;
|
||||
if (lockout.failedAttempts >= identityLdapAuth.lockoutThreshold) {
|
||||
lockout.lockedOut = true;
|
||||
}
|
||||
|
||||
await keyStore.setItemWithExpiry(
|
||||
LOCKOUT_KEY,
|
||||
lockout.lockedOut ? identityLdapAuth.lockoutDurationSeconds : identityLdapAuth.lockoutCounterResetSeconds,
|
||||
JSON.stringify(lockout)
|
||||
);
|
||||
}
|
||||
|
||||
throw new UnauthorizedError({ message: "Invalid credentials" });
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
await lock.release();
|
||||
}
|
||||
};
|
||||
|
||||
const clearLdapAuthLockouts = async ({
|
||||
identityId,
|
||||
actorId,
|
||||
actor,
|
||||
actorOrgId,
|
||||
actorAuthMethod
|
||||
}: TClearLdapAuthLockoutsDTO) => {
|
||||
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
|
||||
if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
|
||||
|
||||
if (!identityMembershipOrg.identity.authMethods.includes(IdentityAuthMethod.LDAP_AUTH)) {
|
||||
throw new BadRequestError({
|
||||
message: "The identity does not have ldap auth"
|
||||
});
|
||||
}
|
||||
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
actor,
|
||||
actorId,
|
||||
identityMembershipOrg.orgId,
|
||||
actorAuthMethod,
|
||||
actorOrgId
|
||||
);
|
||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionIdentityActions.Edit, OrgPermissionSubjects.Identity);
|
||||
|
||||
const deleted = await keyStore.deleteItems({
|
||||
pattern: `lockout:identity:${identityId}:${IdentityAuthMethod.LDAP_AUTH}:*`
|
||||
});
|
||||
|
||||
return { deleted, identityId, orgId: identityMembershipOrg.orgId };
|
||||
};
|
||||
|
||||
return {
|
||||
attachLdapAuth,
|
||||
getLdapConfig,
|
||||
updateLdapAuth,
|
||||
login,
|
||||
revokeIdentityLdapAuth,
|
||||
getLdapAuth
|
||||
getLdapAuth,
|
||||
withLdapLockout,
|
||||
clearLdapAuthLockouts
|
||||
};
|
||||
};
|
||||
|
||||
@@ -27,6 +27,10 @@ export type TAttachLdapAuthDTO = {
|
||||
accessTokenNumUsesLimit: number;
|
||||
accessTokenTrustedIps: { ipAddress: string }[];
|
||||
isActorSuperAdmin?: boolean;
|
||||
lockoutEnabled: boolean;
|
||||
lockoutThreshold: number;
|
||||
lockoutDurationSeconds: number;
|
||||
lockoutCounterResetSeconds: number;
|
||||
} & Omit<TProjectPermission, "projectId">;
|
||||
|
||||
export type TUpdateLdapAuthDTO = {
|
||||
@@ -43,6 +47,10 @@ export type TUpdateLdapAuthDTO = {
|
||||
accessTokenMaxTTL?: number;
|
||||
accessTokenNumUsesLimit?: number;
|
||||
accessTokenTrustedIps?: { ipAddress: string }[];
|
||||
lockoutEnabled?: boolean;
|
||||
lockoutThreshold?: number;
|
||||
lockoutDurationSeconds?: number;
|
||||
lockoutCounterResetSeconds?: number;
|
||||
} & Omit<TProjectPermission, "projectId">;
|
||||
|
||||
export type TGetLdapAuthDTO = {
|
||||
@@ -56,3 +64,12 @@ export type TLoginLdapAuthDTO = {
|
||||
export type TRevokeLdapAuthDTO = {
|
||||
identityId: string;
|
||||
} & Omit<TProjectPermission, "projectId">;
|
||||
|
||||
export type TClearLdapAuthLockoutsDTO = {
|
||||
identityId: string;
|
||||
} & Omit<TProjectPermission, "projectId">;
|
||||
|
||||
export type TCheckLdapAuthLockoutDTO = {
|
||||
identityId: string;
|
||||
username: string;
|
||||
};
|
||||
|
||||
@@ -33,7 +33,7 @@ type TIdentityServiceFactoryDep = {
|
||||
identityProjectDAL: Pick<TIdentityProjectDALFactory, "findByIdentityId">;
|
||||
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getOrgPermissionByRole">;
|
||||
licenseService: Pick<TLicenseServiceFactory, "getPlan" | "updateSubscriptionOrgMemberCount">;
|
||||
keyStore: Pick<TKeyStoreFactory, "getKeysByPattern">;
|
||||
keyStore: Pick<TKeyStoreFactory, "getKeysByPattern" | "getItem">;
|
||||
};
|
||||
|
||||
export type TIdentityServiceFactory = ReturnType<typeof identityServiceFactory>;
|
||||
@@ -261,12 +261,18 @@ export const identityServiceFactory = ({
|
||||
const activeLockouts = await keyStore.getKeysByPattern(`lockout:identity:${id}:*`);
|
||||
|
||||
const activeLockoutAuthMethods = new Set<string>();
|
||||
activeLockouts.forEach((key) => {
|
||||
for await (const key of activeLockouts) {
|
||||
const parts = key.split(":");
|
||||
if (parts.length > 3) {
|
||||
activeLockoutAuthMethods.add(parts[3]);
|
||||
const lockoutRaw = await keyStore.getItem(key);
|
||||
if (lockoutRaw) {
|
||||
const lockout = JSON.parse(lockoutRaw) as { lockedOut: boolean };
|
||||
if (lockout.lockedOut) {
|
||||
activeLockoutAuthMethods.add(parts[3]);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
...identity,
|
||||
|
||||
@@ -34,24 +34,33 @@ To create and manage LDAP auth templates, see our [Machine Identity Auth Templat
|
||||
To configure LDAP auth for your identity, press the **Add Auth Method** button on the identity's page.
|
||||
|
||||

|
||||
|
||||
|
||||
Now select **LDAP Auth** from the list of available auth methods for the identity.
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
|
||||
After selecting **LDAP Auth**, you'll see the form you need to fill out to configure LDAP auth for your identity. The following fields are available:
|
||||
|
||||
**Configuration Tab**
|
||||
- `URL`: The LDAP server to connect to such as `ldap://ldap.your-org.com`, `ldaps://ldap.myorg.com:636` _(for connection over SSL/TLS)_, etc.
|
||||
- `Bind DN`: The DN to bind to the LDAP server with.
|
||||
- `Bind Pass`: The password to bind to the LDAP server with.
|
||||
- `Search Base / DN`: Base DN under which to perform user search such as `ou=Users,dc=acme,dc=com`.
|
||||
- `User Search Filter`: Template used to construct the LDAP user search filter such as `(uid={{username}})`; use literal `{{username}}` to have the given username used in the search. The default is `(uid={{username}})` which is compatible with several common directory schemas.
|
||||
- `Required Attributes`: A key/value pair of attributes that must be present in the LDAP user entry for them to be authenticated. As an example, if you set key `uid` to value `user1,user2,user3`, then only users with `uid` of `user1`, `user2`, or `user3` will be able to login with this identity. Each value is a comma separated list of attributes.
|
||||
- `CA Certificate`: The CA certificate to use when verifying the LDAP server certificate. This field is optional but recommended.
|
||||
- `Access Token TTL` _(default is 2592000 equivalent to 30 days)_: The lifetime for an access token in seconds. This value will be referenced at renewal time.
|
||||
- `Access Token Max TTL` _(default is 2592000 equivalent to 30 days)_: The maximum lifetime for an access token in seconds. This value will be referenced at renewal time.
|
||||
- `Access Token Max Number of Uses` _(default is 0)_: The maximum number of times that an access token can be used; a value of 0 implies infinite number of uses.
|
||||
|
||||
**Lockout Tab**
|
||||
- `Lockout` _(enabled by default)_: The lockout feature will temporarily block login attempts after X consecutive login failures.
|
||||
- `Lockout Threshold` _(default is 3)_: The amount of times login must fail before locking the identity auth method.
|
||||
- `Lockout Duration` _(default is 5 minutes)_: How long an identity auth method lockout lasts.
|
||||
- `Lockout Counter Reset` _(default is 30 seconds)_: How long to wait from the most recent failed login until resetting the lockout counter.
|
||||
|
||||
**Advanced Tab**
|
||||
- `CA Certificate`: The CA certificate to use when verifying the LDAP server certificate. This field is optional but recommended.
|
||||
- `Access Token Trusted IPs`: The IPs or CIDR ranges that access tokens can be used from. By default, each token is given the 0.0.0.0/0, allowing usage from any network address.
|
||||
|
||||
Once you've filled out the form, press **Add** to save your changes.
|
||||
@@ -91,3 +100,13 @@ To create and manage LDAP auth templates, see our [Machine Identity Auth Templat
|
||||
</Step>
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
**FAQ**
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="How do I reset a lockout?">
|
||||
You can reset (remove) all lockouts for an identity auth method by clicking into the auth method and pressing **Reset All Lockouts**.
|
||||
|
||||

|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
BIN
docs/images/platform/identities/ldap-reset-lockouts.png
Normal file
BIN
docs/images/platform/identities/ldap-reset-lockouts.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 211 KiB |
@@ -194,6 +194,7 @@ export const eventToNameMap: { [K in EventType]: string } = {
|
||||
[EventType.UPDATE_IDENTITY_LDAP_AUTH]: "Updated LDAP Auth for identity",
|
||||
[EventType.GET_IDENTITY_LDAP_AUTH]: "Retrieved LDAP Auth for identity",
|
||||
[EventType.REVOKE_IDENTITY_LDAP_AUTH]: "Revoked LDAP Auth for identity",
|
||||
[EventType.CLEAR_IDENTITY_LDAP_AUTH_LOCKOUTS]: "Clear LDAP Auth lockouts",
|
||||
|
||||
[EventType.SECRET_SCANNING_DATA_SOURCE_LIST]: "List Secret Scanning Data Sources",
|
||||
[EventType.SECRET_SCANNING_DATA_SOURCE_CREATE]: "Create Secret Scanning Data Source",
|
||||
|
||||
@@ -54,6 +54,7 @@ export enum EventType {
|
||||
UPDATE_IDENTITY_LDAP_AUTH = "update-identity-ldap-auth",
|
||||
GET_IDENTITY_LDAP_AUTH = "get-identity-ldap-auth",
|
||||
REVOKE_IDENTITY_LDAP_AUTH = "revoke-identity-ldap-auth",
|
||||
CLEAR_IDENTITY_LDAP_AUTH_LOCKOUTS = "clear-identity-ldap-auth-lockouts",
|
||||
|
||||
CREATE_ENVIRONMENT = "create-environment",
|
||||
UPDATE_ENVIRONMENT = "update-environment",
|
||||
|
||||
@@ -874,6 +874,13 @@ interface IntegrationSyncedEvent {
|
||||
};
|
||||
}
|
||||
|
||||
interface ClearIdentityLdapAuthLockoutsEvent {
|
||||
type: EventType.CLEAR_IDENTITY_LDAP_AUTH_LOCKOUTS;
|
||||
metadata: {
|
||||
identityId: string;
|
||||
};
|
||||
}
|
||||
|
||||
export type Event =
|
||||
| GetSecretsEvent
|
||||
| GetSecretEvent
|
||||
@@ -958,7 +965,8 @@ export type Event =
|
||||
| GetCertificateTemplateEstConfig
|
||||
| UpdateProjectWorkflowIntegrationConfig
|
||||
| GetProjectWorkflowIntegrationConfig
|
||||
| IntegrationSyncedEvent;
|
||||
| IntegrationSyncedEvent
|
||||
| ClearIdentityLdapAuthLockoutsEvent;
|
||||
|
||||
export type AuditLog = {
|
||||
id: string;
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
AddIdentityTlsCertAuthDTO,
|
||||
AddIdentityTokenAuthDTO,
|
||||
AddIdentityUniversalAuthDTO,
|
||||
ClearIdentityLdapAuthLockoutsDTO,
|
||||
ClearIdentityUniversalAuthLockoutsDTO,
|
||||
ClientSecretData,
|
||||
CreateIdentityDTO,
|
||||
@@ -1432,7 +1433,11 @@ export const useAddIdentityLdapAuth = () => {
|
||||
accessTokenTTL,
|
||||
accessTokenMaxTTL,
|
||||
accessTokenNumUsesLimit,
|
||||
accessTokenTrustedIps
|
||||
accessTokenTrustedIps,
|
||||
lockoutEnabled,
|
||||
lockoutThreshold,
|
||||
lockoutDurationSeconds,
|
||||
lockoutCounterResetSeconds
|
||||
}) => {
|
||||
const { data } = await apiRequest.post<{ identityLdapAuth: IdentityLdapAuth }>(
|
||||
`/api/v1/auth/ldap-auth/identities/${identityId}`,
|
||||
@@ -1448,7 +1453,11 @@ export const useAddIdentityLdapAuth = () => {
|
||||
accessTokenTTL,
|
||||
accessTokenMaxTTL,
|
||||
accessTokenNumUsesLimit,
|
||||
accessTokenTrustedIps
|
||||
accessTokenTrustedIps,
|
||||
lockoutEnabled,
|
||||
lockoutThreshold,
|
||||
lockoutDurationSeconds,
|
||||
lockoutCounterResetSeconds
|
||||
}
|
||||
);
|
||||
return data.identityLdapAuth;
|
||||
@@ -1481,7 +1490,11 @@ export const useUpdateIdentityLdapAuth = () => {
|
||||
accessTokenTTL,
|
||||
accessTokenMaxTTL,
|
||||
accessTokenNumUsesLimit,
|
||||
accessTokenTrustedIps
|
||||
accessTokenTrustedIps,
|
||||
lockoutEnabled,
|
||||
lockoutThreshold,
|
||||
lockoutDurationSeconds,
|
||||
lockoutCounterResetSeconds
|
||||
}) => {
|
||||
const { data } = await apiRequest.patch<{ identityLdapAuth: IdentityLdapAuth }>(
|
||||
`/api/v1/auth/ldap-auth/identities/${identityId}`,
|
||||
@@ -1497,7 +1510,11 @@ export const useUpdateIdentityLdapAuth = () => {
|
||||
accessTokenTTL,
|
||||
accessTokenMaxTTL,
|
||||
accessTokenNumUsesLimit,
|
||||
accessTokenTrustedIps
|
||||
accessTokenTrustedIps,
|
||||
lockoutEnabled,
|
||||
lockoutThreshold,
|
||||
lockoutDurationSeconds,
|
||||
lockoutCounterResetSeconds
|
||||
}
|
||||
);
|
||||
return data.identityLdapAuth;
|
||||
@@ -1532,3 +1549,22 @@ export const useDeleteIdentityLdapAuth = () => {
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export const useClearIdentityLdapAuthLockouts = () => {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<number, object, ClearIdentityLdapAuthLockoutsDTO>({
|
||||
mutationFn: async ({ identityId }) => {
|
||||
const {
|
||||
data: { deleted }
|
||||
} = await apiRequest.post<{ deleted: number }>(
|
||||
`/api/v1/auth/ldap-auth/identities/${identityId}/clear-lockouts`
|
||||
);
|
||||
return deleted;
|
||||
},
|
||||
onSuccess: (_, { identityId }) => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: identitiesKeys.getIdentityLdapAuth(identityId)
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
@@ -603,6 +603,11 @@ export type AddIdentityLdapAuthDTO = {
|
||||
accessTokenTrustedIps: {
|
||||
ipAddress: string;
|
||||
}[];
|
||||
|
||||
lockoutEnabled: boolean;
|
||||
lockoutThreshold: number;
|
||||
lockoutDurationSeconds: number;
|
||||
lockoutCounterResetSeconds: number;
|
||||
};
|
||||
|
||||
export type UpdateIdentityLdapAuthDTO = {
|
||||
@@ -625,6 +630,11 @@ export type UpdateIdentityLdapAuthDTO = {
|
||||
accessTokenTrustedIps?: {
|
||||
ipAddress: string;
|
||||
}[];
|
||||
|
||||
lockoutEnabled?: boolean;
|
||||
lockoutThreshold?: number;
|
||||
lockoutDurationSeconds?: number;
|
||||
lockoutCounterResetSeconds?: number;
|
||||
};
|
||||
|
||||
export type DeleteIdentityLdapAuthDTO = {
|
||||
@@ -650,6 +660,15 @@ export type IdentityLdapAuth = {
|
||||
accessTokenMaxTTL: number;
|
||||
accessTokenNumUsesLimit: number;
|
||||
accessTokenTrustedIps: IdentityTrustedIp[];
|
||||
|
||||
lockoutEnabled: boolean;
|
||||
lockoutThreshold: number;
|
||||
lockoutDurationSeconds: number;
|
||||
lockoutCounterResetSeconds: number;
|
||||
};
|
||||
|
||||
export type ClearIdentityLdapAuthLockoutsDTO = {
|
||||
identityId: string;
|
||||
};
|
||||
|
||||
export type AddIdentityTokenAuthDTO = {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Controller, useFieldArray, useForm } from "react-hook-form";
|
||||
import { faPlus, faQuestionCircle, faXmark } from "@fortawesome/free-solid-svg-icons";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import ms from "ms";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createNotification } from "@app/components/notifications";
|
||||
@@ -25,6 +26,7 @@ import {
|
||||
OrgPermissionMachineIdentityAuthTemplateActions,
|
||||
OrgPermissionSubjects
|
||||
} from "@app/context/OrgPermissionContext/types";
|
||||
import { getObjectFromSeconds } from "@app/helpers/datetime";
|
||||
import {
|
||||
MachineIdentityAuthMethod,
|
||||
useAddIdentityLdapAuth,
|
||||
@@ -35,6 +37,8 @@ import { IdentityTrustedIp } from "@app/hooks/api/identities/types";
|
||||
import { useGetAvailableTemplates } from "@app/hooks/api/identityAuthTemplates/queries";
|
||||
import { UsePopUpState } from "@app/hooks/usePopUp";
|
||||
|
||||
import { LockoutTab } from "./lockout/LockoutTab";
|
||||
import { superRefineLockout } from "./lockout/super-refine";
|
||||
import { IdentityFormTab } from "./types";
|
||||
|
||||
const schema = z
|
||||
@@ -74,9 +78,28 @@ const schema = z
|
||||
ipAddress: z.string().max(50)
|
||||
})
|
||||
)
|
||||
.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"
|
||||
),
|
||||
lockoutDurationValue: z.string(),
|
||||
lockoutDurationUnit: z.enum(["s", "m", "h", "d"], {
|
||||
invalid_type_error: "Please select a valid time unit"
|
||||
}),
|
||||
lockoutCounterResetValue: z.string(),
|
||||
lockoutCounterResetUnit: z.enum(["s", "m", "h"], {
|
||||
invalid_type_error: "Please select a valid time unit"
|
||||
})
|
||||
})
|
||||
.required()
|
||||
.superRefine((data, ctx) => {
|
||||
superRefineLockout(data, ctx);
|
||||
|
||||
// Validation based on scope
|
||||
if (data.scope === "template") {
|
||||
if (!data.templateId) {
|
||||
@@ -178,12 +201,25 @@ export const IdentityLdapAuthForm = ({
|
||||
accessTokenTTL: "2592000",
|
||||
accessTokenMaxTTL: "2592000",
|
||||
accessTokenNumUsesLimit: "0",
|
||||
accessTokenTrustedIps: [{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }]
|
||||
accessTokenTrustedIps: [{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }],
|
||||
lockoutEnabled: true,
|
||||
lockoutThreshold: "3",
|
||||
lockoutDurationValue: "5",
|
||||
lockoutDurationUnit: "m",
|
||||
lockoutCounterResetValue: "30",
|
||||
lockoutCounterResetUnit: "s"
|
||||
}
|
||||
});
|
||||
|
||||
const scope = watch("scope");
|
||||
|
||||
const lockoutEnabledWatch = watch("lockoutEnabled");
|
||||
const lockoutThresholdWatch = watch("lockoutThreshold");
|
||||
const lockoutDurationValueWatch = watch("lockoutDurationValue");
|
||||
const lockoutDurationUnitWatch = watch("lockoutDurationUnit");
|
||||
const lockoutCounterResetValueWatch = watch("lockoutCounterResetValue");
|
||||
const lockoutCounterResetUnitWatch = watch("lockoutCounterResetUnit");
|
||||
|
||||
const {
|
||||
fields: accessTokenTrustedIpsFields,
|
||||
append: appendAccessTokenTrustedIp,
|
||||
@@ -210,6 +246,9 @@ export const IdentityLdapAuthForm = ({
|
||||
if (data) {
|
||||
const detectedScope = determineScope(data);
|
||||
|
||||
const lockoutDurationObj = getObjectFromSeconds(data.lockoutDurationSeconds);
|
||||
const lockoutCounterResetObj = getObjectFromSeconds(data.lockoutCounterResetSeconds);
|
||||
|
||||
reset({
|
||||
scope: detectedScope,
|
||||
templateId: data.templateId || "",
|
||||
@@ -229,7 +268,13 @@ export const IdentityLdapAuthForm = ({
|
||||
ipAddress: `${ipAddress}${prefix !== undefined ? `/${prefix}` : ""}`
|
||||
};
|
||||
}
|
||||
)
|
||||
),
|
||||
lockoutEnabled: data.lockoutEnabled,
|
||||
lockoutThreshold: String(data.lockoutThreshold),
|
||||
lockoutDurationValue: String(lockoutDurationObj.value),
|
||||
lockoutDurationUnit: lockoutDurationObj.unit as "s" | "m" | "h" | "d",
|
||||
lockoutCounterResetValue: String(lockoutCounterResetObj.value),
|
||||
lockoutCounterResetUnit: lockoutCounterResetObj.unit as "s" | "m" | "h"
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -247,7 +292,13 @@ export const IdentityLdapAuthForm = ({
|
||||
accessTokenTTL: "2592000",
|
||||
accessTokenMaxTTL: "2592000",
|
||||
accessTokenNumUsesLimit: "0",
|
||||
accessTokenTrustedIps: [{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }]
|
||||
accessTokenTrustedIps: [{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }],
|
||||
lockoutEnabled: true,
|
||||
lockoutThreshold: "3",
|
||||
lockoutDurationValue: "5",
|
||||
lockoutDurationUnit: "m",
|
||||
lockoutCounterResetValue: "30",
|
||||
lockoutCounterResetUnit: "s"
|
||||
});
|
||||
}, [data, reset]);
|
||||
|
||||
@@ -275,9 +326,19 @@ export const IdentityLdapAuthForm = ({
|
||||
accessTokenTTL,
|
||||
accessTokenMaxTTL,
|
||||
accessTokenNumUsesLimit,
|
||||
accessTokenTrustedIps
|
||||
accessTokenTrustedIps,
|
||||
lockoutEnabled,
|
||||
lockoutThreshold,
|
||||
lockoutDurationValue,
|
||||
lockoutDurationUnit,
|
||||
lockoutCounterResetValue,
|
||||
lockoutCounterResetUnit
|
||||
} = formData;
|
||||
|
||||
const lockoutDurationSeconds = ms(`${lockoutDurationValue}${lockoutDurationUnit}`) / 1000;
|
||||
const lockoutCounterResetSeconds =
|
||||
ms(`${lockoutCounterResetValue}${lockoutCounterResetUnit}`) / 1000;
|
||||
|
||||
const basePayload = {
|
||||
organizationId: orgId,
|
||||
identityId,
|
||||
@@ -287,7 +348,11 @@ export const IdentityLdapAuthForm = ({
|
||||
accessTokenTTL: Number(accessTokenTTL),
|
||||
accessTokenMaxTTL: Number(accessTokenMaxTTL),
|
||||
accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit),
|
||||
accessTokenTrustedIps
|
||||
accessTokenTrustedIps,
|
||||
lockoutEnabled,
|
||||
lockoutThreshold: Number(lockoutThreshold),
|
||||
lockoutDurationSeconds,
|
||||
lockoutCounterResetSeconds
|
||||
};
|
||||
|
||||
// Add scope-specific fields
|
||||
@@ -327,7 +392,10 @@ export const IdentityLdapAuthForm = ({
|
||||
return (
|
||||
<form
|
||||
onSubmit={handleSubmit(onFormSubmit, (fields) => {
|
||||
setTabValue(
|
||||
const firstErrorField = Object.keys(fields)[0];
|
||||
let tab = IdentityFormTab.Advanced;
|
||||
|
||||
if (
|
||||
[
|
||||
"scope",
|
||||
"templateId",
|
||||
@@ -340,15 +408,29 @@ export const IdentityLdapAuthForm = ({
|
||||
"allowedFields",
|
||||
"accessTokenMaxTTL",
|
||||
"accessTokenNumUsesLimit"
|
||||
].includes(Object.keys(fields)[0])
|
||||
? IdentityFormTab.Configuration
|
||||
: IdentityFormTab.Advanced
|
||||
);
|
||||
].includes(firstErrorField)
|
||||
) {
|
||||
tab = IdentityFormTab.Configuration;
|
||||
} else if (
|
||||
[
|
||||
"lockoutEnabled",
|
||||
"lockoutThreshold",
|
||||
"lockoutDurationValue",
|
||||
"lockoutDurationUnit",
|
||||
"lockoutCounterResetValue",
|
||||
"lockoutCounterResetUnit"
|
||||
].includes(firstErrorField)
|
||||
) {
|
||||
tab = IdentityFormTab.Lockout;
|
||||
}
|
||||
|
||||
setTabValue(tab);
|
||||
})}
|
||||
>
|
||||
<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}>
|
||||
@@ -691,6 +773,15 @@ export const IdentityLdapAuthForm = ({
|
||||
)}
|
||||
/>
|
||||
</TabPanel>
|
||||
<LockoutTab
|
||||
control={control}
|
||||
lockoutEnabled={lockoutEnabledWatch}
|
||||
lockoutThreshold={lockoutThresholdWatch}
|
||||
lockoutDurationValue={lockoutDurationValueWatch}
|
||||
lockoutDurationUnit={lockoutDurationUnitWatch}
|
||||
lockoutCounterResetValue={lockoutCounterResetValueWatch}
|
||||
lockoutCounterResetUnit={lockoutCounterResetUnitWatch}
|
||||
/>
|
||||
<TabPanel value={IdentityFormTab.Advanced}>
|
||||
<Controller
|
||||
control={control}
|
||||
|
||||
@@ -12,9 +12,6 @@ import {
|
||||
FormControl,
|
||||
IconButton,
|
||||
Input,
|
||||
Select,
|
||||
SelectItem,
|
||||
Switch,
|
||||
Tab,
|
||||
TabList,
|
||||
TabPanel,
|
||||
@@ -30,6 +27,8 @@ import {
|
||||
import { IdentityTrustedIp } from "@app/hooks/api/identities/types";
|
||||
import { UsePopUpState } from "@app/hooks/usePopUp";
|
||||
|
||||
import { LockoutTab } from "./lockout/LockoutTab";
|
||||
import { superRefineLockout } from "./lockout/super-refine";
|
||||
import { IdentityFormTab } from "./types";
|
||||
|
||||
const schema = z
|
||||
@@ -83,61 +82,7 @@ const schema = z
|
||||
})
|
||||
})
|
||||
.required()
|
||||
.superRefine((data, ctx) => {
|
||||
const {
|
||||
lockoutDurationValue,
|
||||
lockoutCounterResetValue,
|
||||
lockoutDurationUnit,
|
||||
lockoutCounterResetUnit,
|
||||
lockoutEnabled
|
||||
} = data;
|
||||
|
||||
if (!lockoutEnabled) return;
|
||||
|
||||
let isAnyParseError = false;
|
||||
|
||||
const parsedLockoutDuration = parseInt(lockoutDurationValue, 10);
|
||||
if (Number.isNaN(parsedLockoutDuration)) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "Lockout duration must be a number",
|
||||
path: ["lockoutDurationValue"]
|
||||
});
|
||||
isAnyParseError = true;
|
||||
}
|
||||
|
||||
const parsedLockoutCounterReset = parseInt(lockoutCounterResetValue, 10);
|
||||
if (Number.isNaN(parsedLockoutCounterReset)) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "Lockout counter reset must be a number",
|
||||
path: ["lockoutCounterResetValue"]
|
||||
});
|
||||
isAnyParseError = true;
|
||||
}
|
||||
|
||||
if (isAnyParseError) return;
|
||||
|
||||
const lockoutDurationInSeconds = ms(`${parsedLockoutDuration}${lockoutDurationUnit}`) / 1000;
|
||||
const lockoutCounterResetInSeconds =
|
||||
ms(`${parsedLockoutCounterReset}${lockoutCounterResetUnit}`) / 1000;
|
||||
|
||||
if (lockoutDurationInSeconds > 86400 || lockoutDurationInSeconds < 30) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "Lockout duration must be between 30 seconds and 1 day",
|
||||
path: ["lockoutDurationValue"]
|
||||
});
|
||||
}
|
||||
|
||||
if (lockoutCounterResetInSeconds > 3600 || lockoutCounterResetInSeconds < 5) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "Lockout counter reset must be between 5 seconds and 1 hour",
|
||||
path: ["lockoutCounterResetValue"]
|
||||
});
|
||||
}
|
||||
});
|
||||
.superRefine(superRefineLockout);
|
||||
|
||||
export type FormData = z.infer<typeof schema>;
|
||||
|
||||
@@ -432,187 +377,15 @@ export const IdentityUniversalAuthForm = ({
|
||||
)}
|
||||
/>
|
||||
</TabPanel>
|
||||
<TabPanel value={IdentityFormTab.Lockout}>
|
||||
<div className="mb-3 flex flex-col">
|
||||
<Controller
|
||||
control={control}
|
||||
name="lockoutEnabled"
|
||||
defaultValue
|
||||
render={({ field: { value, onChange }, fieldState: { error } }) => {
|
||||
return (
|
||||
<FormControl
|
||||
helperText={`The lockout feature will prevent login attempts for ${lockoutDurationValueWatch}${lockoutDurationUnitWatch} after ${lockoutThresholdWatch} consecutive login failures. If ${lockoutCounterResetValueWatch}${lockoutCounterResetUnitWatch} 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
|
||||
</Switch>
|
||||
</FormControl>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Controller
|
||||
control={control}
|
||||
name="lockoutThreshold"
|
||||
render={({ field, fieldState: { error } }) => {
|
||||
return (
|
||||
<FormControl
|
||||
className={`mb-0 flex-grow ${lockoutEnabledWatch ? "" : "opacity-70"}`}
|
||||
label="Lockout Threshold"
|
||||
isError={Boolean(error)}
|
||||
errorText={error?.message}
|
||||
tooltipText="The amount of times login must fail before locking the identity auth method"
|
||||
>
|
||||
<Input
|
||||
{...field}
|
||||
placeholder="Enter lockout threshold..."
|
||||
isDisabled={!lockoutEnabledWatch}
|
||||
/>
|
||||
</FormControl>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<div className="flex items-end gap-2">
|
||||
<Controller
|
||||
control={control}
|
||||
name="lockoutDurationValue"
|
||||
render={({ field, fieldState: { error } }) => {
|
||||
return (
|
||||
<FormControl
|
||||
className={`mb-0 flex-grow ${lockoutEnabledWatch ? "" : "opacity-70"}`}
|
||||
label="Lockout Duration"
|
||||
isError={Boolean(error)}
|
||||
errorText={error?.message}
|
||||
tooltipText="How long an identity auth method lockout lasts"
|
||||
>
|
||||
<Input
|
||||
{...field}
|
||||
placeholder="Enter lockout duration..."
|
||||
isDisabled={!lockoutEnabledWatch}
|
||||
/>
|
||||
</FormControl>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<Controller
|
||||
control={control}
|
||||
name="lockoutDurationUnit"
|
||||
render={({ field, fieldState: { error } }) => (
|
||||
<FormControl
|
||||
className={`mb-0 ${lockoutEnabledWatch ? "" : "opacity-70"}`}
|
||||
isError={Boolean(error)}
|
||||
errorText={error?.message}
|
||||
>
|
||||
<Select
|
||||
isDisabled={!lockoutEnabledWatch}
|
||||
value={field.value}
|
||||
className="min-w-32 pr-2"
|
||||
onValueChange={field.onChange}
|
||||
position="popper"
|
||||
>
|
||||
<SelectItem
|
||||
value="s"
|
||||
className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
|
||||
>
|
||||
<div className="ml-3 font-medium">Seconds</div>
|
||||
</SelectItem>
|
||||
<SelectItem
|
||||
value="m"
|
||||
className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
|
||||
>
|
||||
<div className="ml-3 font-medium">Minutes</div>
|
||||
</SelectItem>
|
||||
<SelectItem
|
||||
value="h"
|
||||
className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
|
||||
>
|
||||
<div className="ml-3 font-medium">Hours</div>
|
||||
</SelectItem>
|
||||
<SelectItem
|
||||
value="d"
|
||||
className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
|
||||
>
|
||||
<div className="ml-3 font-medium">Days</div>
|
||||
</SelectItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-end gap-2">
|
||||
<Controller
|
||||
control={control}
|
||||
name="lockoutCounterResetValue"
|
||||
render={({ field, fieldState: { error } }) => {
|
||||
return (
|
||||
<FormControl
|
||||
className={`mb-0 flex-grow ${lockoutEnabledWatch ? "" : "opacity-70"}`}
|
||||
label="Lockout Counter Reset"
|
||||
isError={Boolean(error)}
|
||||
errorText={error?.message}
|
||||
tooltipText="How long to wait from the most recent failed login until resetting the lockout counter"
|
||||
>
|
||||
<Input
|
||||
{...field}
|
||||
placeholder="Enter lockout counter reset..."
|
||||
isDisabled={!lockoutEnabledWatch}
|
||||
/>
|
||||
</FormControl>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<Controller
|
||||
control={control}
|
||||
name="lockoutCounterResetUnit"
|
||||
render={({ field, fieldState: { error } }) => (
|
||||
<FormControl
|
||||
className={`mb-0 ${lockoutEnabledWatch ? "" : "opacity-70"}`}
|
||||
isError={Boolean(error)}
|
||||
errorText={error?.message}
|
||||
>
|
||||
<Select
|
||||
isDisabled={!lockoutEnabledWatch}
|
||||
value={field.value}
|
||||
className="min-w-32 pr-2"
|
||||
onValueChange={field.onChange}
|
||||
position="popper"
|
||||
>
|
||||
<SelectItem
|
||||
value="s"
|
||||
className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
|
||||
>
|
||||
<div className="ml-3 font-medium">Seconds</div>
|
||||
</SelectItem>
|
||||
<SelectItem
|
||||
value="m"
|
||||
className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
|
||||
>
|
||||
<div className="ml-3 font-medium">Minutes</div>
|
||||
</SelectItem>
|
||||
<SelectItem
|
||||
value="h"
|
||||
className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
|
||||
>
|
||||
<div className="ml-3 font-medium">Hours</div>
|
||||
</SelectItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</TabPanel>
|
||||
|
||||
<LockoutTab
|
||||
control={control}
|
||||
lockoutEnabled={lockoutEnabledWatch}
|
||||
lockoutThreshold={lockoutThresholdWatch}
|
||||
lockoutDurationValue={lockoutDurationValueWatch}
|
||||
lockoutDurationUnit={lockoutDurationUnitWatch}
|
||||
lockoutCounterResetValue={lockoutCounterResetValueWatch}
|
||||
lockoutCounterResetUnit={lockoutCounterResetUnitWatch}
|
||||
/>
|
||||
<TabPanel value={IdentityFormTab.Advanced}>
|
||||
{clientSecretTrustedIpsFields.map(({ id }, index) => (
|
||||
<div className="mb-3 flex items-end space-x-2" key={id}>
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
import { Control, Controller } from "react-hook-form";
|
||||
|
||||
import { FormControl, Input, Select, SelectItem, Switch, TabPanel } from "@app/components/v2";
|
||||
|
||||
import { IdentityFormTab } from "../types";
|
||||
|
||||
export const LockoutTab = ({
|
||||
control,
|
||||
lockoutEnabled,
|
||||
lockoutThreshold,
|
||||
lockoutDurationValue,
|
||||
lockoutDurationUnit,
|
||||
lockoutCounterResetValue,
|
||||
lockoutCounterResetUnit
|
||||
}: {
|
||||
control: Control<any>;
|
||||
lockoutEnabled: boolean;
|
||||
lockoutThreshold: string;
|
||||
lockoutDurationValue: string;
|
||||
lockoutDurationUnit: "s" | "m" | "h" | "d";
|
||||
lockoutCounterResetValue: string;
|
||||
lockoutCounterResetUnit: "s" | "m" | "h";
|
||||
}) => {
|
||||
return (
|
||||
<TabPanel value={IdentityFormTab.Lockout}>
|
||||
<div className="mb-3 flex flex-col">
|
||||
<Controller
|
||||
control={control}
|
||||
name="lockoutEnabled"
|
||||
render={({ field: { value, onChange }, fieldState: { error } }) => {
|
||||
return (
|
||||
<FormControl
|
||||
helperText={`The lockout feature will prevent login attempts for ${lockoutDurationValue}${lockoutDurationUnit} after ${lockoutThreshold} consecutive login failures. If ${lockoutCounterResetValue}${lockoutCounterResetUnit} 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
|
||||
</Switch>
|
||||
</FormControl>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<div className="flex flex-col gap-2">
|
||||
<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}
|
||||
tooltipText="The amount of times login must fail before locking the identity auth method"
|
||||
>
|
||||
<Input
|
||||
{...field}
|
||||
placeholder="Enter lockout threshold..."
|
||||
isDisabled={!lockoutEnabled}
|
||||
/>
|
||||
</FormControl>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<div className="flex items-end gap-2">
|
||||
<Controller
|
||||
control={control}
|
||||
name="lockoutDurationValue"
|
||||
render={({ field, fieldState: { error } }) => {
|
||||
return (
|
||||
<FormControl
|
||||
className={`mb-0 flex-grow ${lockoutEnabled ? "" : "opacity-70"}`}
|
||||
label="Lockout Duration"
|
||||
isError={Boolean(error)}
|
||||
errorText={error?.message}
|
||||
tooltipText="How long an identity auth method lockout lasts"
|
||||
>
|
||||
<Input
|
||||
{...field}
|
||||
placeholder="Enter lockout duration..."
|
||||
isDisabled={!lockoutEnabled}
|
||||
/>
|
||||
</FormControl>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<Controller
|
||||
control={control}
|
||||
name="lockoutDurationUnit"
|
||||
render={({ field, fieldState: { error } }) => (
|
||||
<FormControl
|
||||
className={`mb-0 ${lockoutEnabled ? "" : "opacity-70"}`}
|
||||
isError={Boolean(error)}
|
||||
errorText={error?.message}
|
||||
>
|
||||
<Select
|
||||
isDisabled={!lockoutEnabled}
|
||||
value={field.value}
|
||||
className="min-w-32 pr-2"
|
||||
onValueChange={field.onChange}
|
||||
position="popper"
|
||||
>
|
||||
<SelectItem
|
||||
value="s"
|
||||
className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
|
||||
>
|
||||
<div className="ml-3 font-medium">Seconds</div>
|
||||
</SelectItem>
|
||||
<SelectItem
|
||||
value="m"
|
||||
className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
|
||||
>
|
||||
<div className="ml-3 font-medium">Minutes</div>
|
||||
</SelectItem>
|
||||
<SelectItem
|
||||
value="h"
|
||||
className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
|
||||
>
|
||||
<div className="ml-3 font-medium">Hours</div>
|
||||
</SelectItem>
|
||||
<SelectItem
|
||||
value="d"
|
||||
className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
|
||||
>
|
||||
<div className="ml-3 font-medium">Days</div>
|
||||
</SelectItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-end gap-2">
|
||||
<Controller
|
||||
control={control}
|
||||
name="lockoutCounterResetValue"
|
||||
render={({ field, fieldState: { error } }) => {
|
||||
return (
|
||||
<FormControl
|
||||
className={`mb-0 flex-grow ${lockoutEnabled ? "" : "opacity-70"}`}
|
||||
label="Lockout Counter Reset"
|
||||
isError={Boolean(error)}
|
||||
errorText={error?.message}
|
||||
tooltipText="How long to wait from the most recent failed login until resetting the lockout counter"
|
||||
>
|
||||
<Input
|
||||
{...field}
|
||||
placeholder="Enter lockout counter reset..."
|
||||
isDisabled={!lockoutEnabled}
|
||||
/>
|
||||
</FormControl>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<Controller
|
||||
control={control}
|
||||
name="lockoutCounterResetUnit"
|
||||
render={({ field, fieldState: { error } }) => (
|
||||
<FormControl
|
||||
className={`mb-0 ${lockoutEnabled ? "" : "opacity-70"}`}
|
||||
isError={Boolean(error)}
|
||||
errorText={error?.message}
|
||||
>
|
||||
<Select
|
||||
isDisabled={!lockoutEnabled}
|
||||
value={field.value}
|
||||
className="min-w-32 pr-2"
|
||||
onValueChange={field.onChange}
|
||||
position="popper"
|
||||
>
|
||||
<SelectItem
|
||||
value="s"
|
||||
className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
|
||||
>
|
||||
<div className="ml-3 font-medium">Seconds</div>
|
||||
</SelectItem>
|
||||
<SelectItem
|
||||
value="m"
|
||||
className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
|
||||
>
|
||||
<div className="ml-3 font-medium">Minutes</div>
|
||||
</SelectItem>
|
||||
<SelectItem
|
||||
value="h"
|
||||
className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
|
||||
>
|
||||
<div className="ml-3 font-medium">Hours</div>
|
||||
</SelectItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</TabPanel>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,67 @@
|
||||
import ms from "ms";
|
||||
import { z } from "zod";
|
||||
|
||||
export function superRefineLockout(
|
||||
data: {
|
||||
lockoutDurationValue: string;
|
||||
lockoutCounterResetValue: string;
|
||||
lockoutDurationUnit: "s" | "m" | "h" | "d";
|
||||
lockoutCounterResetUnit: "s" | "m" | "h";
|
||||
lockoutEnabled: boolean;
|
||||
},
|
||||
ctx: z.RefinementCtx
|
||||
) {
|
||||
const {
|
||||
lockoutDurationValue,
|
||||
lockoutCounterResetValue,
|
||||
lockoutDurationUnit,
|
||||
lockoutCounterResetUnit,
|
||||
lockoutEnabled
|
||||
} = data;
|
||||
|
||||
if (lockoutEnabled) {
|
||||
let isAnyParseError = false;
|
||||
|
||||
const parsedLockoutDuration = parseInt(lockoutDurationValue, 10);
|
||||
if (Number.isNaN(parsedLockoutDuration)) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "Lockout duration must be a number",
|
||||
path: ["lockoutDurationValue"]
|
||||
});
|
||||
isAnyParseError = true;
|
||||
}
|
||||
|
||||
const parsedLockoutCounterReset = parseInt(lockoutCounterResetValue, 10);
|
||||
if (Number.isNaN(parsedLockoutCounterReset)) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "Lockout counter reset must be a number",
|
||||
path: ["lockoutCounterResetValue"]
|
||||
});
|
||||
isAnyParseError = true;
|
||||
}
|
||||
|
||||
if (!isAnyParseError) {
|
||||
const lockoutDurationInSeconds = ms(`${parsedLockoutDuration}${lockoutDurationUnit}`) / 1000;
|
||||
const lockoutCounterResetInSeconds =
|
||||
ms(`${parsedLockoutCounterReset}${lockoutCounterResetUnit}`) / 1000;
|
||||
|
||||
if (lockoutDurationInSeconds > 86400 || lockoutDurationInSeconds < 30) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "Lockout duration must be between 30 seconds and 1 day",
|
||||
path: ["lockoutDurationValue"]
|
||||
});
|
||||
}
|
||||
|
||||
if (lockoutCounterResetInSeconds > 3600 || lockoutCounterResetInSeconds < 5) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "Lockout counter reset must be between 5 seconds and 1 hour",
|
||||
path: ["lockoutCounterResetValue"]
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { useState } from "react";
|
||||
import { UseMutationResult } from "@tanstack/react-query";
|
||||
import ms from "ms";
|
||||
|
||||
import { createNotification } from "@app/components/notifications";
|
||||
import { OrgPermissionCan } from "@app/components/permissions";
|
||||
import { Button } from "@app/components/v2";
|
||||
import { OrgPermissionIdentityActions, OrgPermissionSubjects } from "@app/context";
|
||||
|
||||
import { IdentityAuthFieldDisplay } from "./IdentityAuthFieldDisplay";
|
||||
|
||||
export const LockoutFields = ({
|
||||
clearLockoutsResult,
|
||||
lockedOut,
|
||||
identityId,
|
||||
data,
|
||||
onResetAllLockouts
|
||||
}: {
|
||||
clearLockoutsResult: UseMutationResult<number, object, { identityId: string }, unknown>;
|
||||
lockedOut: boolean;
|
||||
identityId: string;
|
||||
data: {
|
||||
lockoutEnabled: boolean;
|
||||
lockoutThreshold: number;
|
||||
lockoutDurationSeconds: number;
|
||||
lockoutCounterResetSeconds: number;
|
||||
};
|
||||
onResetAllLockouts: () => void;
|
||||
}) => {
|
||||
const { mutateAsync, isPending } = clearLockoutsResult;
|
||||
|
||||
const [lockedOutState, setLockedOutState] = useState(lockedOut);
|
||||
|
||||
async function clearLockouts() {
|
||||
try {
|
||||
const deleted = await mutateAsync({ identityId });
|
||||
createNotification({
|
||||
text: `Successfully cleared ${deleted} lockout${deleted === 1 ? "" : "s"}`,
|
||||
type: "success"
|
||||
});
|
||||
setLockedOutState(false);
|
||||
onResetAllLockouts();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
createNotification({
|
||||
text: "Failed to clear lockouts. Please try again.",
|
||||
type: "error"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<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 || isPending}
|
||||
size="xs"
|
||||
onClick={() => clearLockouts()}
|
||||
isLoading={isPending}
|
||||
colorSchema="secondary"
|
||||
>
|
||||
Reset All Lockouts
|
||||
</Button>
|
||||
)}
|
||||
</OrgPermissionCan>
|
||||
</div>
|
||||
<IdentityAuthFieldDisplay label="Lockout Threshold">
|
||||
{data.lockoutThreshold}
|
||||
</IdentityAuthFieldDisplay>
|
||||
<IdentityAuthFieldDisplay label="Lockout Duration">
|
||||
{ms(data.lockoutDurationSeconds * 1000, { long: true })}
|
||||
</IdentityAuthFieldDisplay>
|
||||
<IdentityAuthFieldDisplay label="Lockout Counter Reset">
|
||||
{ms(data.lockoutCounterResetSeconds * 1000, { long: true })}
|
||||
</IdentityAuthFieldDisplay>
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -2,11 +2,12 @@ import { faBan, faEye } from "@fortawesome/free-solid-svg-icons";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
|
||||
import { Badge, EmptyState, Spinner, Tooltip } from "@app/components/v2";
|
||||
import { useGetIdentityLdapAuth } from "@app/hooks/api";
|
||||
import { useClearIdentityLdapAuthLockouts, useGetIdentityLdapAuth } from "@app/hooks/api";
|
||||
import { IdentityLdapAuthForm } from "@app/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLdapAuthForm";
|
||||
import { ViewIdentityContentWrapper } from "@app/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/ViewIdentityContentWrapper";
|
||||
|
||||
import { IdentityAuthFieldDisplay } from "./IdentityAuthFieldDisplay";
|
||||
import { LockoutFields } from "./IdentityAuthLockoutFields";
|
||||
import { ViewAuthMethodProps } from "./types";
|
||||
|
||||
export const ViewIdentityLdapAuthContent = ({
|
||||
@@ -14,9 +15,12 @@ export const ViewIdentityLdapAuthContent = ({
|
||||
handlePopUpToggle,
|
||||
handlePopUpOpen,
|
||||
onDelete,
|
||||
popUp
|
||||
popUp,
|
||||
lockedOut,
|
||||
onResetAllLockouts
|
||||
}: ViewAuthMethodProps) => {
|
||||
const { data, isPending } = useGetIdentityLdapAuth(identityId);
|
||||
const clearLockoutsResult = useClearIdentityLdapAuthLockouts();
|
||||
|
||||
if (isPending) {
|
||||
return (
|
||||
@@ -98,6 +102,18 @@ export const ViewIdentityLdapAuthContent = ({
|
||||
</Tooltip>
|
||||
)}
|
||||
</IdentityAuthFieldDisplay>
|
||||
<IdentityAuthFieldDisplay label="Lockout">
|
||||
{data.lockoutEnabled ? "Enabled" : "Disabled"}
|
||||
</IdentityAuthFieldDisplay>
|
||||
{data.lockoutEnabled && (
|
||||
<LockoutFields
|
||||
identityId={identityId}
|
||||
lockedOut={lockedOut}
|
||||
clearLockoutsResult={clearLockoutsResult}
|
||||
data={data}
|
||||
onResetAllLockouts={onResetAllLockouts}
|
||||
/>
|
||||
)}
|
||||
</ViewIdentityContentWrapper>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,12 +1,7 @@
|
||||
import { useState } from "react";
|
||||
import { faBan, faCheck, faCopy } from "@fortawesome/free-solid-svg-icons";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import ms from "ms";
|
||||
|
||||
import { createNotification } from "@app/components/notifications";
|
||||
import { OrgPermissionCan } from "@app/components/permissions";
|
||||
import { Button, EmptyState, IconButton, Spinner, Tooltip } from "@app/components/v2";
|
||||
import { OrgPermissionIdentityActions, OrgPermissionSubjects } from "@app/context";
|
||||
import { EmptyState, IconButton, Spinner, Tooltip } from "@app/components/v2";
|
||||
import { useTimedReset } from "@app/hooks";
|
||||
import {
|
||||
useClearIdentityUniversalAuthLockouts,
|
||||
@@ -16,6 +11,7 @@ import {
|
||||
import { IdentityUniversalAuthForm } from "@app/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityUniversalAuthForm";
|
||||
|
||||
import { IdentityAuthFieldDisplay } from "./IdentityAuthFieldDisplay";
|
||||
import { LockoutFields } from "./IdentityAuthLockoutFields";
|
||||
import { IdentityUniversalAuthClientSecretsTable } from "./IdentityUniversalAuthClientSecretsTable";
|
||||
import { ViewAuthMethodProps } from "./types";
|
||||
import { ViewIdentityContentWrapper } from "./ViewIdentityContentWrapper";
|
||||
@@ -32,33 +28,12 @@ export const ViewIdentityUniversalAuthContent = ({
|
||||
const { data, isPending } = useGetIdentityUniversalAuth(identityId);
|
||||
const { data: clientSecrets = [], isPending: clientSecretsPending } =
|
||||
useGetIdentityUniversalAuthClientSecrets(identityId);
|
||||
const { mutateAsync: clearLockoutsFn, isPending: isClearLockoutsPending } =
|
||||
useClearIdentityUniversalAuthLockouts();
|
||||
|
||||
const [lockedOutState, setLockedOutState] = useState(lockedOut);
|
||||
const clearLockoutsResult = useClearIdentityUniversalAuthLockouts();
|
||||
|
||||
const [copyTextClientId, isCopyingClientId, setCopyTextClientId] = useTimedReset<string>({
|
||||
initialState: "Copy Client ID to clipboard"
|
||||
});
|
||||
|
||||
async function clearLockouts() {
|
||||
try {
|
||||
const deleted = await clearLockoutsFn({ identityId });
|
||||
createNotification({
|
||||
text: `Successfully cleared ${deleted} lockout${deleted === 1 ? "" : "s"}`,
|
||||
type: "success"
|
||||
});
|
||||
setLockedOutState(false);
|
||||
onResetAllLockouts();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
createNotification({
|
||||
text: "Failed to clear lockouts. Please try again.",
|
||||
type: "error"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (isPending || clientSecretsPending) {
|
||||
return (
|
||||
<div className="flex w-full items-center justify-center">
|
||||
@@ -119,36 +94,13 @@ export const ViewIdentityUniversalAuthContent = ({
|
||||
{data.lockoutEnabled ? "Enabled" : "Disabled"}
|
||||
</IdentityAuthFieldDisplay>
|
||||
{data.lockoutEnabled && (
|
||||
<>
|
||||
<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()}
|
||||
isLoading={isClearLockoutsPending}
|
||||
colorSchema="secondary"
|
||||
>
|
||||
Reset All Lockouts
|
||||
</Button>
|
||||
)}
|
||||
</OrgPermissionCan>
|
||||
</div>
|
||||
<IdentityAuthFieldDisplay label="Lockout Threshold">
|
||||
{data.lockoutThreshold}
|
||||
</IdentityAuthFieldDisplay>
|
||||
<IdentityAuthFieldDisplay label="Lockout Duration">
|
||||
{ms(data.lockoutDurationSeconds * 1000, { long: true })}
|
||||
</IdentityAuthFieldDisplay>
|
||||
<IdentityAuthFieldDisplay label="Lockout Counter Reset">
|
||||
{ms(data.lockoutCounterResetSeconds * 1000, { long: true })}
|
||||
</IdentityAuthFieldDisplay>
|
||||
</>
|
||||
<LockoutFields
|
||||
identityId={identityId}
|
||||
lockedOut={lockedOut}
|
||||
clearLockoutsResult={clearLockoutsResult}
|
||||
data={data}
|
||||
onResetAllLockouts={onResetAllLockouts}
|
||||
/>
|
||||
)}
|
||||
<div className="col-span-2 my-3">
|
||||
<div className="mb-3 border-b border-mineshaft-500 pb-2">
|
||||
|
||||
Reference in New Issue
Block a user