Skip to content

test(clerk-js): Add dynamic TTL calculation tests for JWT expiration handling #6231

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
3 changes: 3 additions & 0 deletions .changeset/ten-kiwis-cry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
---
---

99 changes: 99 additions & 0 deletions packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,30 @@ vi.mock('../resources/Base', () => {
const jwt =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NzU4NzY3OTAsImRhdGEiOiJmb29iYXIiLCJpYXQiOjE2NzU4NzY3MzB9.Z1BC47lImYvaAtluJlY-kBo0qOoAk42Xb-gNrB2SxJg';

// Helper function to create JWT with custom exp and iat values using the same structure as the working JWT
function createJwtWithTtl(ttlSeconds: number): string {
// Use the existing JWT as template
const baseJwt =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NzU4NzY3OTAsImRhdGEiOiJmb29iYXIiLCJpYXQiOjE2NzU4NzY3MzB9.Z1BC47lImYvaAtluJlY-kBo0qOoAk42Xb-gNrB2SxJg';
const [headerB64, , signature] = baseJwt.split('.');

// Use the same iat as the original working JWT to maintain consistency with test environment
// Original JWT: iat: 1675876730, exp: 1675876790 (60 second TTL)
const baseIat = 1675876730;
const payload = {
exp: baseIat + ttlSeconds,
data: 'foobar', // Keep same data as original
iat: baseIat,
};

// Encode the new payload using base64url encoding (like JWT standard)
const payloadString = JSON.stringify(payload);
// Use proper base64url encoding: standard base64 but replace + with -, / with _, and remove padding =
const newPayloadB64 = btoa(payloadString).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');

return `${headerB64}.${newPayloadB64}.${signature}`;
}

describe('MemoryTokenCache', () => {
beforeAll(() => {
vi.useFakeTimers();
Expand Down Expand Up @@ -163,4 +187,79 @@ describe('MemoryTokenCache', () => {
expect(cache.get(key, 0)).toBeUndefined();
});
});

describe('dynamic TTL calculation', () => {
it('calculates expiresIn from JWT exp and iat claims and sets timeout based on calculated TTL', async () => {
const cache = SessionTokenCache;

// Mock Date.now to return a fixed timestamp initially
const initialTime = 1675876730000; // Same as our JWT's iat in milliseconds
vi.spyOn(Date, 'now').mockImplementation(() => initialTime);

// Test with a 30-second TTL
const shortTtlJwt = createJwtWithTtl(30);
const shortTtlToken = new Token({
object: 'token',
id: 'short-ttl',
jwt: shortTtlJwt,
});

const shortTtlKey = { tokenId: 'short-ttl', audience: 'test' };
const shortTtlResolver = Promise.resolve(shortTtlToken);
cache.set({ ...shortTtlKey, tokenResolver: shortTtlResolver });
await shortTtlResolver;

const cachedEntry = cache.get(shortTtlKey);
expect(cachedEntry).toMatchObject(shortTtlKey);

// Advance both the timer and the mocked current time
const advanceBy = 31 * 1000;
vi.advanceTimersByTime(advanceBy);
vi.spyOn(Date, 'now').mockImplementation(() => initialTime + advanceBy);

const cachedEntry2 = cache.get(shortTtlKey);
expect(cachedEntry2).toBeUndefined();
});
Comment on lines +192 to +222
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Fix Date.now mock cleanup to ensure test isolation.

The Date.now mock is not properly restored between test cases, which could cause test isolation issues.

  it('calculates expiresIn from JWT exp and iat claims and sets timeout based on calculated TTL', async () => {
    const cache = SessionTokenCache;

    // Mock Date.now to return a fixed timestamp initially
    const initialTime = 1675876730000; // Same as our JWT's iat in milliseconds
-   vi.spyOn(Date, 'now').mockImplementation(() => initialTime);
+   const dateNowSpy = vi.spyOn(Date, 'now').mockImplementation(() => initialTime);

    // Test with a 30-second TTL
    const shortTtlJwt = createJwtWithTtl(30);
    const shortTtlToken = new Token({
      object: 'token',
      id: 'short-ttl',
      jwt: shortTtlJwt,
    });

    const shortTtlKey = { tokenId: 'short-ttl', audience: 'test' };
    const shortTtlResolver = Promise.resolve(shortTtlToken);
    cache.set({ ...shortTtlKey, tokenResolver: shortTtlResolver });
    await shortTtlResolver;

    const cachedEntry = cache.get(shortTtlKey);
    expect(cachedEntry).toMatchObject(shortTtlKey);

    // Advance both the timer and the mocked current time
    const advanceBy = 31 * 1000;
    vi.advanceTimersByTime(advanceBy);
-   vi.spyOn(Date, 'now').mockImplementation(() => initialTime + advanceBy);
+   dateNowSpy.mockImplementation(() => initialTime + advanceBy);

    const cachedEntry2 = cache.get(shortTtlKey);
    expect(cachedEntry2).toBeUndefined();
+   
+   // Cleanup
+   dateNowSpy.mockRestore();
  });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it('calculates expiresIn from JWT exp and iat claims and sets timeout based on calculated TTL', async () => {
const cache = SessionTokenCache;
// Mock Date.now to return a fixed timestamp initially
const initialTime = 1675876730000; // Same as our JWT's iat in milliseconds
vi.spyOn(Date, 'now').mockImplementation(() => initialTime);
// Test with a 30-second TTL
const shortTtlJwt = createJwtWithTtl(30);
const shortTtlToken = new Token({
object: 'token',
id: 'short-ttl',
jwt: shortTtlJwt,
});
const shortTtlKey = { tokenId: 'short-ttl', audience: 'test' };
const shortTtlResolver = Promise.resolve(shortTtlToken);
cache.set({ ...shortTtlKey, tokenResolver: shortTtlResolver });
await shortTtlResolver;
const cachedEntry = cache.get(shortTtlKey);
expect(cachedEntry).toMatchObject(shortTtlKey);
// Advance both the timer and the mocked current time
const advanceBy = 31 * 1000;
vi.advanceTimersByTime(advanceBy);
vi.spyOn(Date, 'now').mockImplementation(() => initialTime + advanceBy);
const cachedEntry2 = cache.get(shortTtlKey);
expect(cachedEntry2).toBeUndefined();
});
it('calculates expiresIn from JWT exp and iat claims and sets timeout based on calculated TTL', async () => {
const cache = SessionTokenCache;
// Mock Date.now to return a fixed timestamp initially
const initialTime = 1675876730000; // Same as our JWT's iat in milliseconds
const dateNowSpy = vi.spyOn(Date, 'now').mockImplementation(() => initialTime);
// Test with a 30-second TTL
const shortTtlJwt = createJwtWithTtl(30);
const shortTtlToken = new Token({
object: 'token',
id: 'short-ttl',
jwt: shortTtlJwt,
});
const shortTtlKey = { tokenId: 'short-ttl', audience: 'test' };
const shortTtlResolver = Promise.resolve(shortTtlToken);
cache.set({ ...shortTtlKey, tokenResolver: shortTtlResolver });
await shortTtlResolver;
const cachedEntry = cache.get(shortTtlKey);
expect(cachedEntry).toMatchObject(shortTtlKey);
// Advance both the timer and the mocked current time
const advanceBy = 31 * 1000;
vi.advanceTimersByTime(advanceBy);
dateNowSpy.mockImplementation(() => initialTime + advanceBy);
const cachedEntry2 = cache.get(shortTtlKey);
expect(cachedEntry2).toBeUndefined();
// Cleanup
dateNowSpy.mockRestore();
});
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/__tests__/tokenCache.spec.ts around lines 192 to
222, the Date.now mock is not restored after the test, risking interference with
other tests. To fix this, add a cleanup step to restore the original Date.now
implementation after the test completes, typically by calling
vi.restoreAllMocks() or Date.now.mockRestore() in an afterEach or finally block
to ensure test isolation.


it('handles tokens with TTL greater than 60 seconds correctly', async () => {
const cache = SessionTokenCache;

// Mock Date.now to return a fixed timestamp initially
const initialTime = 1675876730000; // Same as our JWT's iat in milliseconds
vi.spyOn(Date, 'now').mockImplementation(() => initialTime);

// Test with a 120-second TTL
const longTtlJwt = createJwtWithTtl(120);
const longTtlToken = new Token({
object: 'token',
id: 'long-ttl',
jwt: longTtlJwt,
});

const longTtlKey = { tokenId: 'long-ttl', audience: 'test' };
const longTtlResolver = Promise.resolve(longTtlToken);
cache.set({ ...longTtlKey, tokenResolver: longTtlResolver });
await longTtlResolver;

// Check token is cached initially
const cachedEntry = cache.get(longTtlKey);
expect(cachedEntry).toMatchObject(longTtlKey);

// Advance 90 seconds - token should still be cached
const firstAdvance = 90 * 1000;
vi.advanceTimersByTime(firstAdvance);
vi.spyOn(Date, 'now').mockImplementation(() => initialTime + firstAdvance);

const cachedEntryAfter90s = cache.get(longTtlKey);
expect(cachedEntryAfter90s).toMatchObject(longTtlKey);

// Advance to 121 seconds - token should be removed
const secondAdvance = 31 * 1000;
vi.advanceTimersByTime(secondAdvance);
vi.spyOn(Date, 'now').mockImplementation(() => initialTime + firstAdvance + secondAdvance);

const cachedEntryAfter121s = cache.get(longTtlKey);
expect(cachedEntryAfter121s).toBeUndefined();
});
Comment on lines +224 to +263
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Apply the same mock cleanup pattern for consistency.

This test should follow the same Date.now mock cleanup pattern as the previous test.

  it('handles tokens with TTL greater than 60 seconds correctly', async () => {
    const cache = SessionTokenCache;

    // Mock Date.now to return a fixed timestamp initially
    const initialTime = 1675876730000; // Same as our JWT's iat in milliseconds
-   vi.spyOn(Date, 'now').mockImplementation(() => initialTime);
+   const dateNowSpy = vi.spyOn(Date, 'now').mockImplementation(() => initialTime);

    // Test with a 120-second TTL
    const longTtlJwt = createJwtWithTtl(120);
    const longTtlToken = new Token({
      object: 'token',
      id: 'long-ttl',
      jwt: longTtlJwt,
    });

    const longTtlKey = { tokenId: 'long-ttl', audience: 'test' };
    const longTtlResolver = Promise.resolve(longTtlToken);
    cache.set({ ...longTtlKey, tokenResolver: longTtlResolver });
    await longTtlResolver;

    // Check token is cached initially
    const cachedEntry = cache.get(longTtlKey);
    expect(cachedEntry).toMatchObject(longTtlKey);

    // Advance 90 seconds - token should still be cached
    const firstAdvance = 90 * 1000;
    vi.advanceTimersByTime(firstAdvance);
-   vi.spyOn(Date, 'now').mockImplementation(() => initialTime + firstAdvance);
+   dateNowSpy.mockImplementation(() => initialTime + firstAdvance);

    const cachedEntryAfter90s = cache.get(longTtlKey);
    expect(cachedEntryAfter90s).toMatchObject(longTtlKey);

    // Advance to 121 seconds - token should be removed
    const secondAdvance = 31 * 1000;
    vi.advanceTimersByTime(secondAdvance);
-   vi.spyOn(Date, 'now').mockImplementation(() => initialTime + firstAdvance + secondAdvance);
+   dateNowSpy.mockImplementation(() => initialTime + firstAdvance + secondAdvance);

    const cachedEntryAfter121s = cache.get(longTtlKey);
    expect(cachedEntryAfter121s).toBeUndefined();
+   
+   // Cleanup
+   dateNowSpy.mockRestore();
  });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it('handles tokens with TTL greater than 60 seconds correctly', async () => {
const cache = SessionTokenCache;
// Mock Date.now to return a fixed timestamp initially
const initialTime = 1675876730000; // Same as our JWT's iat in milliseconds
vi.spyOn(Date, 'now').mockImplementation(() => initialTime);
// Test with a 120-second TTL
const longTtlJwt = createJwtWithTtl(120);
const longTtlToken = new Token({
object: 'token',
id: 'long-ttl',
jwt: longTtlJwt,
});
const longTtlKey = { tokenId: 'long-ttl', audience: 'test' };
const longTtlResolver = Promise.resolve(longTtlToken);
cache.set({ ...longTtlKey, tokenResolver: longTtlResolver });
await longTtlResolver;
// Check token is cached initially
const cachedEntry = cache.get(longTtlKey);
expect(cachedEntry).toMatchObject(longTtlKey);
// Advance 90 seconds - token should still be cached
const firstAdvance = 90 * 1000;
vi.advanceTimersByTime(firstAdvance);
vi.spyOn(Date, 'now').mockImplementation(() => initialTime + firstAdvance);
const cachedEntryAfter90s = cache.get(longTtlKey);
expect(cachedEntryAfter90s).toMatchObject(longTtlKey);
// Advance to 121 seconds - token should be removed
const secondAdvance = 31 * 1000;
vi.advanceTimersByTime(secondAdvance);
vi.spyOn(Date, 'now').mockImplementation(() => initialTime + firstAdvance + secondAdvance);
const cachedEntryAfter121s = cache.get(longTtlKey);
expect(cachedEntryAfter121s).toBeUndefined();
});
it('handles tokens with TTL greater than 60 seconds correctly', async () => {
const cache = SessionTokenCache;
// Mock Date.now to return a fixed timestamp initially
const initialTime = 1675876730000; // Same as our JWT's iat in milliseconds
const dateNowSpy = vi.spyOn(Date, 'now').mockImplementation(() => initialTime);
// Test with a 120-second TTL
const longTtlJwt = createJwtWithTtl(120);
const longTtlToken = new Token({
object: 'token',
id: 'long-ttl',
jwt: longTtlJwt,
});
const longTtlKey = { tokenId: 'long-ttl', audience: 'test' };
const longTtlResolver = Promise.resolve(longTtlToken);
cache.set({ ...longTtlKey, tokenResolver: longTtlResolver });
await longTtlResolver;
// Check token is cached initially
const cachedEntry = cache.get(longTtlKey);
expect(cachedEntry).toMatchObject(longTtlKey);
// Advance 90 seconds - token should still be cached
const firstAdvance = 90 * 1000;
vi.advanceTimersByTime(firstAdvance);
dateNowSpy.mockImplementation(() => initialTime + firstAdvance);
const cachedEntryAfter90s = cache.get(longTtlKey);
expect(cachedEntryAfter90s).toMatchObject(longTtlKey);
// Advance to 121 seconds - token should be removed
const secondAdvance = 31 * 1000;
vi.advanceTimersByTime(secondAdvance);
dateNowSpy.mockImplementation(() => initialTime + firstAdvance + secondAdvance);
const cachedEntryAfter121s = cache.get(longTtlKey);
expect(cachedEntryAfter121s).toBeUndefined();
// Cleanup
dateNowSpy.mockRestore();
});
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/__tests__/tokenCache.spec.ts around lines 224 to
263, the test mocks Date.now multiple times but does not restore the original
implementation after the test. To fix this, add a cleanup step to restore the
original Date.now mock after the test completes, using vi.restoreAllMocks() or a
similar method, ensuring consistency with other tests that mock Date.now.

});
});
Loading