Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

Take a refunded try back off where it was counted

Claude4413786deb69
diff --git a/src/lib/security/rate-limit.dbtest.ts b/src/lib/security/rate-limit.dbtest.ts
index 4df9b3e..48bb3b0 100644
--- a/src/lib/security/rate-limit.dbtest.ts
+++ b/src/lib/security/rate-limit.dbtest.ts
@@ -51,32 +51,38 @@ test("requests up to the limit pass, the next one waits, and the count starts ov
assert.deepEqual(await at(0), {
allowed: true,
count: 1,
+ countedIn: "database",
retryAfterSeconds: 60,
});
assert.deepEqual(await at(1000), {
allowed: true,
count: 2,
+ countedIn: "database",
retryAfterSeconds: 59,
});
assert.deepEqual(await at(15_000), {
allowed: false,
count: 3,
+ countedIn: "database",
retryAfterSeconds: 45,
});
// Trying again while blocked does not push the window back.
assert.deepEqual(await at(59_000), {
allowed: false,
count: 4,
+ countedIn: "database",
retryAfterSeconds: 1,
});
assert.deepEqual(await at(MINUTE), {
allowed: true,
count: 1,
+ countedIn: "database",
retryAfterSeconds: 60,
});
assert.deepEqual(await at(MINUTE + 1), {
allowed: true,
count: 2,
+ countedIn: "database",
retryAfterSeconds: 60,
});
assert.equal((await at(MINUTE + 2)).allowed, false);
diff --git a/src/lib/security/rate-limit.test.ts b/src/lib/security/rate-limit.test.ts
index 61bbfd7..26f23fd 100644
--- a/src/lib/security/rate-limit.test.ts
+++ b/src/lib/security/rate-limit.test.ts
@@ -6,6 +6,7 @@ import {
clearRateLimitStoreForTests,
consumeRateLimit,
consumeRateLimitInMemory,
+ refundRateLimit,
} from "./rate-limit.ts";
// The statement itself is exercised against a real Postgres in
@@ -54,6 +55,7 @@ test("in memory, requests up to the limit are allowed and the next is not", () =
assert.deepEqual(consumeRateLimitInMemory({ ...input, now: START + 10 }), {
allowed: false,
count: 4,
+ countedIn: "memory",
retryAfterSeconds: 60,
});
});
@@ -115,6 +117,7 @@ test("the database's count decides, and only a hash of the key is sent to it", a
assert.deepEqual(decision, {
allowed: false,
count: 6,
+ countedIn: "database",
retryAfterSeconds: 30,
});
@@ -164,3 +167,41 @@ test("when the database cannot be used the limit is still enforced, from memory"
// Said once, not once per request.
assert.equal(warn.mock.callCount(), 1);
});
+
+test("a refund goes to the store that counted the request", async () => {
+ const input = {
+ key: "access:signer:code",
+ limit: 5,
+ now: START,
+ windowMs: MINUTE,
+ };
+ const down = fakeDatabase(() => new Error("connection refused"));
+
+ // Counted in memory while the database could not be asked.
+ await consumeRateLimit(input, { database: down.database });
+ const second = await consumeRateLimit(input, { database: down.database });
+
+ assert.equal(second.countedIn, "memory");
+
+ // The database is back by the time of the refund: memory is still where
+ // the count is taken off, and the database is not asked.
+ const up = fakeDatabase(() => ({ count: 0, expires_at: START + MINUTE }));
+
+ await refundRateLimit(input.key, second, {
+ database: up.database,
+ now: START,
+ });
+
+ assert.equal(up.queries.length, 0);
+ assert.equal(consumeRateLimitInMemory(input).count, 2);
+
+ // Counted in the database: the database is where it comes off.
+ await refundRateLimit(
+ input.key,
+ { countedIn: "database" },
+ { database: up.database, now: START },
+ );
+
+ assert.equal(up.queries.length, 1);
+ assert.match(up.queries[0]!.text, /count = greatest\(count - 1, 0\)/);
+});
diff --git a/src/lib/security/rate-limit.ts b/src/lib/security/rate-limit.ts
index ad1ed3e..e4fa8dc 100644
--- a/src/lib/security/rate-limit.ts
+++ b/src/lib/security/rate-limit.ts
@@ -17,6 +17,8 @@ export type RateLimitDecision = {
count: number;
/** Seconds until the current window ends. At least 1 when not allowed. */
retryAfterSeconds: number;
+ /** Where this request was counted, for refundRateLimit. */
+ countedIn?: "database" | "memory";
};
type RateLimitInput = {
@@ -101,7 +103,10 @@ export function consumeRateLimitInMemory(
memoryStore.set(input.key, entry);
- return toDecision(entry.count, entry.expiresAt, input, now);
+ return {
+ ...toDecision(entry.count, entry.expiresAt, input, now),
+ countedIn: "memory",
+ };
}
function warnAboutFallback(error: unknown) {
@@ -181,7 +186,10 @@ export async function consumeRateLimit(
void deleteExpiredRateLimits(executor, now).catch(() => undefined);
}
- return toDecision(row.count, Number(row.expires_at), input, now);
+ return {
+ ...toDecision(row.count, Number(row.expires_at), input, now),
+ countedIn: "database",
+ };
} catch (error) {
warnAboutFallback(error);
@@ -243,22 +251,15 @@ export async function peekRateLimit(
*/
export async function refundRateLimit(
key: string,
+ counted: Pick<RateLimitDecision, "countedIn">,
{
database,
now = Date.now(),
}: ConsumeRateLimitOptions & { now?: number } = {},
): Promise<void> {
- try {
- // One statement, so refunds that arrive together each take one off:
- // the row's lock puts them in turn. A count of zero is left in place;
- // consumeRateLimit treats it as no window at all.
- await (database ?? getDb()).query(
- "update public.rate_limits set count = greatest(count - 1, 0) where key = $1 and expires_at > $2",
- [hashKey(key), now],
- );
- } catch (error) {
- warnAboutFallback(error);
-
+ // Taken back where it was counted: a count kept in memory while the
+ // database could not be asked is not in the database, and the other way.
+ if (counted.countedIn === "memory") {
const entry = memoryStore.get(key);
if (entry && entry.count <= 1) {
@@ -266,6 +267,22 @@ export async function refundRateLimit(
} else if (entry && entry.expiresAt > now) {
entry.count -= 1;
}
+
+ return;
+ }
+
+ // One statement, so refunds that arrive together each take one off:
+ // the row's lock puts them in turn. A count of zero is left in place;
+ // consumeRateLimit treats it as no window at all. If the database cannot
+ // be asked now, the try stays counted: a limit that is too strict for a
+ // while is safer than one that forgets.
+ try {
+ await (database ?? getDb()).query(
+ "update public.rate_limits set count = greatest(count - 1, 0) where key = $1 and expires_at > $2",
+ [hashKey(key), now],
+ );
+ } catch (error) {
+ warnAboutFallback(error);
}
}
diff --git a/src/lib/signing.ts b/src/lib/signing.ts
index d5d0336..e8961bb 100644
--- a/src/lib/signing.ts
+++ b/src/lib/signing.ts
@@ -1662,7 +1662,7 @@ export async function verifySignerCheck(
passed = checkAccessCode(parsed.code, state.accessCodeHash!);
if (passed) {
- await refundRateLimit(failuresKey, { database });
+ await refundRateLimit(failuresKey, attempt, { database });
}
} else {
// Count the attempt and read the code in one statement, so parallel