Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add checks for development env in route.ts and rateLimiter for testing #17

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ jobs:
run: pnpm exec playwright install chromium
- name: Start Development Server in Background
run: |
nohup pnpm dev & # Run server in the background
sleep 10 # Give it a moment to start (optional)
nohup pnpm dev &
sleep 6
- name: Run Tests
run: pnpm test
- uses: actions/upload-artifact@v4
Expand Down
9 changes: 0 additions & 9 deletions playwright.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,4 @@ export default defineConfig({
use: { ...devices['Desktop Chrome'] }
}
],

webServer: {
command: 'pnpm dev',
url: 'http://127.0.0.1:3000',
reuseExistingServer: true,
env: {
REDIS_URL: process.env.REDIS_URL as string
}
}
});
7 changes: 7 additions & 0 deletions src/app/contact/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@ export async function POST(request: NextRequest): Promise<Response> {
);
}

if (process.env.NODE_ENV === 'development') {
return new NextResponse(
JSON.stringify({ message: 'Development Mode' }),
{ status: 200 }
);
}

const res = await fetch('https://api.resend.com/emails', {
method: 'POST',
headers: {
Expand Down
10 changes: 5 additions & 5 deletions src/lib/middleware/rate-limiter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@ import redis from '../config/redis';
const WINDOW_SIZE_IN_SECONDS = 86400;
const MAX_REQUESTS_PER_WINDOW = 3;

const namespace =
process.env.NODE_ENV === 'development' ? 'test:' : '';

export async function rateLimiter(request: NextRequest) {
try {
const ip =
request.headers.get('x-forwarded-for') ||
request.headers.get('x-real-ip') ||
'anonymous';
const key = `rate_limit:${ip}`;

// Get the current request count for this IP
const key = `${namespace}rate_limit:${ip}`;
const currentRequestCount = await redis.get(key);

if (currentRequestCount === null) {
Expand All @@ -36,7 +37,6 @@ export async function rateLimiter(request: NextRequest) {
await redis.incr(key);
return null;
} catch (error) {
console.error('Rate limiting error:', error);
return null;
console.error('Rate limiter error:', error);
}
}
23 changes: 5 additions & 18 deletions tests/contact-form/rate-limiter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,12 @@ test.describe('Contact Form Rate Limiter', () => {
const DAILY_LIMIT = 3;

test.beforeEach(async ({ page }) => {
// Clear any existing rate limit data
const keys = await redis.keys('rate_limit:*');
// Clear Redis keys with the "test:*" namespace before each test
const keys = await redis.keys('test:*');
if (keys.length > 0) {
await redis.del(...keys);
}

// Set consistent IP for testing
await page.setExtraHTTPHeaders({
'X-Forwarded-For': '127.0.0.1'
});
Expand All @@ -35,7 +34,9 @@ test.describe('Contact Form Rate Limiter', () => {
expect(response[0].ok()).toBe(true);

// Wait for toast to disappear
await page.waitForTimeout(2000);
await page
.locator('li[role="status"]')
.waitFor({ state: 'hidden', timeout: 7500 });
}

// Next submission should be rate limited
Expand All @@ -53,25 +54,11 @@ test.describe('Contact Form Rate Limiter', () => {
page.click('input[type="submit"]')
]);

if (response[0].status() !== 429) {
const text = await response[0].text();
console.log('Unexpected response:', text);
console.log('Response status:', response[0].status());
}

expect(response[0].status()).toBe(429);

// Check for rate limit toast
const rateLimitToast = page.locator('li[role="status"]');
await expect(rateLimitToast).toBeVisible();
await expect(rateLimitToast).toContainText('Rate Limit Exceeded');
});

test.afterAll(async () => {
// Clean up Redis after tests
const keys = await redis.keys('rate_limit:*');
if (keys.length > 0) {
await redis.del(...keys);
}
});
});
Loading