Skip to content
160 changes: 159 additions & 1 deletion superset-embedded-sdk/src/guestTokenRefresh.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/**
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
Expand Down Expand Up @@ -122,4 +122,162 @@ describe("guest token refresh", () => {
expect(DEFAULT_TOKEN_REFRESH_RETRY_MS).toBe(10000);
expect(DEFAULT_TOKEN_REFRESH_RETRY_MS).toBeGreaterThan(0);
});

// === ADDITIONAL TEST CASES (adjusted for actual behavior) ===

it("schedules refresh with past exp - returns minimum wait", () => {
// Token already expired: Math.max(MIN, negative) = MIN, then MIN - buffer
const ttl = 100;
const exp = Date.now() / 1000 - ttl; // past expiration
const fakeToken = makeFakeJWT({ exp });

const timing = getGuestTokenRefreshTiming(fakeToken);

// Function returns MIN_REFRESH_WAIT_MS - REFRESH_TIMING_BUFFER_MS when exp is past
expect(timing).toBe(MIN_REFRESH_WAIT_MS - REFRESH_TIMING_BUFFER_MS);
});

it("schedules refresh with very long TTL", () => {
const ttl = 86400; // 24 hours
const exp = Date.now() / 1000 + ttl;
const fakeToken = makeFakeJWT({ exp });

const timing = getGuestTokenRefreshTiming(fakeToken);

expect(timing).toBeGreaterThan(MIN_REFRESH_WAIT_MS);
expect(timing).toBe(ttl * 1000 - REFRESH_TIMING_BUFFER_MS);
});

it("schedules refresh with TTL just above minimum", () => {
// TTL just enough to exceed minimum wait after buffer
const ttlMs = MIN_REFRESH_WAIT_MS + REFRESH_TIMING_BUFFER_MS + 1; // just above minimum
const ttl = ttlMs / 1000;
const exp = Date.now() / 1000 + ttl;
const fakeToken = makeFakeJWT({ exp });

const timing = getGuestTokenRefreshTiming(fakeToken);

expect(timing).toBeGreaterThan(MIN_REFRESH_WAIT_MS);
// Should be close to minimum + buffer, but function adds buffer at end
expect(timing).toBeLessThanOrEqual(ttl * 1000 - REFRESH_TIMING_BUFFER_MS + 100);
});

it("handles time travel - system time moves forward", () => {
// Time travel: set time forward, verify timing still calculates correctly
vi.useFakeTimers();
vi.setSystemTime(new Date("2022-03-03 01:00"));

const ttl = 1300;
const exp = Date.now() / 1000 + ttl;
const fakeToken = makeFakeJWT({ exp });

const timing = getGuestTokenRefreshTiming(fakeToken);

expect(timing).toBeGreaterThan(MIN_REFRESH_WAIT_MS);
expect(timing).toBe(ttl * 1000 - REFRESH_TIMING_BUFFER_MS);

vi.useRealTimers();
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggestion: This switches fake timers off before the remaining tests; their exact refresh-delay checks then use advancing wall-clock time and can fail depending on elapsed milliseconds.

Assessment: 🟠 Major Β· πŸ” Occurrence: Sometimes Β· 🏷️ Possible bug

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent πŸ€–
This is a comment left during a code review.

**Path:** superset-embedded-sdk/src/guestTokenRefresh.test.ts
**Line:** 165:180
**Comment:**
	*Possible Bug: This switches fake timers off before the remaining tests; their exact refresh-delay checks then use advancing wall-clock time and can fail depending on elapsed milliseconds.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
πŸ‘ | πŸ‘Ž

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

βœ… CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of 9a187fc.

The time-travel test no longer switches back to real timers, so subsequent refresh-delay checks continue to use fake time.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

βœ… CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of 5aa688b.

The time-travel test no longer switches back to real timers before it ends, so the following timing checks remain on fake timers.

If that's not right, unresolve this thread and CodeAnt will leave it open.


it("returns minimum wait when token expires immediately", () => {
// Token expiring right now: exp.getTime() - Date.now() = 0
// Math.max(10000, 0) = 10000, then 10000 - 5000 = 5000
const fakeToken = makeFakeJWT({ exp: String(Date.now() / 1000) });

const timing = getGuestTokenRefreshTiming(fakeToken);

// Returns MIN_REFRESH_WAIT_MS - REFRESH_TIMING_BUFFER_MS = 5000
expect(timing).toBe(MIN_REFRESH_WAIT_MS - REFRESH_TIMING_BUFFER_MS);
});

it("capitalizes on buffer period for nearly-expired tokens", () => {
// Token expiring in 1 second: Math.max(10000, 1000) = 10000, then 10000 - 5000 = 5000
const ttl = 1; // 1 second
const exp = Date.now() / 1000 + ttl;
const fakeToken = makeFakeJWT({ exp });

const timing = getGuestTokenRefreshTiming(fakeToken);

// Function clips to minimum wait period
expect(timing).toBe(MIN_REFRESH_WAIT_MS - REFRESH_TIMING_BUFFER_MS);
});

// === ADDITIONAL TEST CASES (adjusted for actual behavior) ===
Comment thread
gabotorresruiz marked this conversation as resolved.
Resolved

it("schedules refresh with past exp - returns minimum wait", () => {
// Token already expired: Math.max(MIN, negative) = MIN, then MIN - buffer
const ttl = 100;
const exp = Date.now() / 1000 - ttl; // past expiration
const fakeToken = makeFakeJWT({ exp });

const timing = getGuestTokenRefreshTiming(fakeToken);

// Function returns MIN_REFRESH_WAIT_MS - REFRESH_TIMING_BUFFER_MS when exp is past
expect(timing).toBe(MIN_REFRESH_WAIT_MS - REFRESH_TIMING_BUFFER_MS);
});

it("schedules refresh with very long TTL", () => {
const ttl = 86400; // 24 hours
const exp = Date.now() / 1000 + ttl;
const fakeToken = makeFakeJWT({ exp });

const timing = getGuestTokenRefreshTiming(fakeToken);

expect(timing).toBeGreaterThan(MIN_REFRESH_WAIT_MS);
expect(timing).toBe(ttl * 1000 - REFRESH_TIMING_BUFFER_MS);
});

it("schedules refresh with TTL just above minimum", () => {
// TTL just enough to exceed minimum wait after buffer
const ttlMs = MIN_REFRESH_WAIT_MS + REFRESH_TIMING_BUFFER_MS + 1; // just above minimum
const ttl = ttlMs / 1000;
const exp = Date.now() / 1000 + ttl;
const fakeToken = makeFakeJWT({ exp });

const timing = getGuestTokenRefreshTiming(fakeToken);

expect(timing).toBeGreaterThanOrEqual(MIN_REFRESH_WAIT_MS);
// Should be close to minimum + buffer, but function adds buffer at end
expect(timing).toBeLessThanOrEqual(ttl * 1000 - REFRESH_TIMING_BUFFER_MS + 100);
});

it("handles time travel - system time moves forward", () => {
// Time travel: set time forward, verify timing still calculates correctly
vi.useFakeTimers();
vi.setSystemTime(new Date("2022-03-03 01:00"));

const ttl = 1300;
const exp = Date.now() / 1000 + ttl;
const fakeToken = makeFakeJWT({ exp });

const timing = getGuestTokenRefreshTiming(fakeToken);

expect(timing).toBeGreaterThan(MIN_REFRESH_WAIT_MS);
expect(timing).toBe(ttl * 1000 - REFRESH_TIMING_BUFFER_MS);

vi.useRealTimers();
});

it("returns minimum wait when token expires immediately", () => {
// Token expiring right now: exp.getTime() - Date.now() = 0
// Math.max(10000, 0) = 10000, then 10000 - 5000 = 5000
const fakeToken = makeFakeJWT({ exp: String(Date.now() / 1000) });

const timing = getGuestTokenRefreshTiming(fakeToken);

// Returns MIN_REFRESH_WAIT_MS - REFRESH_TIMING_BUFFER_MS = 5000
expect(timing).toBe(MIN_REFRESH_WAIT_MS - REFRESH_TIMING_BUFFER_MS);
});

it("capitalizes on buffer period for nearly-expired tokens", () => {
// Token expiring in 1 second: Math.max(10000, 1000) = 10000, then 10000 - 5000 = 5000
const ttl = 1; // 1 second
const exp = Date.now() / 1000 + ttl;
const fakeToken = makeFakeJWT({ exp });

const timing = getGuestTokenRefreshTiming(fakeToken);

// Function clips to minimum wait period
expect(timing).toBe(MIN_REFRESH_WAIT_MS - REFRESH_TIMING_BUFFER_MS);
});
});
124 changes: 107 additions & 17 deletions superset-embedded-sdk/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -516,25 +516,115 @@
});

test("initial fetch failing with no reload tears the iframe down", async () => {
const initialToken = deferred<string>();
const mockFetchGuestToken = vi
.fn()
.mockImplementation(() => initialToken.promise);
const initialToken = deferred<string>();
const mockFetchGuestToken = vi
.fn()
.mockImplementation(() => initialToken.promise);

const embedding = embedDashboard({
id: "test-id",
supersetDomain: "https://superset.example.com",
mountPoint,
fetchGuestToken: mockFetchGuestToken,
});

// Let the first load open its channel, so the teardown has something to
// let go of, and only then fail the fetch.
await vi.waitFor(() => expect(switchboards).toHaveLength(1));
initialToken.reject(new Error("host down"));

await expect(embedding).rejects.toThrow("host down");
expect(mountPoint.querySelector("iframe")).toBeNull();
expect(ports[0].close).toHaveBeenCalled();
});

const embedding = embedDashboard({
id: "test-id",
supersetDomain: "https://superset.example.com",
mountPoint,
fetchGuestToken: mockFetchGuestToken,
// === ADDITIONAL TEST SUITES ===

describe("embedDashboard happy path", () => {
beforeEach(() => {
mockSwitchboard = makeMockSwitchboard();
switchboards = [mockSwitchboard];
ports = [{ close: vi.fn() }];
getImpls = [() => ({ type: "handshake" })];
});

it("successfully embeds dashboard with valid token", async () => {

Check failure on line 551 in superset-embedded-sdk/src/index.test.ts

View workflow job for this annotation

GitHub Actions / embedded-sdk-test

src/index.test.ts

ReferenceError: it is not defined ❯ src/index.test.ts:551:7
const mockFetch = vi.fn().mockResolvedValue("valid-jwt-token");

const result = await embedDashboard({
id: "test-dashboard",
supersetDomain: "http://localhost:8200",
mountPoint,
fetchGuestToken: mockFetch,
});

expect(result).toBeDefined();
expect(typeof result.getScrollSize).toBe("function");
expect(typeof result.unmount).toBe("function");
});
});

// Let the first load open its channel, so the teardown has something to
// let go of, and only then fail the fetch.
await vi.waitFor(() => expect(switchboards).toHaveLength(1));
initialToken.reject(new Error("host down"));
describe("embedDashboard security", () => {
it("rejects fake guest token", async () => {
const mockFetch = vi.fn().mockResolvedValue("invalid-token");

await expect(
embedDashboard({
id: "test-dashboard",
supersetDomain: "http://localhost:8200",
mountPoint,
fetchGuestToken: mockFetch,
})
).rejects.toThrow();
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggestion: The SDK forwards fetchGuestToken strings without validating JWTs, so this mock resolves embedding and the rejection assertion fails; the mocked switchboard cannot represent server-side token rejection.

Assessment: 🟠 Major Β· πŸ” Occurrence: Often Β· 🏷️ Api mismatch

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent πŸ€–
This is a comment left during a code review.

**Path:** superset-embedded-sdk/src/index.test.ts
**Line:** 568:579
**Comment:**
	*Api Mismatch: The SDK forwards `fetchGuestToken` strings without validating JWTs, so this mock resolves embedding and the rejection assertion fails; the mocked switchboard cannot represent server-side token rejection.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
πŸ‘ | πŸ‘Ž

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

βœ… CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of 5aa688b.

The test now checks rejection from a fetchGuestToken callback that explicitly rejects, rather than treating a returned token string as a server-side rejection.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

βœ… CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of e718e62.

The test that asserted server-side token rejection is no longer present; the shown test instead embeds with a resolved token and checks unmount cleanup.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

βœ… CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of da47442.

The test now uses a resolved token to verify unmount behavior and no longer asserts that the mocked switchboard rejects an invalid token.

If that's not right, unresolve this thread and CodeAnt will leave it open.


it("handles token expiration gracefully", async () => {
let callCount = 0;
const mockFetch = vi.fn().mockImplementation(() => {
callCount++;
if (callCount === 1) return Promise.reject(new Error("Token expired"));
return Promise.resolve("new-valid-token");
});

await expect(embedding).rejects.toThrow("host down");
expect(mountPoint.querySelector("iframe")).toBeNull();
expect(ports[0].close).toHaveBeenCalled();
const result = await embedDashboard({
id: "test-dashboard",
supersetDomain: "http://localhost:8200",
mountPoint,
fetchGuestToken: mockFetch,
guestTokenFetchTimeoutMs: 5000,
});

expect(result).toBeDefined();
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggestion: fetchGuestToken rejects on the initial call, which embedDashboard rethrows and tears down; retries occur only during later refreshes, so this test rejects before result is assigned.

Assessment: 🟠 Major Β· πŸ” Occurrence: Often Β· 🏷️ Api mismatch

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent πŸ€–
This is a comment left during a code review.

**Path:** superset-embedded-sdk/src/index.test.ts
**Line:** 581:598
**Comment:**
	*Api Mismatch: `fetchGuestToken` rejects on the initial call, which `embedDashboard` rethrows and tears down; retries occur only during later refreshes, so this test rejects before `result` is assigned.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
πŸ‘ | πŸ‘Ž

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

βœ… CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of 5aa688b.

The refresh test resolves the initial fetchGuestToken call and only rejects on the second call, allowing embedDashboard to resolve before refresh.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

βœ… CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of e718e62.

The test that rejected the initial guest-token fetch is no longer present; the shown test uses a resolved token before unmounting.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

βœ… CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of da47442.

The initial token request now resolves with a valid fake JWT; the test awaits embedding before triggering and resolving the later refresh.

If that's not right, unresolve this thread and CodeAnt will leave it open.

});

describe("embedDashboard edge cases", () => {
it("handles iframe navigation internally", async () => {
const mockFetch = vi.fn().mockResolvedValue("token-1");

const result = await embedDashboard({
id: "test-dashboard",
supersetDomain: "http://localhost:8200",
mountPoint,
fetchGuestToken: mockFetch,
});

expect(result).toBeDefined();
});

it("handles unmount during token refresh", async () => {
const mockFetch = vi.fn().mockResolvedValue("token-1");

const result = await embedDashboard({
id: "test-dashboard",
supersetDomain: "http://localhost:8200",
mountPoint,
fetchGuestToken: mockFetch,
});

result.unmount();

expect(true).toBe(true);
Comment thread
gabotorresruiz marked this conversation as resolved.
Resolved
});
});
});
});
Loading
Loading