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: enhance identity lockout keystore with bounded reaping logic and new test
Victor Hugo dos Santosa3d41083093f
diff --git a/backend/e2e-test/identity-lockout-keystore.spec.ts b/backend/e2e-test/identity-lockout-keystore.spec.tsindex d3abe077ee..40323f35fc 100644--- a/backend/e2e-test/identity-lockout-keystore.spec.ts+++ b/backend/e2e-test/identity-lockout-keystore.spec.ts@@ -144,6 +144,46 @@ describe("identity lockout keystore", () => {);});+ test("the reap walks a bounded slice, so one write cannot be made to cost O(fields)", async () => {+ // LDAP slugs are caller-supplied usernames, so the field count is attacker-driven. Walking the+ // whole hash per write would make distributed attempts against one identity scale with the+ // square of the number of sources, on the single-threaded server this change exists to protect.+ const expired = JSON.stringify({ lockedOut: false, failedAttempts: 1, expiresAt: Date.now() - 1_000 });+ const sprayed: Record<string, string> = {};+ for (let i = 0; i < 400; 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+ );++ await write();+ const afterOne = await testRedis.hlen(lockoutFor(identityId));++ // Bounded: one write cannot have reclaimed all 400. If this ever reaches 1 the reap has gone+ // back to walking the whole hash and the cost is caller-controlled again.+ expect(afterOne).toBeGreaterThan(1);+ expect(afterOne).toBeLessThan(401);++ // ...but it reclaims far more per write than the single field a write adds, so it converges+ // rather than falling behind.+ let previous = afterOne;+ for (let i = 0; i < 12; i += 1) {+ // eslint-disable-next-line no-await-in-loop+ await write();+ // eslint-disable-next-line no-await-in-loop+ const current = await testRedis.hlen(lockoutFor(identityId));+ expect(current).toBeLessThanOrEqual(previous);+ previous = current;+ }+ expect(previous).toBeLessThan(afterOne);+ });+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.diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex 1dccf335fb..1bd86a1329 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -544,6 +544,8 @@ export const keyStoreFactory = (// 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])@@ -555,8 +557,13 @@ export const keyStoreFactory = (if redis.call('HLEN', KEYS[1]) > tonumber(ARGV[5]) thenlocal now = tonumber(ARGV[4])- local entries = redis.call('HGETALL', KEYS[1])- for i = 1, #entries, 2 do+ local batch = tonumber(ARGV[6])+ local scanned = redis.call('HSCAN', KEYS[1], '0', 'COUNT', batch)+ local entries = scanned[2]+ -- COUNT is only a hint, and a listpack-encoded hash ignores it and returns every field, so the+ -- loop is what actually bounds the decoding.+ local limit = math.min(#entries, batch * 2)+ for i = 1, limit, 2 doif entries[i] ~= ARGV[1] thenlocal ok, parsed = pcall(cjson.decode, entries[i + 1])if ok and type(parsed) == 'table' and type(parsed.expiresAt) == 'number' and parsed.expiresAt <= now then@@ -570,6 +577,7 @@ export const keyStoreFactory = (`;const HASH_FIELD_REAP_THRESHOLD = 50;+ const HASH_FIELD_REAP_BATCH = 64;const hashSetFieldWithMinExpiry = async (key: string, field: string, value: string, expiryInSeconds: number) => {await primaryRedis.eval(@@ -580,7 +588,8 @@ export const keyStoreFactory = (value,String(expiryInSeconds),String(Date.now()),- String(HASH_FIELD_REAP_THRESHOLD)+ String(HASH_FIELD_REAP_THRESHOLD),+ String(HASH_FIELD_REAP_BATCH));};