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: refactor identity lockout management to use indexed items and improve test coverage
Victor Hugo dos Santos7155baaf7c51
diff --git a/backend/e2e-test/identity-lockout-keystore.spec.ts b/backend/e2e-test/identity-lockout-keystore.spec.tsindex 3e0580a38e..88f48b49d9 100644--- a/backend/e2e-test/identity-lockout-keystore.spec.ts+++ b/backend/e2e-test/identity-lockout-keystore.spec.ts@@ -7,14 +7,15 @@ import { IdentityAuthMethod } from "@app/db/schemas";import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import {clearIdentityLockoutsForAuthMethod,+ clearIdentityLockoutState,getIdentityActiveLockoutAuthMethods,getIdentityLockoutState,persistIdentityLockoutState} from "@app/services/identity/identity-fns";-// These run against the real Redis the e2e environment boots, because the behaviour under test is-// server-side: the reap lives in a Lua script, and the regression this guards was a SCAN issued by-// ioredis. The in-memory keystore the unit tests use fakes both, so it cannot see either.+// Against the real Redis the e2e environment boots, because what is under test is server-side: the+// write is a Lua script, expiry is Redis's own, and the regression this guards was a SCAN issued by+// ioredis. The in-memory keystore the unit tests use fakes all three.declare const testRedis: Redis;declare const testKeyStore: TKeyStoreFactory;@@ -26,181 +27,146 @@ const commandCalls = async (command: string) => {return line ? Number(/^[^:]+:calls=(\d+),/.exec(line)?.[1] ?? 0) : 0;};-const lockoutFor = (id: string) => KeyStorePrefixes.IdentityLockoutStateHash(id);+const indexKey = (id: string) => KeyStorePrefixes.IdentityLockoutIndex(id);+const itemKey = (id: string, authMethod: string, slug: string) =>+ KeyStorePrefixes.IdentityLockoutState(id, authMethod, slug);-// Mirrors HASH_FIELD_REAP_THRESHOLD in the keystore: below this a hash is small enough that the-// reap skips it entirely, so a handful of expired fields legitimately survive until the key's TTL.-const REAP_THRESHOLD = 50;--// The reap keeps its resume position in a field of the same hash, so it is excluded here: only-// fields naming an auth method and slug are lockout state.-const lockoutFieldCount = async (id: string) =>- Object.keys(await testRedis.hgetall(lockoutFor(id))).filter((field) => field.includes(":")).length;+const lockout = (identityId: string, slug: string, expiryInSeconds: number, lockedOut: boolean) =>+ persistIdentityLockoutState(+ { identityId, authMethod: IdentityAuthMethod.LDAP_AUTH, slug, expiryInSeconds },+ { lockedOut, failedAttempts: lockedOut ? 3 : 1 },+ testKeyStore+ );let identityId: string;beforeEach(async () => {identityId = randomUUID();- await testRedis.del(lockoutFor(identityId));+ await testRedis.del(indexKey(identityId));});describe("identity lockout keystore", () => {- test("a lockout round-trips through the hash and is reported by auth method", async () => {- await persistIdentityLockoutState(- { identityId, authMethod: IdentityAuthMethod.UNIVERSAL_AUTH, slug: "client-a", expiryInSeconds: 300 },- { lockedOut: true, failedAttempts: 3 },- testKeyStore- );+ test("a lockout round-trips, and both the item and the index expire on their own", async () => {+ await lockout(identityId, "alice", 300, true);++ await expect(+ getIdentityLockoutState({ identityId, authMethod: IdentityAuthMethod.LDAP_AUTH, slug: "alice" }, testKeyStore)+ ).resolves.toEqual({ lockedOut: true, failedAttempts: 3 });await expect(getIdentityActiveLockoutAuthMethods(identityId, testKeyStore)).resolves.toEqual([- IdentityAuthMethod.UNIVERSAL_AUTH+ IdentityAuthMethod.LDAP_AUTH]);- // The key must expire on its own; a lockout hash that outlives its lockout is a leak.- const ttl = await testRedis.ttl(lockoutFor(identityId));- expect(ttl).toBeGreaterThan(0);- expect(ttl).toBeLessThanOrEqual(300);+ // Neither may outlive its lockout: a key with no TTL is a leak nothing reclaims.+ const itemTtl = await testRedis.ttl(itemKey(identityId, IdentityAuthMethod.LDAP_AUTH, "alice"));+ const idxTtl = await testRedis.ttl(indexKey(identityId));+ expect(itemTtl).toBeGreaterThan(0);+ expect(itemTtl).toBeLessThanOrEqual(300);+ expect(idxTtl).toBeGreaterThan(0);});- test("the key TTL only ever grows, so a short write cannot cut a long lockout short", async () => {- await persistIdentityLockoutState(- { identityId, authMethod: IdentityAuthMethod.UNIVERSAL_AUTH, slug: "client-a", expiryInSeconds: 3600 },- { lockedOut: true, failedAttempts: 9 },- testKeyStore- );- await persistIdentityLockoutState(- { identityId, authMethod: IdentityAuthMethod.LDAP_AUTH, slug: "alice", expiryInSeconds: 30 },- { lockedOut: false, failedAttempts: 1 },- testKeyStore- );+ test("the index expiry only ever grows, so a short write cannot cut a long lockout short", async () => {+ await lockout(identityId, "long", 3600, true);+ await lockout(identityId, "short", 30, true);- expect(await testRedis.ttl(lockoutFor(identityId))).toBeGreaterThan(300);+ expect(await testRedis.ttl(indexKey(identityId))).toBeGreaterThan(300);});- test("a field past its own deadline is ignored even while the key is still alive", async () => {- // Redis cannot expire one field, so a long-lived sibling keeps an expired one resident. Reads- // have to honour expiresAt or a lockout outlives its duration.- await persistIdentityLockoutState(- { identityId, authMethod: IdentityAuthMethod.UNIVERSAL_AUTH, slug: "client-a", expiryInSeconds: 3600 },- { lockedOut: false, failedAttempts: 1 },- testKeyStore- );- await testRedis.hset(- lockoutFor(identityId),- KeyStorePrefixes.IdentityLockoutStateField(IdentityAuthMethod.LDAP_AUTH, "alice"),- JSON.stringify({ lockedOut: true, failedAttempts: 9, expiresAt: Date.now() - 1_000 })- );+ test("a failure counter is never indexed, so spraying slugs cannot enlarge the list read", async () => {+ // LDAP slugs are caller-supplied usernames. Counters are addressed directly by login and are of+ // no use to the list endpoints, so keeping them out of the index is what bounds that read.+ for (let i = 0; i < 500; i += 1) {+ // eslint-disable-next-line no-await-in-loop+ await lockout(identityId, `sprayed-${i}`, 60, false);+ }+ expect(await testRedis.zcard(indexKey(identityId))).toBe(0);await expect(getIdentityActiveLockoutAuthMethods(identityId, testKeyStore)).resolves.toEqual([]);++ // The counters themselves are still readable by the login path that knows their slug.await expect(- getIdentityLockoutState({ identityId, authMethod: IdentityAuthMethod.LDAP_AUTH, slug: "alice" }, testKeyStore)- ).resolves.toBeUndefined();- });+ getIdentityLockoutState({ identityId, authMethod: IdentityAuthMethod.LDAP_AUTH, slug: "sprayed-1" }, testKeyStore)+ ).resolves.toEqual({ lockedOut: false, failedAttempts: 1 });- test("expired fields are reaped on write, so the resident set tracks the counter window", async () => {- // Without the reap a field survives until the key TTL, which one 24h lockout can pin, rather- // than until its own deadline.- const expired = JSON.stringify({ lockedOut: true, failedAttempts: 1, expiresAt: Date.now() - 1_000 });- const sprayed: Record<string, string> = {};- for (let i = 0; i < 60; i += 1) {- sprayed[KeyStorePrefixes.IdentityLockoutStateField(IdentityAuthMethod.LDAP_AUTH, `sprayed-${i}`)] = expired;- }- await testRedis.hset(lockoutFor(identityId), sprayed);- expect(await lockoutFieldCount(identityId)).toBe(60);+ // ...and one real lockout among them is still found, without the spray inflating the index.+ await lockout(identityId, "victim", 300, true);+ expect(await testRedis.zcard(indexKey(identityId))).toBe(1);+ await expect(getIdentityActiveLockoutAuthMethods(identityId, testKeyStore)).resolves.toEqual([+ IdentityAuthMethod.LDAP_AUTH+ ]);+ });- await persistIdentityLockoutState(- { identityId, authMethod: IdentityAuthMethod.UNIVERSAL_AUTH, slug: "client-a", expiryInSeconds: 300 },- { lockedOut: false, failedAttempts: 1 },- testKeyStore- );+ test("a member that outlives its item is not reported, before anything prunes it", async () => {+ // Redis expires the item on its own but cannot expire an index member, so the index is briefly+ // stale. Reads range by score, which is why that staleness is never visible.+ await lockout(identityId, "alice", 300, true);+ await testRedis.del(itemKey(identityId, IdentityAuthMethod.LDAP_AUTH, "alice"));+ await testRedis.zadd(indexKey(identityId), Date.now() - 1_000, `${IdentityAuthMethod.LDAP_AUTH}:alice`);- expect(await lockoutFieldCount(identityId)).toBe(1);+ expect(await testRedis.zcard(indexKey(identityId))).toBe(1);await expect(getIdentityActiveLockoutAuthMethods(identityId, testKeyStore)).resolves.toEqual([]);});- test("the reap leaves live fields and fields carrying no deadline alone", async () => {- const now = Date.now();- const fields: Record<string, string> = {- [KeyStorePrefixes.IdentityLockoutStateField(IdentityAuthMethod.LDAP_AUTH, "live")]: JSON.stringify({- lockedOut: true,- failedAttempts: 9,- expiresAt: now + 600_000- }),- [KeyStorePrefixes.IdentityLockoutStateField(IdentityAuthMethod.TOKEN_AUTH, "no-deadline")]: JSON.stringify({- lockedOut: true,- failedAttempts: 9- }),- [KeyStorePrefixes.IdentityLockoutStateField(IdentityAuthMethod.AWS_AUTH, "unreadable")]: "{{{"- };- for (let i = 0; i < 60; i += 1) {- fields[KeyStorePrefixes.IdentityLockoutStateField(IdentityAuthMethod.LDAP_AUTH, `dead-${i}`)] = JSON.stringify({- lockedOut: true,- failedAttempts: 1,- expiresAt: now - 1_000- });- }- await testRedis.hset(lockoutFor(identityId), fields);+ test("expired members are pruned on write, in one command and with nothing left behind", async () => {+ const stale = Array.from({ length: 400 }, (_, i) => [+ Date.now() - 1_000,+ `${IdentityAuthMethod.LDAP_AUTH}:old-${i}`+ ]);+ await testRedis.zadd(indexKey(identityId), ...stale.flat());+ expect(await testRedis.zcard(indexKey(identityId))).toBe(400);- await persistIdentityLockoutState(- { identityId, authMethod: IdentityAuthMethod.UNIVERSAL_AUTH, slug: "client-a", expiryInSeconds: 300 },- { lockedOut: false, failedAttempts: 1 },- testKeyStore- );+ // A single write, not a batch that has to be repeated: the index is ordered by deadline, so one+ // range removal takes every expired member regardless of how many there are.+ await lockout(identityId, "alice", 300, true);- expect(await lockoutFieldCount(identityId)).toBe(4);- await expect(getIdentityActiveLockoutAuthMethods(identityId, testKeyStore)).resolves.toEqual(- expect.arrayContaining([IdentityAuthMethod.LDAP_AUTH, IdentityAuthMethod.TOKEN_AUTH])- );+ expect(await testRedis.zcard(indexKey(identityId))).toBe(1);+ await expect(getIdentityActiveLockoutAuthMethods(identityId, testKeyStore)).resolves.toEqual([+ IdentityAuthMethod.LDAP_AUTH+ ]);});- test.each([- // Below hash-max-listpack-entries (512 by default) HSCAN ignores cursor and COUNT and returns- // the whole hash; above it, real cursor semantics apply. The reap has to make progress in both.- { label: "listpack-encoded", fields: 400 },- { label: "hashtable-encoded", fields: 1200 }- ])("the reap eventually covers the whole $label hash instead of one fixed segment", async ({ fields }) => {- const expired = JSON.stringify({ lockedOut: false, failedAttempts: 1, expiresAt: Date.now() - 1_000 });- const sprayed: Record<string, string> = {};- for (let i = 0; i < fields; i += 1) {- sprayed[KeyStorePrefixes.IdentityLockoutStateField(IdentityAuthMethod.LDAP_AUTH, `sprayed-${i}`)] = expired;- }- await testRedis.hset(lockoutFor(identityId), sprayed);-- const write = async () =>- persistIdentityLockoutState(- { identityId, authMethod: IdentityAuthMethod.UNIVERSAL_AUTH, slug: "client-a", expiryInSeconds: 300 },- { lockedOut: false, failedAttempts: 1 },- testKeyStore- );+ test("clearing one slug removes the item and its index member together", async () => {+ await lockout(identityId, "alice", 300, true);+ await lockout(identityId, "bob", 300, true);- // Counts lockout fields only: the reap keeps its resume position in a field of the same hash.- const lockoutFields = async () => lockoutFieldCount(identityId);+ await clearIdentityLockoutState(+ { identityId, authMethod: IdentityAuthMethod.LDAP_AUTH, slug: "alice" },+ testKeyStore+ );- await write();- const afterOne = await lockoutFields();+ expect(await testRedis.exists(itemKey(identityId, IdentityAuthMethod.LDAP_AUTH, "alice"))).toBe(0);+ expect(await testRedis.zscore(indexKey(identityId), `${IdentityAuthMethod.LDAP_AUTH}:alice`)).toBeNull();+ expect(await testRedis.zscore(indexKey(identityId), `${IdentityAuthMethod.LDAP_AUTH}:bob`)).not.toBeNull();+ });- // Bounded: one write must not have walked the whole hash, or the cost is caller-controlled.- expect(afterOne).toBeGreaterThan(1);+ test("clearing a method removes every locked slug for it, and leaves other methods alone", async () => {+ await lockout(identityId, "alice", 300, true);+ await lockout(identityId, "bob", 300, true);+ await persistIdentityLockoutState(+ {+ identityId,+ authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,+ slug: "client-a",+ expiryInSeconds: 300+ },+ { lockedOut: true, failedAttempts: 3 },+ testKeyStore+ );- // ...and it must not stall. Scanning from a fixed start drains one segment and then returns the- // same live fields forever, leaving everything else resident until the key's TTL.- let remaining = afterOne;- for (let i = 0; i < 200 && remaining > REAP_THRESHOLD; i += 1) {- // eslint-disable-next-line no-await-in-loop- await write();- // eslint-disable-next-line no-await-in-loop- remaining = await lockoutFields();- }+ await expect(+ clearIdentityLockoutsForAuthMethod(identityId, IdentityAuthMethod.LDAP_AUTH, testKeyStore)+ ).resolves.toBe(2);- // Down to within the threshold below which the reap deliberately stops walking. What matters is- // that the plateau is that constant and not whatever size the caller managed to grow the hash- // to -- a fixed scan start plateaus at the latter.- expect(remaining).toBeLessThanOrEqual(REAP_THRESHOLD);+ expect(await testRedis.exists(itemKey(identityId, IdentityAuthMethod.LDAP_AUTH, "alice"))).toBe(0);+ expect(await testRedis.exists(itemKey(identityId, IdentityAuthMethod.LDAP_AUTH, "bob"))).toBe(0);+ await expect(getIdentityActiveLockoutAuthMethods(identityId, testKeyStore)).resolves.toEqual([+ IdentityAuthMethod.UNIVERSAL_AUTH+ ]);});test("no lockout path issues a SCAN, whatever the keyspace holds", async () => {- // The incident: one SCAN MATCH walk of the whole keyspace per identity on every list row.- // MATCH is a post-filter, so the cost tracked the keyspace, not the number of lockouts.+ // The incident: one SCAN MATCH walk of the whole keyspace per identity on every list row. MATCH+ // is a post-filter, so the cost tracked the keyspace, not the number of lockouts.const decoys: string[] = [];const pipeline = testRedis.pipeline();for (let i = 0; i < 2_000; i += 1) {@@ -210,33 +176,27 @@ describe("identity lockout keystore", () => {}await pipeline.exec();- await persistIdentityLockoutState(- { identityId, authMethod: IdentityAuthMethod.UNIVERSAL_AUTH, slug: "client-a", expiryInSeconds: 300 },- { lockedOut: true, failedAttempts: 3 },- testKeyStore- );+ await lockout(identityId, "alice", 300, true);const scanBefore = await commandCalls("scan");- const hgetallBefore = await commandCalls("hgetall");+ const rangeBefore = await commandCalls("zrangebyscore");- // Every read shape the list, detail and admin paths use.const LIST_READS = 10;for (let i = 0; i < LIST_READS; i += 1) {// eslint-disable-next-line no-await-in-loopawait getIdentityActiveLockoutAuthMethods(identityId, testKeyStore);}await getIdentityLockoutState(- { identityId, authMethod: IdentityAuthMethod.UNIVERSAL_AUTH, slug: "client-a" },+ { identityId, authMethod: IdentityAuthMethod.LDAP_AUTH, slug: "alice" },testKeyStore);- await clearIdentityLockoutsForAuthMethod(identityId, IdentityAuthMethod.UNIVERSAL_AUTH, testKeyStore);+ await clearIdentityLockoutsForAuthMethod(identityId, IdentityAuthMethod.LDAP_AUTH, testKeyStore);- // Proves the counter is actually being read before the SCAN assertion leans on it: a broken- // parser reports zero for every command, which would make that assertion pass having measured- // nothing. It also pins the cost itself -- one keyed read per list row, plus the clear path's.- expect(await commandCalls("hgetall")).toBe(hgetallBefore + LIST_READS + 1);+ // Proves the counter is being read at all before the SCAN assertion leans on it: a broken parser+ // reports zero for every command, which would make that assertion pass having measured nothing.+ // It also pins the cost -- one keyed range read per list row, and no more.+ expect(await commandCalls("zrangebyscore")).toBe(rangeBefore + LIST_READS);expect(await commandCalls("scan")).toBe(scanBefore);- await expect(getIdentityActiveLockoutAuthMethods(identityId, testKeyStore)).resolves.toEqual([]);await testRedis.del(...decoys);});diff --git a/backend/e2e-test/mocks/keystore.ts b/backend/e2e-test/mocks/keystore.tsindex 5cd33a122f..baeab13b6e 100644--- a/backend/e2e-test/mocks/keystore.ts+++ b/backend/e2e-test/mocks/keystore.ts@@ -8,6 +8,7 @@ import { Lock } from "@app/lib/red-lock";export const mockKeyStore = (): TKeyStoreFactory => {const store: Record<string, string | number | Buffer> = {};const hashStore: Record<string, Record<string, string>> = {};+ const sortedSetStore: Record<string, Record<string, number>> = {};const getRegex = (pattern: string) =>new RE2(`^${pattern.replace(/[-[\]/{}()+?.\\^$|]/g, "\\$&").replace(/\*/g, ".*")}$`);@@ -117,22 +118,31 @@ export const mockKeyStore = (): TKeyStoreFactory => {hashGetAllPrimary: async (key) => {return { ...(hashStore[key] ?? {}) };},- hashSetFieldWithMinExpiry: async (key, field, value) => {- if (!hashStore[key]) hashStore[key] = {};- hashStore[key][field] = value;+ setIndexedItemWithExpiry: async ({ indexKey, member, itemKey, value, expiryInSeconds, indexed }) => {+ store[itemKey] = value;+ if (!sortedSetStore[indexKey]) sortedSetStore[indexKey] = {};+ if (indexed) {+ sortedSetStore[indexKey][member] = Date.now() + expiryInSeconds * 1000;+ } else {+ delete sortedSetStore[indexKey][member];+ }},- 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;+ deleteIndexedItems: async ({ indexKey, members, itemKeys }) => {+ itemKeys.forEach((key) => delete store[key]);+ members.forEach((member) => delete sortedSetStore[indexKey]?.[member]);+ },+ sortedSetRangeByScore: async (key, min, max) => {+ const lower = min === "-inf" ? -Infinity : Number(min);+ const upper = max === "+inf" ? Infinity : Number(max);+ return Object.entries(sortedSetStore[key] ?? {})+ .filter(([, score]) => score >= lower && score <= upper)+ .sort(([, a], [, b]) => a - b)+ .map(([member]) => member);+ },+ sortedSetMembersPrimary: async (key) => {+ return Object.entries(sortedSetStore[key] ?? {})+ .sort(([, a], [, b]) => a - b)+ .map(([member]) => member);},pgIncrementBy: async () => {return 1;diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex 1d9a2b1009..c03838b304 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -163,8 +163,11 @@ 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,- IdentityLockoutStateHash: (identityId: string) => `lockout:identity:${identityId}` as const,- IdentityLockoutStateField: (authMethod: string, slug: string) => `${authMethod}:${slug}` as const,+ IdentityLockoutState: (identityId: string, authMethod: string, slug: string) =>+ `lockout:identity:${identityId}:${authMethod}:${slug}` as const,+ // Sorted set of the identity's *locked* auth methods, scored by when each lockout ends.+ IdentityLockoutIndex: (identityId: string) => `lockout:identity:${identityId}` as const,+ IdentityLockoutMember: (authMethod: string, slug: string) => `${authMethod}:${slug}` as const,TelemetryAggregatedEventStream: (event: string, bucketId: string) =>`telemetry-agg-stream:${event}:${bucketId}` as const,@@ -305,8 +308,19 @@ export type TKeyStoreFactory = {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>;+ // sorted-set indexed items: item key gets native TTL; optional index member is scored by the same+ // deadline and pruned on write.+ setIndexedItemWithExpiry: (arg: {+ indexKey: string;+ member: string;+ itemKey: string;+ value: string;+ expiryInSeconds: number;+ indexed: boolean;+ }) => Promise<void>;+ deleteIndexedItems: (arg: { indexKey: string; members: string[]; itemKeys: string[] }) => Promise<void>;+ sortedSetRangeByScore: (key: string, min: string | number, max: string | number) => Promise<string[]>;+ sortedSetMembersPrimary: (key: string) => Promise<string[]>;// pgpgIncrementBy: (key: string, dto: { incr?: number; expiry?: string; tx?: Knex }) => Promise<number>;pgGetIntItem: (key: string, prefix?: string) => Promise<number | undefined>;@@ -537,101 +551,79 @@ export const keyStoreFactory = (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.- //- // The reap walks one bounded HSCAN slice, never the whole hash.- 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)+ // KEYS[1] indexKey (ZSET), KEYS[2] itemKey (payload string).+ // ARGV[1] member, ARGV[2] value, ARGV[3] expiryInSeconds, ARGV[4] expiresAt score (ms),+ // ARGV[5] indexed ('1' | '0'), ARGV[6] now (ms, stale-index prune cutoff).+ const INDEXED_ITEM_UPSERT = `+ redis.call('SET', KEYS[2], ARGV[2], 'EX', ARGV[3])++ if ARGV[5] == '1' then+ redis.call('ZADD', KEYS[1], ARGV[4], ARGV[1])+ else+ redis.call('ZREM', KEYS[1], ARGV[1])end- if redis.call('HLEN', KEYS[1]) > tonumber(ARGV[5]) then- local now = tonumber(ARGV[4])- local batch = tonumber(ARGV[6])- -- Resume where the last reap stopped. A fixed start rescans one segment forever: it drains- -- that segment and then returns the same live fields on every write, leaving everything- -- outside it resident until the key's TTL. The cursor lives in the hash it describes so it- -- shares that TTL and needs no separate key; it carries no ':' so every reader of these- -- fields already skips it.- local cursorField = '__reap_cursor'- local position = tonumber(redis.call('HGET', KEYS[1], cursorField) or '0') or 0-- local scanned = redis.call('HSCAN', KEYS[1], position, 'COUNT', batch)- local entries = scanned[2]- local total = #entries / 2-- if total > 0 then- local take = math.min(total, batch)- local offset = 0- local nextPosition = tonumber(scanned[1])-- local listpack = total > batch- if listpack then- -- A listpack-encoded hash ignores both the cursor and COUNT and returns every field, so- -- HSCAN cannot advance on its own and the window has to be tracked by hand.- offset = position % total- end-- local kept = 0- for n = 0, take - 1 do- local i = math.floor((offset + n) % total) * 2 + 1- local name = entries[i]- local reaped = false-- if name ~= ARGV[1] and name ~= cursorField 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], name)- reaped = true- end- end-- if not reaped then kept = kept + 1 end- end-- if listpack then- nextPosition = position + kept- end-- redis.call('HSET', KEYS[1], cursorField, nextPosition)+ redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', ARGV[6])++ if redis.call('ZCARD', KEYS[1]) == 0 then+ redis.call('DEL', KEYS[1])+ else+ 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)endendreturn 1`;- const HASH_FIELD_REAP_THRESHOLD = 50;- const HASH_FIELD_REAP_BATCH = 64;-- const hashSetFieldWithMinExpiry = async (key: string, field: string, value: string, expiryInSeconds: number) => {+ const setIndexedItemWithExpiry: TKeyStoreFactory["setIndexedItemWithExpiry"] = async ({+ indexKey,+ member,+ itemKey,+ value,+ expiryInSeconds,+ indexed+ }) => {+ const now = Date.now();await primaryRedis.eval(- HASH_SET_FIELD_WITH_MIN_EXPIRY,- 1,- key,- field,+ INDEXED_ITEM_UPSERT,+ 2,+ indexKey,+ itemKey,+ member,value,String(expiryInSeconds),- String(Date.now()),- String(HASH_FIELD_REAP_THRESHOLD),- String(HASH_FIELD_REAP_BATCH)+ String(now + expiryInSeconds * 1000),+ indexed ? "1" : "0",+ String(now));};- const hashDeleteFields = async (key: string, fields: string[]) => {- if (!fields.length) return 0;- return primaryRedis.hdel(key, ...fields);+ const DELETE_INDEXED_ITEMS = `+ for i = 1, #ARGV do+ redis.call('ZREM', KEYS[1], ARGV[i])+ end+ for i = 2, #KEYS do+ redis.call('DEL', KEYS[i])+ end+ if redis.call('ZCARD', KEYS[1]) == 0 then+ redis.call('DEL', KEYS[1])+ end+ return 1+ `;++ const deleteIndexedItems: TKeyStoreFactory["deleteIndexedItems"] = async ({ indexKey, members, itemKeys }) => {+ if (!members.length && !itemKeys.length) return;+ await primaryRedis.eval(DELETE_INDEXED_ITEMS, itemKeys.length + 1, indexKey, ...itemKeys, ...members);};+ const sortedSetRangeByScore = async (key: string, min: string | number, max: string | number) =>+ pickPrimaryOrSecondaryRedis(primaryRedis, redisReadReplicas).zrangebyscore(key, min, max);++ const sortedSetMembersPrimary = async (key: string) => primaryRedis.zrange(key, 0, -1);+// List operationsconst listPush = async (key: string, value: string) => primaryRedis.rpush(key, value);@@ -760,8 +752,10 @@ export const keyStoreFactory = (hashGet,hashGetAll,hashGetAllPrimary,- hashSetFieldWithMinExpiry,- hashDeleteFields,+ setIndexedItemWithExpiry,+ deleteIndexedItems,+ sortedSetRangeByScore,+ sortedSetMembersPrimary,listPush,listRange,listRemove,diff --git a/backend/src/keystore/memory.ts b/backend/src/keystore/memory.tsindex 84268cd03d..a45a2ff8b3 100644--- a/backend/src/keystore/memory.ts+++ b/backend/src/keystore/memory.ts@@ -10,6 +10,7 @@ export const inMemoryKeyStore = (): TKeyStoreFactory => {const store: Record<string, string | number | Buffer> = {};const listStore: Record<string, string[]> = {};const hashStore: Record<string, Record<string, string>> = {};+ const sortedSetStore: Record<string, Record<string, number>> = {};const getRegex = (pattern: string) =>new RE2(`^${pattern.replace(/[-[\]/{}()+?.\\^$|]/g, "\\$&").replace(/\*/g, ".*")}$`);@@ -89,22 +90,31 @@ export const inMemoryKeyStore = (): TKeyStoreFactory => {hashGetAllPrimary: async (key) => {return { ...(hashStore[key] ?? {}) };},- hashSetFieldWithMinExpiry: async (key, field, value) => {- if (!hashStore[key]) hashStore[key] = {};- hashStore[key][field] = value;+ setIndexedItemWithExpiry: async ({ indexKey, member, itemKey, value, expiryInSeconds, indexed }) => {+ store[itemKey] = value;+ if (!sortedSetStore[indexKey]) sortedSetStore[indexKey] = {};+ if (indexed) {+ sortedSetStore[indexKey][member] = Date.now() + expiryInSeconds * 1000;+ } else {+ delete sortedSetStore[indexKey][member];+ }},- 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;+ deleteIndexedItems: async ({ indexKey, members, itemKeys }) => {+ itemKeys.forEach((key) => delete store[key]);+ members.forEach((member) => delete sortedSetStore[indexKey]?.[member]);+ },+ sortedSetRangeByScore: async (key, min, max) => {+ const lower = min === "-inf" ? -Infinity : Number(min);+ const upper = max === "+inf" ? Infinity : Number(max);+ return Object.entries(sortedSetStore[key] ?? {})+ .filter(([, score]) => score >= lower && score <= upper)+ .sort(([, a], [, b]) => a - b)+ .map(([member]) => member);+ },+ sortedSetMembersPrimary: async (key) => {+ return Object.entries(sortedSetStore[key] ?? {})+ .sort(([, a], [, b]) => a - b)+ .map(([member]) => member);},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 576f145730..35fb1c8a0d 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@@ -85,10 +85,10 @@ type TIdentityLdapAuthServiceFactoryDep = {keyStore: Pick<TKeyStoreFactory,| "setItemWithExpiryNX"- | "hashGet"- | "hashGetAllPrimary"- | "hashSetFieldWithMinExpiry"- | "hashDeleteFields"+ | "getItem"+ | "setIndexedItemWithExpiry"+ | "deleteIndexedItems"+ | "sortedSetMembersPrimary"| "acquireLock">;orgDAL: Pick<TOrgDALFactory, "findById" | "findOne" | "findEffectiveOrgMembership">;diff --git a/backend/src/services/identity-ua/identity-ua-service.ts b/backend/src/services/identity-ua/identity-ua-service.tsindex 7d4f491848..2fbf998191 100644--- a/backend/src/services/identity-ua/identity-ua-service.ts+++ b/backend/src/services/identity-ua/identity-ua-service.ts@@ -80,10 +80,10 @@ type TIdentityUaServiceFactoryDep = {keyStore: Pick<TKeyStoreFactory,| "setItemWithExpiryNX"- | "hashGet"- | "hashGetAllPrimary"- | "hashSetFieldWithMinExpiry"- | "hashDeleteFields"+ | "getItem"+ | "setIndexedItemWithExpiry"+ | "deleteIndexedItems"+ | "sortedSetMembersPrimary"| "acquireLock">;};diff --git a/backend/src/services/identity-v2/identity-service.test.ts b/backend/src/services/identity-v2/identity-service.test.tsindex f19e574890..b47cb52d22 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: { hashGetAll: vi.fn().mockResolvedValue({}) } as never,+ keyStore: { sortedSetRangeByScore: 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 0535110671..e163ab433b 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, "hashGetAll">;+ keyStore: Pick<TKeyStoreFactory, "sortedSetRangeByScore">;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.tsindex ca3fea46f3..ab8c783d8c 100644--- a/backend/src/services/identity/identity-fns.test.ts+++ b/backend/src/services/identity/identity-fns.test.ts@@ -10,123 +10,107 @@ import {} 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),+const INDEX_KEY = KeyStorePrefixes.IdentityLockoutIndex(IDENTITY_ID);+const itemKey = (authMethod: string, slug: string) =>+ KeyStorePrefixes.IdentityLockoutState(IDENTITY_ID, authMethod, slug);++const makeKeyStore = () => ({+ getItem: vi.fn().mockResolvedValue(null),+ setIndexedItemWithExpiry: vi.fn().mockResolvedValue(undefined),+ deleteIndexedItems: vi.fn().mockResolvedValue(undefined),+ sortedSetRangeByScore: vi.fn().mockResolvedValue([]),+ sortedSetMembersPrimary: vi.fn().mockResolvedValue([]),getKeysByPattern: vi.fn(),- getItem: vi.fn()+ deleteItems: 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() });+describe("getIdentityLockoutState", () => {+ const selector = { identityId: IDENTITY_ID, authMethod: IdentityAuthMethod.UNIVERSAL_AUTH, slug: "client-a" };- await getIdentityActiveLockoutAuthMethods(IDENTITY_ID, keyStore);+ test("reads the one key it already knows, and never the index", async () => {+ const keyStore = makeKeyStore();+ keyStore.getItem.mockResolvedValue(JSON.stringify({ lockedOut: true, failedAttempts: 3 }));+ await expect(getIdentityLockoutState(selector, keyStore)).resolves.toEqual({+ lockedOut: true,+ failedAttempts: 3+ });+ expect(keyStore.getItem).toHaveBeenCalledWith(itemKey(IdentityAuthMethod.UNIVERSAL_AUTH, "client-a"));+ expect(keyStore.sortedSetRangeByScore).not.toHaveBeenCalled();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("treats a missing key as no lockout, since the key's TTL is the expiry", async () => {+ await expect(getIdentityLockoutState(selector, makeKeyStore())).resolves.toBeUndefined();});- test("returns an empty list for an empty hash and for a missing key", async () => {- await expect(getIdentityActiveLockoutAuthMethods(IDENTITY_ID, makeKeyStore({}))).resolves.toEqual([]);+ test("treats an unreadable value as no lockout rather than failing the login", async () => {+ const keyStore = makeKeyStore();+ keyStore.getItem.mockResolvedValue("{{{");- const missing = { ...makeKeyStore({}), hashGetAll: vi.fn().mockResolvedValue(null) };- await expect(getIdentityActiveLockoutAuthMethods(IDENTITY_ID, missing)).resolves.toEqual([]);+ await expect(getIdentityLockoutState(selector, keyStore)).resolves.toBeUndefined();});+});- 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+describe("getIdentityActiveLockoutAuthMethods", () => {+ test("ranges the index by score and reports the methods it names", async () => {+ const keyStore = makeKeyStore();+ keyStore.sortedSetRangeByScore.mockResolvedValue([+ `${IdentityAuthMethod.UNIVERSAL_AUTH}:client-a`,+ `${IdentityAuthMethod.LDAP_AUTH}:alice`]);- });-- 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.UNIVERSAL_AUTH,IdentityAuthMethod.LDAP_AUTH]);++ const [key, min, max] = keyStore.sortedSetRangeByScore.mock.calls[0] as [string, number, string];+ expect(key).toBe(INDEX_KEY);+ expect(max).toBe("+inf");+ // Filtering by score is what makes a member that outlived its key harmless.+ expect(min).toBeGreaterThan(0);});-});-describe("getIdentityLockoutState", () => {- const selector = { identityId: IDENTITY_ID, authMethod: IdentityAuthMethod.UNIVERSAL_AUTH, slug: "client-a" };+ test("reads no item keys at all", async () => {+ const keyStore = makeKeyStore();+ keyStore.sortedSetRangeByScore.mockResolvedValue([`${IdentityAuthMethod.LDAP_AUTH}:alice`]);- 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 getIdentityActiveLockoutAuthMethods(IDENTITY_ID, keyStore);- 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();+ expect(keyStore.getKeysByPattern).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("reports a method locked under several slugs once", async () => {+ const keyStore = makeKeyStore();+ keyStore.sortedSetRangeByScore.mockResolvedValue([+ `${IdentityAuthMethod.LDAP_AUTH}:alice`,+ `${IdentityAuthMethod.LDAP_AUTH}:bob`+ ]);++ await expect(getIdentityActiveLockoutAuthMethods(IDENTITY_ID, keyStore)).resolves.toEqual([+ IdentityAuthMethod.LDAP_AUTH+ ]);});- 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 an empty list for an identity with no index", async () => {+ await expect(getIdentityActiveLockoutAuthMethods(IDENTITY_ID, makeKeyStore())).resolves.toEqual([]);});- 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();+ test("ignores a member with no method separator", async () => {+ const keyStore = makeKeyStore();+ keyStore.sortedSetRangeByScore.mockResolvedValue(["malformed", `${IdentityAuthMethod.LDAP_AUTH}:alice`]);- const corrupt = { ...makeKeyStore({}), hashGet: vi.fn().mockResolvedValue("{{{") };- await expect(getIdentityLockoutState(selector, corrupt)).resolves.toBeUndefined();+ await expect(getIdentityActiveLockoutAuthMethods(IDENTITY_ID, keyStore)).resolves.toEqual([+ IdentityAuthMethod.LDAP_AUTH+ ]);});});describe("persistIdentityLockoutState", () => {- test("writes the hash field only, stamped with its own deadline", async () => {- const keyStore = makeKeyStore({});+ test("indexes a lockout so the list endpoints can see it", async () => {+ const keyStore = makeKeyStore();await persistIdentityLockoutState({@@ -139,79 +123,96 @@ describe("persistIdentityLockoutState", () => {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());+ expect(keyStore.setIndexedItemWithExpiry).toHaveBeenCalledWith({+ indexKey: INDEX_KEY,+ member: `${IdentityAuthMethod.UNIVERSAL_AUTH}:client-a`,+ itemKey: itemKey(IdentityAuthMethod.UNIVERSAL_AUTH, "client-a"),+ value: JSON.stringify({ lockedOut: true, failedAttempts: 3 }),+ expiryInSeconds: 300,+ indexed: true+ });+ });++ test("does not index a failure counter", async () => {+ // The list endpoints have no use for counters, and on LDAP their slug is caller-supplied. Keeping+ // them out of the index is what stops a username spray from enlarging that read.+ const keyStore = makeKeyStore();++ await persistIdentityLockoutState(+ { identityId: IDENTITY_ID, authMethod: IdentityAuthMethod.LDAP_AUTH, slug: "alice", expiryInSeconds: 30 },+ { lockedOut: false, failedAttempts: 1 },+ keyStore+ );++ expect(keyStore.setIndexedItemWithExpiry).toHaveBeenCalledWith(expect.objectContaining({ indexed: false }));});});describe("clearIdentityLockoutState", () => {- test("removes the hash field and touches no string key", async () => {- const keyStore = makeKeyStore({});+ test("removes the item and its index member together", 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();+ // Dropping only the item would leave the index reporting a lockout that no longer exists.+ expect(keyStore.deleteIndexedItems).toHaveBeenCalledWith({+ indexKey: INDEX_KEY,+ members: [`${IdentityAuthMethod.LDAP_AUTH}:alice`],+ itemKeys: [itemKey(IdentityAuthMethod.LDAP_AUTH, "alice")]+ });});});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);+ test("clears every locked slug for that method and no others", async () => {+ const keyStore = makeKeyStore();+ keyStore.sortedSetMembersPrimary.mockResolvedValue([+ `${IdentityAuthMethod.UNIVERSAL_AUTH}:client-a`,+ `${IdentityAuthMethod.LDAP_AUTH}:alice`,+ `${IdentityAuthMethod.LDAP_AUTH}:bob`+ ]);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();+ expect(keyStore.deleteIndexedItems).toHaveBeenCalledWith({+ indexKey: INDEX_KEY,+ members: [`${IdentityAuthMethod.LDAP_AUTH}:alice`, `${IdentityAuthMethod.LDAP_AUTH}:bob`],+ itemKeys: [itemKey(IdentityAuthMethod.LDAP_AUTH, "alice"), itemKey(IdentityAuthMethod.LDAP_AUTH, "bob")]+ });});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() });+ const keyStore = makeKeyStore();+ keyStore.sortedSetMembersPrimary.mockResolvedValue([`${IdentityAuthMethod.LDAP_AUTH}:alice`]);await clearIdentityLockoutsForAuthMethod(IDENTITY_ID, IdentityAuthMethod.LDAP_AUTH, keyStore);- expect(keyStore.hashGetAllPrimary).toHaveBeenCalledWith(HASH_KEY);- expect(keyStore.hashGetAll).not.toHaveBeenCalled();+ expect(keyStore.sortedSetMembersPrimary).toHaveBeenCalledWith(INDEX_KEY);+ expect(keyStore.sortedSetRangeByScore).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() });+ test("never scans the keyspace", async () => {+ const keyStore = makeKeyStore();+ keyStore.sortedSetMembersPrimary.mockResolvedValue([`${IdentityAuthMethod.LDAP_AUTH}:alice`]);++ await clearIdentityLockoutsForAuthMethod(IDENTITY_ID, IdentityAuthMethod.LDAP_AUTH, keyStore);++ expect(keyStore.getKeysByPattern).not.toHaveBeenCalled();+ expect(keyStore.deleteItems).not.toHaveBeenCalled();+ });++ test("is a no-op when the identity has no lockout for that method", async () => {+ const keyStore = makeKeyStore();+ keyStore.sortedSetMembersPrimary.mockResolvedValue([`${IdentityAuthMethod.UNIVERSAL_AUTH}:client-a`]);await expect(clearIdentityLockoutsForAuthMethod(IDENTITY_ID, IdentityAuthMethod.LDAP_AUTH, keyStore)).resolves.toBe(0);-- expect(keyStore.deleteItemsByKeyIn).not.toHaveBeenCalled();- expect(keyStore.hashDeleteFields).not.toHaveBeenCalled();+ expect(keyStore.deleteIndexedItems).not.toHaveBeenCalled();});});diff --git a/backend/src/services/identity/identity-fns.ts b/backend/src/services/identity/identity-fns.tsindex 8460844703..7c11327d1d 100644--- a/backend/src/services/identity/identity-fns.ts+++ b/backend/src/services/identity/identity-fns.ts@@ -4,66 +4,49 @@ 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 lockoutIndexKey = (identityId: string) => KeyStorePrefixes.IdentityLockoutIndex(identityId);+const lockoutMember = (authMethod: string, slug: string) => KeyStorePrefixes.IdentityLockoutMember(authMethod, slug);+const lockoutItemKey = (identityId: string, authMethod: string, slug: string) =>+ KeyStorePrefixes.IdentityLockoutState(identityId, authMethod, slug);-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)}`);+ KeyStorePrefixes.IdentityLockoutLock(lockoutItemKey(identityId, authMethod, slug));export const getIdentityLockoutState = async ({ identityId, authMethod, slug }: { identityId: string; authMethod: string; slug: string },- keyStore: Pick<TKeyStoreFactory, "hashGet">+ keyStore: Pick<TKeyStoreFactory, "getItem">): Promise<TIdentityLockoutState | undefined> => {- const raw = await keyStore.hashGet(lockoutHashKey(identityId), lockoutField(authMethod, slug));+ const raw = await keyStore.getItem(lockoutItemKey(identityId, authMethod, slug));if (!raw) return undefined;- const state = parseLockoutState(raw);- if (!state || !isLive(state, Date.now())) return undefined;-- return state;+ try {+ return JSON.parse(raw) as TIdentityLockoutState;+ } catch {+ // An unreadable value must not fail the login it was read for.+ return undefined;+ }};+// Runs once per row on the list endpoints. Only locked methods are indexed, so this costs one range+// read bounded by how many of an identity's methods are locked right nowexport const getIdentityActiveLockoutAuthMethods = async (identityId: string,- keyStore: Pick<TKeyStoreFactory, "hashGetAll">+ keyStore: Pick<TKeyStoreFactory, "sortedSetRangeByScore">) => {- const lockoutStates = await keyStore.hashGetAll(lockoutHashKey(identityId));+ const members = await keyStore.sortedSetRangeByScore(lockoutIndexKey(identityId), Date.now(), "+inf");- const now = Date.now();const activeLockoutAuthMethods = new Set<string>();-- 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));+ members.forEach((member) => {+ const separatorIndex = member.indexOf(":");+ if (separatorIndex > 0) activeLockoutAuthMethods.add(member.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.+// The counter and the lockout share one key and one TTL.export const persistIdentityLockoutState = async ({identityId,@@ -71,41 +54,50 @@ export const persistIdentityLockoutState = async (slug,expiryInSeconds}: { identityId: string; authMethod: string; slug: string; expiryInSeconds: number },- lockout: { lockedOut: boolean; failedAttempts: number },- keyStore: Pick<TKeyStoreFactory, "hashSetFieldWithMinExpiry">+ lockout: TIdentityLockoutState,+ keyStore: Pick<TKeyStoreFactory, "setIndexedItemWithExpiry">) => {- await keyStore.hashSetFieldWithMinExpiry(- lockoutHashKey(identityId),- lockoutField(authMethod, slug),- JSON.stringify({ ...lockout, expiresAt: Date.now() + expiryInSeconds * 1000 }),- expiryInSeconds- );+ await keyStore.setIndexedItemWithExpiry({+ indexKey: lockoutIndexKey(identityId),+ member: lockoutMember(authMethod, slug),+ itemKey: lockoutItemKey(identityId, authMethod, slug),+ value: JSON.stringify(lockout),+ expiryInSeconds,+ indexed: lockout.lockedOut+ });};+// Both halves, or the index keeps reporting a lockout whose key is already gone.export const clearIdentityLockoutState = async ({ identityId, authMethod, slug }: { identityId: string; authMethod: string; slug: string },- keyStore: Pick<TKeyStoreFactory, "hashDeleteFields">+ keyStore: Pick<TKeyStoreFactory, "deleteIndexedItems">) => {- await keyStore.hashDeleteFields(lockoutHashKey(identityId), [lockoutField(authMethod, slug)]);+ await keyStore.deleteIndexedItems({+ indexKey: lockoutIndexKey(identityId),+ members: [lockoutMember(authMethod, slug)],+ itemKeys: [lockoutItemKey(identityId, 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">+ keyStore: Pick<TKeyStoreFactory, "sortedSetMembersPrimary" | "deleteIndexedItems">) => {- const hashKey = lockoutHashKey(identityId);- const fieldPrefix = `${authMethod}:`;+ const indexKey = lockoutIndexKey(identityId);+ const memberPrefix = `${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;+ const members = await keyStore.sortedSetMembersPrimary(indexKey);+ const matching = members.filter((member) => member.startsWith(memberPrefix));+ if (!matching.length) return 0;++ await keyStore.deleteIndexedItems({+ indexKey,+ members: matching,+ itemKeys: matching.map((member) => lockoutItemKey(identityId, authMethod, member.slice(memberPrefix.length)))+ });- return keyStore.hashDeleteFields(hashKey, fields);+ return matching.length;};export const buildAuthMethods = ({diff --git a/backend/src/services/identity/identity-service.test.ts b/backend/src/services/identity/identity-service.test.tsindex f730db74da..cfe0a5d9fc 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: { hashGetAll: vi.fn().mockResolvedValue({}) } as never,+ keyStore: { sortedSetRangeByScore: 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 79a06881ae..ba0f9b4372 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, "hashGetAll">;+ keyStore: Pick<TKeyStoreFactory, "sortedSetRangeByScore">;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 756e29b793..e329e5aabd 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: { hashGetAll: vi.fn().mockResolvedValue({}) } as never,+ keyStore: { sortedSetRangeByScore: 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 3abe443132..c3a86271ef 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, "hashGetAll">;+ keyStore: Pick<TKeyStoreFactory, "sortedSetRangeByScore">;usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit" | "emitForProject">;alertService: Pick<TAlertServiceFactory, "deleteAlertsForResource">;identityAccessTokenService: Pick<