Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: add hash operations for identity lockout management
Victor Hugo dos Santos809047b6aa53
diff --git a/backend/e2e-test/mocks/keystore.ts b/backend/e2e-test/mocks/keystore.tsindex e6893151cd..5cd33a122f 100644--- a/backend/e2e-test/mocks/keystore.ts+++ b/backend/e2e-test/mocks/keystore.ts@@ -111,6 +111,29 @@ export const mockKeyStore = (): TKeyStoreFactory => {hashGet: async (key, field) => {return hashStore[key]?.[field] ?? null;},+ hashGetAll: async (key) => {+ return { ...(hashStore[key] ?? {}) };+ },+ hashGetAllPrimary: async (key) => {+ return { ...(hashStore[key] ?? {}) };+ },+ hashSetFieldWithMinExpiry: async (key, field, value) => {+ if (!hashStore[key]) hashStore[key] = {};+ hashStore[key][field] = value;+ },+ hashDeleteFields: async (key, fields) => {+ const hash = hashStore[key];+ if (!hash) return 0;++ let deleted = 0;+ fields.forEach((field) => {+ if (field in hash) {+ delete hash[field];+ deleted += 1;+ }+ });+ return deleted;+ },pgIncrementBy: async () => {return 1;},diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex a017afe9fa..1dccf335fb 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -163,11 +163,8 @@ export const KeyStorePrefixes = {LicenseUsageReconcileMarker: (orgId: string) => `license-usage-reconcile-${orgId}` as const,LicenseUsageLastReported: (orgId: string, featureKey: string) =>`license-usage-last-reported-${orgId}-${featureKey}` as const,- IdentityLockoutState: (identityId: string, authMethod: string, slug: string) =>- `lockout:identity:${identityId}:${authMethod}:${slug}` as const,- IdentityLockoutStateByMethodPattern: (identityId: string, authMethod: string) =>- `lockout:identity:${identityId}:${authMethod}:*` as const,- IdentityLockoutStatePattern: (identityId: string) => `lockout:identity:${identityId}:*` as const,+ IdentityLockoutStateHash: (identityId: string) => `lockout:identity:${identityId}` as const,+ IdentityLockoutStateField: (authMethod: string, slug: string) => `${authMethod}:${slug}` as const,TelemetryAggregatedEventStream: (event: string, bucketId: string) =>`telemetry-agg-stream:${event}:${bucketId}` as const,@@ -306,6 +303,10 @@ export type TKeyStoreFactory = {// hash operationshashSet: (key: string, field: string, value: string) => Promise<number>;hashGet: (key: string, field: string) => Promise<string | null>;+ hashGetAll: (key: string) => Promise<Record<string, string>>;+ hashGetAllPrimary: (key: string) => Promise<Record<string, string>>;+ hashSetFieldWithMinExpiry: (key: string, field: string, value: string, expiryInSeconds: number) => Promise<void>;+ hashDeleteFields: (key: string, fields: string[]) => Promise<number>;// pgpgIncrementBy: (key: string, dto: { incr?: number; expiry?: string; tx?: Knex }) => Promise<number>;pgGetIntItem: (key: string, prefix?: string) => Promise<number | undefined>;@@ -532,6 +533,62 @@ export const keyStoreFactory = (const hashGet = async (key: string, field: string) => primaryRedis.hget(key, field);+ const hashGetAll = async (key: string) => pickPrimaryOrSecondaryRedis(primaryRedis, redisReadReplicas).hgetall(key);++ const hashGetAllPrimary = async (key: string) => primaryRedis.hgetall(key);++ // A hash carries one TTL for the whole key, so the expiry can only ever grow: shortening it would+ // drop sibling fields that are still live. Callers stamp each field with its own deadline instead.+ // HSET and EXPIRE go in one script so a crash between them cannot strand the hash without a TTL.+ //+ // Redis cannot expire an individual field, so a hash keyed by caller-supplied slugs would grow+ // until the whole key expires. Fields past their own deadline are reaped here, but only once the+ // hash is big enough to be worth walking, so the common one-or-two-field case pays nothing.+ const HASH_SET_FIELD_WITH_MIN_EXPIRY = `+ redis.call('HSET', KEYS[1], ARGV[1], ARGV[2])++ local current = redis.call('TTL', KEYS[1])+ local wanted = tonumber(ARGV[3])+ if current < 0 or current < wanted then+ redis.call('EXPIRE', KEYS[1], wanted)+ end++ if redis.call('HLEN', KEYS[1]) > tonumber(ARGV[5]) then+ local now = tonumber(ARGV[4])+ local entries = redis.call('HGETALL', KEYS[1])+ for i = 1, #entries, 2 do+ if entries[i] ~= ARGV[1] then+ local ok, parsed = pcall(cjson.decode, entries[i + 1])+ if ok and type(parsed) == 'table' and type(parsed.expiresAt) == 'number' and parsed.expiresAt <= now then+ redis.call('HDEL', KEYS[1], entries[i])+ end+ end+ end+ end++ return 1+ `;++ const HASH_FIELD_REAP_THRESHOLD = 50;++ const hashSetFieldWithMinExpiry = async (key: string, field: string, value: string, expiryInSeconds: number) => {+ await primaryRedis.eval(+ HASH_SET_FIELD_WITH_MIN_EXPIRY,+ 1,+ key,+ field,+ value,+ String(expiryInSeconds),+ String(Date.now()),+ String(HASH_FIELD_REAP_THRESHOLD)+ );+ };++ const hashDeleteFields = async (key: string, fields: string[]) => {+ if (!fields.length) return 0;+ return primaryRedis.hdel(key, ...fields);+ };+// List operationsconst listPush = async (key: string, value: string) => primaryRedis.rpush(key, value);@@ -658,6 +715,10 @@ export const keyStoreFactory = (pgIncrementBy,hashSet,hashGet,+ hashGetAll,+ hashGetAllPrimary,+ hashSetFieldWithMinExpiry,+ hashDeleteFields,listPush,listRange,listRemove,diff --git a/backend/src/keystore/memory.ts b/backend/src/keystore/memory.tsindex 6598c6b9dd..84268cd03d 100644--- a/backend/src/keystore/memory.ts+++ b/backend/src/keystore/memory.ts@@ -83,6 +83,29 @@ export const inMemoryKeyStore = (): TKeyStoreFactory => {hashGet: async (key, field) => {return hashStore[key]?.[field] ?? null;},+ hashGetAll: async (key) => {+ return { ...(hashStore[key] ?? {}) };+ },+ hashGetAllPrimary: async (key) => {+ return { ...(hashStore[key] ?? {}) };+ },+ hashSetFieldWithMinExpiry: async (key, field, value) => {+ if (!hashStore[key]) hashStore[key] = {};+ hashStore[key][field] = value;+ },+ hashDeleteFields: async (key, fields) => {+ const hash = hashStore[key];+ if (!hash) return 0;++ let deleted = 0;+ fields.forEach((field) => {+ if (field in hash) {+ delete hash[field];+ deleted += 1;+ }+ });+ return deleted;+ },pgIncrementBy: async () => {return 1;},diff --git a/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts b/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.tsindex 736c9f1f03..576f145730 100644--- a/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts+++ b/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts@@ -18,7 +18,7 @@ import {} from "@app/ee/services/permission/permission-fns";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import { ProjectPermissionIdentityActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";-import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";+import { TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import {BadRequestError,@@ -43,6 +43,13 @@ import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";import { ActorType } from "../auth/auth-type";import { TIdentityDALFactory } from "../identity/identity-dal";+import {+ clearIdentityLockoutsForAuthMethod,+ clearIdentityLockoutState,+ getIdentityLockoutState,+ identityLockoutLockKey,+ persistIdentityLockoutState+} from "../identity/identity-fns";import { TIdentityAccessTokenDALFactory } from "../identity-access-token/identity-access-token-dal";import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";import { TKmsServiceFactory } from "../kms/kms-service";@@ -77,12 +84,11 @@ type TIdentityLdapAuthServiceFactoryDep = {identityAuthTemplateDAL: TIdentityAuthTemplateDALFactory;keyStore: Pick<TKeyStoreFactory,- | "setItemWithExpiry"| "setItemWithExpiryNX"- | "getItem"- | "deleteItem"- | "getKeysByPattern"- | "deleteItems"+ | "hashGet"+ | "hashGetAllPrimary"+ | "hashSetFieldWithMinExpiry"+ | "hashDeleteFields"| "acquireLock">;orgDAL: Pick<TOrgDALFactory, "findById" | "findOne" | "findEffectiveOrgMembership">;@@ -94,11 +100,6 @@ type TIdentityLdapAuthServiceFactoryDep = {export type TIdentityLdapAuthServiceFactory = ReturnType<typeof identityLdapAuthServiceFactory>;-type LockoutObject = {- lockedOut: boolean;- failedAttempts: number;-};-export const identityLdapAuthServiceFactory = ({identityAccessTokenDAL,identityDAL,@@ -909,14 +910,9 @@ export const identityLdapAuthServiceFactory = ({);const orgId = identity?.orgId ?? null;- const lockoutKey = KeyStorePrefixes.IdentityLockoutState(identityId, IdentityAuthMethod.LDAP_AUTH, usernameSlug);+ const lockoutSelector = { identityId, authMethod: IdentityAuthMethod.LDAP_AUTH, slug: usernameSlug };- const lockoutRaw = await keyStore.getItem(lockoutKey);-- let lockout: LockoutObject | undefined;- if (lockoutRaw) {- lockout = JSON.parse(lockoutRaw) as LockoutObject;- }+ let lockout = await getIdentityLockoutState(lockoutSelector, keyStore);const identityLdapAuth = await identityLdapAuthDAL.findOne({ identityId });if (!identityLdapAuth) {@@ -938,7 +934,7 @@ export const identityLdapAuthServiceFactory = ({// If auth succeeds, clear any existing lockoutif (lockout) {- await keyStore.deleteItem(lockoutKey);+ await clearIdentityLockoutState(lockoutSelector, keyStore);}return result;@@ -948,22 +944,21 @@ export const identityLdapAuthServiceFactory = ({if (identityLdapAuth.lockoutEnabled) {let lock: Awaited<ReturnType<typeof keyStore.acquireLock>> | undefined;try {- lock = await keyStore.acquireLock([KeyStorePrefixes.IdentityLockoutLock(lockoutKey)], 500, {- retryCount: 10,- retryDelay: 300,- retryJitter: 100- });+ lock = await keyStore.acquireLock(+ [identityLockoutLockKey(identityId, IdentityAuthMethod.LDAP_AUTH, usernameSlug)],+ 500,+ {+ retryCount: 10,+ retryDelay: 300,+ retryJitter: 100+ }+ );// Re-fetch the latest lockout data while holding the lock- const lockoutRawNew = await keyStore.getItem(lockoutKey);- if (lockoutRawNew) {- lockout = JSON.parse(lockoutRawNew) as LockoutObject;- } else {- lockout = {- lockedOut: false,- failedAttempts: 0- };- }+ lockout = (await getIdentityLockoutState(lockoutSelector, keyStore)) ?? {+ lockedOut: false,+ failedAttempts: 0+ };if (lockout.lockedOut) {throw new UnauthorizedError({@@ -977,10 +972,15 @@ export const identityLdapAuthServiceFactory = ({lockout.lockedOut = true;}- await keyStore.setItemWithExpiry(- lockoutKey,- lockout.lockedOut ? identityLdapAuth.lockoutDurationSeconds : identityLdapAuth.lockoutCounterResetSeconds,- JSON.stringify(lockout)+ await persistIdentityLockoutState(+ {+ ...lockoutSelector,+ expiryInSeconds: lockout.lockedOut+ ? identityLdapAuth.lockoutDurationSeconds+ : identityLdapAuth.lockoutCounterResetSeconds+ },+ lockout,+ keyStore);} catch (e) {if (lock === undefined) {@@ -1058,9 +1058,7 @@ export const identityLdapAuthServiceFactory = ({ForbiddenError.from(permission).throwUnlessCan(OrgPermissionIdentityActions.Edit, OrgPermissionSubjects.Identity);}- const deleted = await keyStore.deleteItems({- pattern: KeyStorePrefixes.IdentityLockoutStateByMethodPattern(identityId, IdentityAuthMethod.LDAP_AUTH)- });+ const deleted = await clearIdentityLockoutsForAuthMethod(identityId, IdentityAuthMethod.LDAP_AUTH, keyStore);return { deleted, identityId, orgId: identityMembershipOrg.scopeOrgId };};diff --git a/backend/src/services/identity-ua/identity-ua-service.ts b/backend/src/services/identity-ua/identity-ua-service.tsindex 41cc2e505e..7d4f491848 100644--- a/backend/src/services/identity-ua/identity-ua-service.ts+++ b/backend/src/services/identity-ua/identity-ua-service.ts@@ -35,6 +35,13 @@ import {import { ActorType } from "../auth/auth-type";import { TIdentityDALFactory } from "../identity/identity-dal";+import {+ clearIdentityLockoutsForAuthMethod,+ clearIdentityLockoutState,+ getIdentityLockoutState,+ identityLockoutLockKey,+ persistIdentityLockoutState+} from "../identity/identity-fns";import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";import { TMembershipIdentityDALFactory } from "../membership-identity/membership-identity-dal";import { recordIdentityLastLogin, shouldRecordIdentityLastLogin } from "../membership-identity/membership-identity-fns";@@ -72,23 +79,17 @@ type TIdentityUaServiceFactoryDep = {>;keyStore: Pick<TKeyStoreFactory,- | "setItemWithExpiry"| "setItemWithExpiryNX"- | "getItem"- | "deleteItem"- | "getKeysByPattern"- | "deleteItems"+ | "hashGet"+ | "hashGetAllPrimary"+ | "hashSetFieldWithMinExpiry"+ | "hashDeleteFields"| "acquireLock">;};export type TIdentityUaServiceFactory = ReturnType<typeof identityUaServiceFactory>;-type LockoutObject = {- lockedOut: boolean;- failedAttempts: number;-};-// debounce per-secret usage writes so login bursts on one unlimited secret don't pile up on its row lockconst UA_CLIENT_SECRET_USAGE_DEBOUNCE_SECONDS = 10;@@ -131,18 +132,13 @@ export const identityUaServiceFactory = ({trustedIps: identityUa.clientSecretTrustedIps as TIp[]});- const lockoutKey = KeyStorePrefixes.IdentityLockoutState(- identityUa.identityId,- IdentityAuthMethod.UNIVERSAL_AUTH,- clientId- );-- const lockoutRaw = await keyStore.getItem(lockoutKey);+ const lockoutSelector = {+ identityId: identityUa.identityId,+ authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,+ slug: clientId+ };- let lockout: LockoutObject | undefined;- if (lockoutRaw) {- lockout = JSON.parse(lockoutRaw) as LockoutObject;- }+ let lockout = await getIdentityLockoutState(lockoutSelector, keyStore);if (lockout && lockout.lockedOut && identityUa.lockoutEnabled) {throw new UnauthorizedError({@@ -177,22 +173,21 @@ export const identityUaServiceFactory = ({if (identityUa.lockoutEnabled) {let lock: Awaited<ReturnType<typeof keyStore.acquireLock>> | undefined;try {- lock = await keyStore.acquireLock([KeyStorePrefixes.IdentityLockoutLock(lockoutKey)], 300, {- retryCount: 3,- retryDelay: 300,- retryJitter: 100- });+ lock = await keyStore.acquireLock(+ [identityLockoutLockKey(identityUa.identityId, IdentityAuthMethod.UNIVERSAL_AUTH, clientId)],+ 300,+ {+ retryCount: 3,+ retryDelay: 300,+ retryJitter: 100+ }+ );// Re-fetch the latest lockout data while holding the lock- const lockoutRawNew = await keyStore.getItem(lockoutKey);- if (lockoutRawNew) {- lockout = JSON.parse(lockoutRawNew) as LockoutObject;- } else {- lockout = {- lockedOut: false,- failedAttempts: 0- };- }+ lockout = (await getIdentityLockoutState(lockoutSelector, keyStore)) ?? {+ lockedOut: false,+ failedAttempts: 0+ };if (lockout.lockedOut) {throw new UnauthorizedError({@@ -211,10 +206,15 @@ export const identityUaServiceFactory = ({lockout.lockedOut = true;}- await keyStore.setItemWithExpiry(- lockoutKey,- lockout.lockedOut ? identityUa.lockoutDurationSeconds : identityUa.lockoutCounterResetSeconds,- JSON.stringify(lockout)+ await persistIdentityLockoutState(+ {+ ...lockoutSelector,+ expiryInSeconds: lockout.lockedOut+ ? identityUa.lockoutDurationSeconds+ : identityUa.lockoutCounterResetSeconds+ },+ lockout,+ keyStore);} catch (e) {if (lock === undefined) {@@ -242,7 +242,7 @@ export const identityUaServiceFactory = ({});} else if (lockout) {// If credentials are valid, clear any existing lockout record- await keyStore.deleteItem(lockoutKey);+ await clearIdentityLockoutState(lockoutSelector, keyStore);}const { clientSecretTTL, clientSecretNumUses, clientSecretNumUsesLimit } = validClientSecretInfo;@@ -1300,9 +1300,7 @@ export const identityUaServiceFactory = ({await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);- const deleted = await keyStore.deleteItems({- pattern: KeyStorePrefixes.IdentityLockoutStateByMethodPattern(identityId, IdentityAuthMethod.UNIVERSAL_AUTH)- });+ const deleted = await clearIdentityLockoutsForAuthMethod(identityId, IdentityAuthMethod.UNIVERSAL_AUTH, keyStore);return { deleted, identityId, orgId: identityMembershipOrg.scopeOrgId };};diff --git a/backend/src/services/identity-v2/identity-service.test.ts b/backend/src/services/identity-v2/identity-service.test.tsindex f3d4e0f4a7..f19e574890 100644--- a/backend/src/services/identity-v2/identity-service.test.ts+++ b/backend/src/services/identity-v2/identity-service.test.ts@@ -70,7 +70,7 @@ const createService = ({insertIdentityWideRevocationMarker: vi.fn().mockResolvedValue(undefined),bumpIdentityRevocationVersion: vi.fn().mockResolvedValue(undefined)} as never,- keyStore: { getKeysByPattern: vi.fn(), getItem: vi.fn() } as never,+ keyStore: { hashGetAll: vi.fn().mockResolvedValue({}) } as never,projectDAL: {findActorAccessibleProjectIds: vi.fn(),findOrgProjectIds: vi.fn(),diff --git a/backend/src/services/identity-v2/identity-service.ts b/backend/src/services/identity-v2/identity-service.tsindex b9d12051fb..0535110671 100644--- a/backend/src/services/identity-v2/identity-service.ts+++ b/backend/src/services/identity-v2/identity-service.ts@@ -74,7 +74,7 @@ type TScopedIdentityV2ServiceFactoryDep = {TIdentityAccessTokenServiceFactory,"insertIdentityWideRevocationMarker" | "bumpIdentityRevocationVersion">;- keyStore: Pick<TKeyStoreFactory, "getKeysByPattern" | "getItem">;+ keyStore: Pick<TKeyStoreFactory, "hashGetAll">;projectDAL: Pick<TProjectDALFactory, "findActorAccessibleProjectIds" | "findOrgProjectIds" | "findById">;orgDAL: Pick<TOrgDALFactory, "findById">;roleDAL: Pick<TRoleDALFactory, "find">;diff --git a/backend/src/services/identity/identity-fns.test.ts b/backend/src/services/identity/identity-fns.test.tsnew file mode 100644index 0000000000..ca3fea46f3--- /dev/null+++ b/backend/src/services/identity/identity-fns.test.ts@@ -0,0 +1,217 @@+import { IdentityAuthMethod } from "@app/db/schemas";+import { KeyStorePrefixes } from "@app/keystore/keystore";++import {+ clearIdentityLockoutsForAuthMethod,+ clearIdentityLockoutState,+ getIdentityActiveLockoutAuthMethods,+ getIdentityLockoutState,+ persistIdentityLockoutState+} from "./identity-fns";++const IDENTITY_ID = "6f7c1b6a-6e6f-4c0e-9f1a-2c2f5b8d9e01";+const HASH_KEY = KeyStorePrefixes.IdentityLockoutStateHash(IDENTITY_ID);++const lockedOut = (expiresAt?: number) => JSON.stringify({ lockedOut: true, failedAttempts: 5, expiresAt });+const notLockedOut = () => JSON.stringify({ lockedOut: false, failedAttempts: 1 });++const makeKeyStore = (hash: Record<string, string>) => ({+ hashGetAll: vi.fn().mockResolvedValue(hash),+ hashGetAllPrimary: vi.fn().mockResolvedValue(hash),+ hashGet: vi.fn().mockResolvedValue(null),+ hashDeleteFields: vi.fn().mockResolvedValue(0),+ hashSetFieldWithMinExpiry: vi.fn().mockResolvedValue(undefined),+ setItemWithExpiry: vi.fn().mockResolvedValue(undefined),+ deleteItem: vi.fn().mockResolvedValue(1),+ deleteItemsByKeyIn: vi.fn().mockResolvedValue(0),+ getKeysByPattern: vi.fn(),+ getItem: vi.fn()+});++describe("getIdentityActiveLockoutAuthMethods", () => {+ test("returns only the auth methods whose state is locked out", async () => {+ const keyStore = makeKeyStore({+ [`${IdentityAuthMethod.UNIVERSAL_AUTH}:client-a`]: lockedOut(),+ [`${IdentityAuthMethod.LDAP_AUTH}:alice`]: notLockedOut()+ });++ await expect(getIdentityActiveLockoutAuthMethods(IDENTITY_ID, keyStore)).resolves.toEqual([+ IdentityAuthMethod.UNIVERSAL_AUTH+ ]);+ expect(keyStore.hashGetAll).toHaveBeenCalledWith(HASH_KEY);+ });++ test("never scans the keyspace", async () => {+ const keyStore = makeKeyStore({ [`${IdentityAuthMethod.UNIVERSAL_AUTH}:client-a`]: lockedOut() });++ await getIdentityActiveLockoutAuthMethods(IDENTITY_ID, keyStore);++ expect(keyStore.getKeysByPattern).not.toHaveBeenCalled();+ expect(keyStore.getItem).not.toHaveBeenCalled();+ expect(keyStore.hashGetAll).toHaveBeenCalledTimes(1);+ });++ test("de-duplicates an auth method locked out under several slugs", async () => {+ const keyStore = makeKeyStore({+ [`${IdentityAuthMethod.LDAP_AUTH}:alice`]: lockedOut(),+ [`${IdentityAuthMethod.LDAP_AUTH}:bob`]: lockedOut()+ });++ await expect(getIdentityActiveLockoutAuthMethods(IDENTITY_ID, keyStore)).resolves.toEqual([+ IdentityAuthMethod.LDAP_AUTH+ ]);+ });++ test("returns an empty list for an empty hash and for a missing key", async () => {+ await expect(getIdentityActiveLockoutAuthMethods(IDENTITY_ID, makeKeyStore({}))).resolves.toEqual([]);++ const missing = { ...makeKeyStore({}), hashGetAll: vi.fn().mockResolvedValue(null) };+ await expect(getIdentityActiveLockoutAuthMethods(IDENTITY_ID, missing)).resolves.toEqual([]);+ });++ test("drops a field whose own deadline has passed", async () => {+ const keyStore = makeKeyStore({+ [`${IdentityAuthMethod.UNIVERSAL_AUTH}:client-a`]: lockedOut(Date.now() - 1_000),+ [`${IdentityAuthMethod.LDAP_AUTH}:alice`]: lockedOut(Date.now() + 60_000)+ });++ await expect(getIdentityActiveLockoutAuthMethods(IDENTITY_ID, keyStore)).resolves.toEqual([+ IdentityAuthMethod.LDAP_AUTH+ ]);+ });++ test("skips unparseable and malformed fields instead of throwing", async () => {+ const keyStore = makeKeyStore({+ "not-a-field": lockedOut(),+ [`${IdentityAuthMethod.UNIVERSAL_AUTH}:client-a`]: "{{{",+ [`${IdentityAuthMethod.LDAP_AUTH}:alice`]: lockedOut()+ });++ await expect(getIdentityActiveLockoutAuthMethods(IDENTITY_ID, keyStore)).resolves.toEqual([+ IdentityAuthMethod.LDAP_AUTH+ ]);+ });+});++describe("getIdentityLockoutState", () => {+ const selector = { identityId: IDENTITY_ID, authMethod: IdentityAuthMethod.UNIVERSAL_AUTH, slug: "client-a" };++ test("reads the one field it needs, never the whole hash or a string key", async () => {+ const keyStore = { ...makeKeyStore({}), hashGet: vi.fn().mockResolvedValue(lockedOut()) };++ await expect(getIdentityLockoutState(selector, keyStore)).resolves.toMatchObject({ lockedOut: true });+ expect(keyStore.hashGet).toHaveBeenCalledWith(HASH_KEY, `${IdentityAuthMethod.UNIVERSAL_AUTH}:client-a`);+ expect(keyStore.getItem).not.toHaveBeenCalled();+ expect(keyStore.hashGetAll).not.toHaveBeenCalled();+ });++ test("treats a field past its own deadline as absent", async () => {+ const keyStore = { ...makeKeyStore({}), hashGet: vi.fn().mockResolvedValue(lockedOut(Date.now() - 1_000)) };+ await expect(getIdentityLockoutState(selector, keyStore)).resolves.toBeUndefined();+ });++ test("keeps a field whose deadline is still ahead", async () => {+ const keyStore = { ...makeKeyStore({}), hashGet: vi.fn().mockResolvedValue(lockedOut(Date.now() + 60_000)) };+ await expect(getIdentityLockoutState(selector, keyStore)).resolves.toMatchObject({ lockedOut: true });+ });++ test("returns undefined for a missing or unreadable field", async () => {+ const missing = { ...makeKeyStore({}), hashGet: vi.fn().mockResolvedValue(null) };+ await expect(getIdentityLockoutState(selector, missing)).resolves.toBeUndefined();++ const corrupt = { ...makeKeyStore({}), hashGet: vi.fn().mockResolvedValue("{{{") };+ await expect(getIdentityLockoutState(selector, corrupt)).resolves.toBeUndefined();+ });+});++describe("persistIdentityLockoutState", () => {+ test("writes the hash field only, stamped with its own deadline", async () => {+ const keyStore = makeKeyStore({});++ await persistIdentityLockoutState(+ {+ identityId: IDENTITY_ID,+ authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,+ slug: "client-a",+ expiryInSeconds: 300+ },+ { lockedOut: true, failedAttempts: 3 },+ keyStore+ );++ const [hashKey, field, payload, hashTtl] = keyStore.hashSetFieldWithMinExpiry.mock.calls[0] as [+ string,+ string,+ string,+ number+ ];++ expect(hashKey).toBe(HASH_KEY);+ expect(field).toBe(`${IdentityAuthMethod.UNIVERSAL_AUTH}:client-a`);+ expect(hashTtl).toBe(300);+ expect(keyStore.setItemWithExpiry).not.toHaveBeenCalled();++ const parsed = JSON.parse(payload) as { lockedOut: boolean; failedAttempts: number; expiresAt: number };+ expect(parsed.lockedOut).toBe(true);+ expect(parsed.failedAttempts).toBe(3);+ expect(parsed.expiresAt).toBeGreaterThan(Date.now());+ });+});++describe("clearIdentityLockoutState", () => {+ test("removes the hash field and touches no string key", async () => {+ const keyStore = makeKeyStore({});++ await clearIdentityLockoutState(+ { identityId: IDENTITY_ID, authMethod: IdentityAuthMethod.LDAP_AUTH, slug: "alice" },+ keyStore+ );++ expect(keyStore.hashDeleteFields).toHaveBeenCalledWith(HASH_KEY, [`${IdentityAuthMethod.LDAP_AUTH}:alice`]);+ expect(keyStore.deleteItem).not.toHaveBeenCalled();+ });+});++describe("clearIdentityLockoutsForAuthMethod", () => {+ test("clears only the requested method's fields", async () => {+ const keyStore = makeKeyStore({+ [`${IdentityAuthMethod.UNIVERSAL_AUTH}:client-a`]: lockedOut(),+ [`${IdentityAuthMethod.LDAP_AUTH}:alice`]: lockedOut(),+ [`${IdentityAuthMethod.LDAP_AUTH}:bob`]: notLockedOut()+ });+ keyStore.hashDeleteFields.mockResolvedValue(2);++ await expect(clearIdentityLockoutsForAuthMethod(IDENTITY_ID, IdentityAuthMethod.LDAP_AUTH, keyStore)).resolves.toBe(+ 2+ );++ expect(keyStore.hashDeleteFields).toHaveBeenCalledWith(HASH_KEY, [+ `${IdentityAuthMethod.LDAP_AUTH}:alice`,+ `${IdentityAuthMethod.LDAP_AUTH}:bob`+ ]);+ expect(keyStore.getKeysByPattern).not.toHaveBeenCalled();+ expect(keyStore.deleteItemsByKeyIn).not.toHaveBeenCalled();+ });++ test("decides what to delete from the primary, never a read replica", async () => {+ // A replica read can lag behind a lockout the primary already holds, and the delete driven off+ // it would leave that lockout in place after the admin asked to clear it.+ const keyStore = makeKeyStore({ [`${IdentityAuthMethod.LDAP_AUTH}:alice`]: lockedOut() });++ await clearIdentityLockoutsForAuthMethod(IDENTITY_ID, IdentityAuthMethod.LDAP_AUTH, keyStore);++ expect(keyStore.hashGetAllPrimary).toHaveBeenCalledWith(HASH_KEY);+ expect(keyStore.hashGetAll).not.toHaveBeenCalled();+ });++ test("is a no-op when the identity has no lockouts for that method", async () => {+ const keyStore = makeKeyStore({ [`${IdentityAuthMethod.UNIVERSAL_AUTH}:client-a`]: lockedOut() });++ await expect(clearIdentityLockoutsForAuthMethod(IDENTITY_ID, IdentityAuthMethod.LDAP_AUTH, keyStore)).resolves.toBe(+ 0+ );++ expect(keyStore.deleteItemsByKeyIn).not.toHaveBeenCalled();+ expect(keyStore.hashDeleteFields).not.toHaveBeenCalled();+ });+});diff --git a/backend/src/services/identity/identity-fns.ts b/backend/src/services/identity/identity-fns.tsindex efa0e63f95..8460844703 100644--- a/backend/src/services/identity/identity-fns.ts+++ b/backend/src/services/identity/identity-fns.ts@@ -1,29 +1,113 @@import { IdentityAuthMethod } from "@app/db/schemas";import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";+export type TIdentityLockoutState = {+ lockedOut: boolean;+ failedAttempts: number;+ // Redis cannot expire an individual hash field. The key's TTL only garbage-collects the whole+ // hash once its longest-lived field is gone, so this deadline is what makes a read correct.+ expiresAt?: number;+};++const parseLockoutState = (raw: string): TIdentityLockoutState | null => {+ try {+ return JSON.parse(raw) as TIdentityLockoutState;+ } catch {+ // A single unreadable field must not fail the whole list page it was read for.+ return null;+ }+};++const isLive = (state: TIdentityLockoutState, now: number) => !state.expiresAt || state.expiresAt > now;++const lockoutHashKey = (identityId: string) => KeyStorePrefixes.IdentityLockoutStateHash(identityId);+const lockoutField = (authMethod: string, slug: string) => KeyStorePrefixes.IdentityLockoutStateField(authMethod, slug);++// Named after the hash key and field so the login paths serialise per lockout rather than per identity.+export const identityLockoutLockKey = (identityId: string, authMethod: string, slug: string) =>+ KeyStorePrefixes.IdentityLockoutLock(`${lockoutHashKey(identityId)}:${lockoutField(authMethod, slug)}`);++export const getIdentityLockoutState = async (+ { identityId, authMethod, slug }: { identityId: string; authMethod: string; slug: string },+ keyStore: Pick<TKeyStoreFactory, "hashGet">+): Promise<TIdentityLockoutState | undefined> => {+ const raw = await keyStore.hashGet(lockoutHashKey(identityId), lockoutField(authMethod, slug));+ if (!raw) return undefined;++ const state = parseLockoutState(raw);+ if (!state || !isLive(state, Date.now())) return undefined;++ return state;+};+export const getIdentityActiveLockoutAuthMethods = async (identityId: string,- keyStore: Pick<TKeyStoreFactory, "getKeysByPattern" | "getItem">+ keyStore: Pick<TKeyStoreFactory, "hashGetAll">) => {- const activeLockouts = await keyStore.getKeysByPattern(KeyStorePrefixes.IdentityLockoutStatePattern(identityId));+ const lockoutStates = await keyStore.hashGetAll(lockoutHashKey(identityId));+ const now = Date.now();const activeLockoutAuthMethods = new Set<string>();- for await (const key of activeLockouts) {- const parts = key.split(":");- if (parts.length > 3) {- const lockoutRaw = await keyStore.getItem(key);- if (lockoutRaw) {- const lockout = JSON.parse(lockoutRaw) as { lockedOut: boolean };- if (lockout.lockedOut) {- activeLockoutAuthMethods.add(parts[3]);- }- }- }- }++ Object.entries(lockoutStates ?? {}).forEach(([field, raw]) => {+ const separatorIndex = field.indexOf(":");+ if (separatorIndex <= 0) return;++ const state = parseLockoutState(raw);+ if (!state?.lockedOut || !isLive(state, now)) return;++ activeLockoutAuthMethods.add(field.slice(0, separatorIndex));+ });return Array.from(activeLockoutAuthMethods);};+// The key TTL never shortens, so it always outlives the longest-lived field; expiresAt is what+// retires this one.+export const persistIdentityLockoutState = async (+ {+ identityId,+ authMethod,+ slug,+ expiryInSeconds+ }: { identityId: string; authMethod: string; slug: string; expiryInSeconds: number },+ lockout: { lockedOut: boolean; failedAttempts: number },+ keyStore: Pick<TKeyStoreFactory, "hashSetFieldWithMinExpiry">+) => {+ await keyStore.hashSetFieldWithMinExpiry(+ lockoutHashKey(identityId),+ lockoutField(authMethod, slug),+ JSON.stringify({ ...lockout, expiresAt: Date.now() + expiryInSeconds * 1000 }),+ expiryInSeconds+ );+};++export const clearIdentityLockoutState = async (+ { identityId, authMethod, slug }: { identityId: string; authMethod: string; slug: string },+ keyStore: Pick<TKeyStoreFactory, "hashDeleteFields">+) => {+ await keyStore.hashDeleteFields(lockoutHashKey(identityId), [lockoutField(authMethod, slug)]);+};++// The field names carry the slugs, so the whole set for one method is addressable without the+// pattern delete (a full keyspace SCAN) this replaced.+export const clearIdentityLockoutsForAuthMethod = async (+ identityId: string,+ authMethod: string,+ keyStore: Pick<TKeyStoreFactory, "hashGetAllPrimary" | "hashDeleteFields">+) => {+ const hashKey = lockoutHashKey(identityId);+ const fieldPrefix = `${authMethod}:`;++ // Primary, not a replica: this read decides what gets deleted, and a lagging replica would hide+ // a lockout the admin just asked to clear.+ const lockoutStates = await keyStore.hashGetAllPrimary(hashKey);+ const fields = Object.keys(lockoutStates ?? {}).filter((field) => field.startsWith(fieldPrefix));+ if (!fields.length) return 0;++ return keyStore.hashDeleteFields(hashKey, fields);+};+export const buildAuthMethods = ({uaId,gcpId,diff --git a/backend/src/services/identity/identity-service.test.ts b/backend/src/services/identity/identity-service.test.tsindex ed01b3d864..f730db74da 100644--- a/backend/src/services/identity/identity-service.test.ts+++ b/backend/src/services/identity/identity-service.test.ts@@ -76,7 +76,7 @@ const createService = ({getOrgPermissionByRoles: vi.fn()} as never,licenseService: { getPlan: vi.fn(), getOrgSeatUsage: vi.fn(), updateSubscriptionOrgMemberCount: vi.fn() } as never,- keyStore: { getKeysByPattern: vi.fn(), getItem: vi.fn() } as never,+ keyStore: { hashGetAll: vi.fn().mockResolvedValue({}) } as never,orgDAL: { findById: vi.fn(), findEffectiveOrgMembership: vi.fn() } as never,additionalPrivilegeDAL: { delete: vi.fn().mockResolvedValue(undefined) } as never,usageMeteringService: { emit: vi.fn() } as never,diff --git a/backend/src/services/identity/identity-service.ts b/backend/src/services/identity/identity-service.tsindex 148a831933..79a06881ae 100644--- a/backend/src/services/identity/identity-service.ts+++ b/backend/src/services/identity/identity-service.ts@@ -49,7 +49,7 @@ type TIdentityServiceFactoryDep = {identityProjectDAL: Pick<TIdentityProjectDALFactory, "findByIdentityId">;permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getOrgPermissionByRoles">;licenseService: Pick<TLicenseServiceFactory, "getPlan" | "getOrgSeatUsage" | "updateSubscriptionOrgMemberCount">;- keyStore: Pick<TKeyStoreFactory, "getKeysByPattern" | "getItem">;+ keyStore: Pick<TKeyStoreFactory, "hashGetAll">;orgDAL: Pick<TOrgDALFactory, "findById" | "findEffectiveOrgMembership">;additionalPrivilegeDAL: Pick<TAdditionalPrivilegeDALFactory, "delete">;usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit">;diff --git a/backend/src/services/membership-identity/membership-identity-service.test.ts b/backend/src/services/membership-identity/membership-identity-service.test.tsindex b4bfc5640f..756e29b793 100644--- a/backend/src/services/membership-identity/membership-identity-service.test.ts+++ b/backend/src/services/membership-identity/membership-identity-service.test.ts@@ -81,7 +81,7 @@ const createService = ({licenseService: { getPlan: vi.fn() } as never,applicationMembershipCleanupService: { cleanupActorApplicationMemberships: vi.fn() } as never,projectDAL: { findById: vi.fn() } as never,- keyStore: { getKeysByPattern: vi.fn(), getItem: vi.fn() } as never,+ keyStore: { hashGetAll: vi.fn().mockResolvedValue({}) } as never,usageMeteringService: { emit: vi.fn(), emitForProject: vi.fn() } as never,alertService: { deleteAlertsForResource } as never,identityAccessTokenService: {diff --git a/backend/src/services/membership-identity/membership-identity-service.ts b/backend/src/services/membership-identity/membership-identity-service.tsindex aa93b82f78..3abe443132 100644--- a/backend/src/services/membership-identity/membership-identity-service.ts+++ b/backend/src/services/membership-identity/membership-identity-service.ts@@ -52,7 +52,7 @@ type TMembershipIdentityServiceFactoryDep = {"cleanupActorApplicationMemberships">;projectDAL: Pick<TProjectDALFactory, "findById">;- keyStore: Pick<TKeyStoreFactory, "getKeysByPattern" | "getItem">;+ keyStore: Pick<TKeyStoreFactory, "hashGetAll">;usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit" | "emitForProject">;alertService: Pick<TAlertServiceFactory, "deleteAlertsForResource">;identityAccessTokenService: Pick<