-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
13 changed files
with
340 additions
and
72 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
2.5 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
2.5 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
import { Throttler, createThrottlerStorage } from "./Throttler"; | ||
|
||
export class SlipAuthRateLimiters { | ||
login: Throttler; | ||
|
||
constructor() { | ||
this.login = new Throttler({ | ||
points: 5, | ||
duration: 0, | ||
}, | ||
{ | ||
storage: createThrottlerStorage("./data/ratelimiter/login"), | ||
}); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
import { RateLimiterMemory, RateLimiterRes, type IRateLimiterOptions } from "rate-limiter-flexible"; | ||
import { createStorage, type Storage } from "unstorage"; | ||
import fsDriver from "unstorage/drivers/fs"; | ||
import { SlipAuthRateLimiterError } from "../errors/SlipAuthError"; | ||
|
||
export function createThrottlerStorage(base: string = "./.data/cache/ratelimit"): Storage<number> { | ||
return createStorage<number>({ | ||
driver: fsDriver({ base }), | ||
}); | ||
} | ||
|
||
export class Throttler extends RateLimiterMemory { | ||
storage: Storage<number>; | ||
initialBlockDurationSeconds = 5; | ||
#incrementFactor = 2; | ||
|
||
constructor(depOptions: IRateLimiterOptions, options: { storage: Storage<number>, initialBlockDurationSeconds?: number }) { | ||
super(depOptions); | ||
this.storage = options.storage; | ||
this.initialBlockDurationSeconds = options.initialBlockDurationSeconds ?? this.initialBlockDurationSeconds; | ||
} | ||
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
async consumeIncremental(key: string | number, pointsToConsume?: number, options?: { [key: string]: any }): Promise<RateLimiterRes | SlipAuthRateLimiterError> { | ||
const strKey = key.toString(); | ||
const cachedBlockDuration = await this.storage.getItem(strKey) ?? (this.initialBlockDurationSeconds / this.#incrementFactor); | ||
|
||
return super.consume(strKey, pointsToConsume, options) | ||
.then((res) => { | ||
this.storage.setItem(strKey, cachedBlockDuration); | ||
|
||
if (res.remainingPoints <= 0) { | ||
this.block(strKey, cachedBlockDuration); | ||
} | ||
|
||
return res; | ||
}) | ||
.catch((error) => { | ||
let msBeforeNext; | ||
|
||
if (error instanceof RateLimiterRes && error.remainingPoints === 0) { | ||
// Increase block duration and ensure it stays within the 32-bit signed integer range | ||
const newBlockDuration = Math.min(cachedBlockDuration * 2, Number.MAX_SAFE_INTEGER); | ||
this.storage.setItem(strKey, newBlockDuration); | ||
msBeforeNext = newBlockDuration * 1000; | ||
} | ||
|
||
return new SlipAuthRateLimiterError({ | ||
msBeforeNext: msBeforeNext, | ||
}); | ||
}); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,12 +1,12 @@ | ||
import { describe, it, expect, vi, beforeEach, beforeAll } from "vitest"; | ||
import { describe, it, expect, vi, beforeEach } from "vitest"; | ||
import sqlite from "db0/connectors/better-sqlite3"; | ||
import { createDatabase } from "db0"; | ||
import { SlipAuthCore } from "../src/runtime/core/core"; | ||
import type { SlipAuthUser } from "~/src/runtime/core/types"; | ||
import { autoSetupTestsDatabase, createH3Event, testTablesNames } from "./test-helpers"; | ||
import { RateLimitLoginError, SlipAuthRateLimiterError } from "../src/runtime/core/errors/SlipAuthError"; | ||
|
||
const db = createDatabase(sqlite({ | ||
name: "core-email-password.test", | ||
name: "rate-limit.test", | ||
})); | ||
|
||
let auth: SlipAuthCore; | ||
|
@@ -15,6 +15,11 @@ beforeEach(async () => { | |
await autoSetupTestsDatabase(db); | ||
}); | ||
|
||
const defaultInsert = { | ||
email: "[email protected]", | ||
password: "pa$$word", | ||
}; | ||
|
||
const mocks = vi.hoisted(() => { | ||
return { | ||
userCreatedCount: 0, | ||
|
@@ -63,9 +68,44 @@ describe("rate limit", () => { | |
}); | ||
|
||
describe("login", () => { | ||
it("should work", async () => { | ||
auth.login(createH3Event(), { email: "[email protected]", password: "password" }); | ||
auth.login(createH3Event(), { email: "[email protected]", password: "password" }); | ||
it.only("should allow 5 failed tries", async () => { | ||
await auth.register(createH3Event(), defaultInsert); | ||
const doAttempt = () => auth.login(createH3Event(), { | ||
email: defaultInsert.email, | ||
password: defaultInsert.password + "123", | ||
}); | ||
|
||
const results = await Promise.all([ | ||
doAttempt(), | ||
doAttempt(), | ||
doAttempt(), | ||
doAttempt(), | ||
doAttempt(), | ||
]); | ||
|
||
expect(results.every(res => res instanceof SlipAuthRateLimiterError)).toBe(false); | ||
}); | ||
|
||
it("should rate-limit 6 failed tries", async () => { | ||
await auth.register(createH3Event(), defaultInsert); | ||
const doAttempt = () => auth.login(createH3Event(), { | ||
email: defaultInsert.email, | ||
password: defaultInsert.password + "123", | ||
}).catch(e => e); | ||
|
||
const results = await Promise.all([ | ||
doAttempt(), | ||
doAttempt(), | ||
doAttempt(), | ||
doAttempt(), | ||
doAttempt(), | ||
doAttempt(), | ||
]); | ||
|
||
console.log(results); | ||
|
||
|
||
expect(results.every(res => res instanceof RateLimitLoginError)).toBe(false); | ||
}); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
import { beforeEach, describe, expect, it, vi } from "vitest"; | ||
import { Throttler } from "../src/runtime/core/rate-limit/Throttler"; | ||
import { SlipAuthRateLimiterError } from "../src/runtime/core/errors/SlipAuthError"; | ||
import { RateLimiterRes } from "rate-limiter-flexible"; | ||
import { createStorage } from "unstorage"; | ||
import memoryDriver from "unstorage/drivers/memory"; | ||
|
||
const date = new Date(Date.UTC(1998, 11, 19)); | ||
|
||
const storage = createStorage<number>({ | ||
driver: memoryDriver(), | ||
}); | ||
|
||
describe("Throttler", () => { | ||
beforeEach(() => { | ||
storage.clear(); | ||
}); | ||
|
||
it("should allow X failed attemps", async () => { | ||
const attempsLimit = 5; | ||
|
||
const rateLimit = new Throttler({ | ||
points: attempsLimit, | ||
duration: 20, | ||
}, | ||
{ | ||
storage, | ||
}); | ||
|
||
const attemptsArray = Array.from(Array(attempsLimit).keys()); | ||
const attemptsResults = await Promise.all(attemptsArray.map(async () => { | ||
return await rateLimit.consumeIncremental("hey"); | ||
})); | ||
|
||
expect(attemptsResults.every(_result => _result instanceof RateLimiterRes)).toBe(true); | ||
}); | ||
|
||
it("should not allow X + 1 failed attemps", async () => { | ||
const attempsLimit = 5; | ||
|
||
const rateLimit = new Throttler({ | ||
points: attempsLimit, | ||
duration: 20, | ||
}, | ||
{ | ||
storage, | ||
}); | ||
|
||
const attemptsArray = Array.from(Array(attempsLimit + 1).keys()); | ||
const attemptsResults = await Promise.all(attemptsArray.map(async () => { | ||
return await rateLimit.consumeIncremental("hey"); | ||
})); | ||
|
||
const allAttemptsButLast = attemptsResults.slice(0, -1); | ||
const lastAttempt = attemptsResults[attemptsResults.length - 1]; | ||
|
||
expect(allAttemptsButLast.every(_result => _result instanceof RateLimiterRes)).toBe(true); | ||
expect(lastAttempt instanceof SlipAuthRateLimiterError).toBe(true); | ||
expect((lastAttempt as SlipAuthRateLimiterError).data.msBeforeNext).toBe(5000); | ||
}); | ||
|
||
it("should increment timeout on failed attemps", async () => { | ||
vi.useFakeTimers(); | ||
vi.setSystemTime(date); | ||
|
||
const attempsLimit = 5; | ||
|
||
const rateLimit = new Throttler({ | ||
points: attempsLimit, | ||
duration: 20, | ||
}, | ||
{ | ||
storage, | ||
initialBlockDurationSeconds: 1, | ||
}); | ||
|
||
const attemptsArray = Array.from(Array(attempsLimit).keys()); | ||
await Promise.all(attemptsArray.map(async () => { | ||
return await rateLimit.consumeIncremental("hey"); | ||
})); | ||
|
||
// Now, exceed the limit and verify block duration increments correctly | ||
let expectedMsBeforeNext = 1000; // Initial block duration in ms (1 second) | ||
for (let i = 0; i < 20; i++) { | ||
// vi.advanceTimersByTime(expectedMsBeforeNext); | ||
const result = await rateLimit.consumeIncremental("hey") as SlipAuthRateLimiterError; | ||
|
||
// Expect SlipAuthRateLimiterError after limit is reached | ||
expect(result instanceof SlipAuthRateLimiterError).toBe(true); | ||
expect(result.data.msBeforeNext).toBe( | ||
expectedMsBeforeNext, | ||
); | ||
|
||
// Double the expected block duration for the next iteration | ||
expectedMsBeforeNext = Math.min(expectedMsBeforeNext * 2, Number.MAX_SAFE_INTEGER); | ||
} | ||
}); | ||
}); |