-
Notifications
You must be signed in to change notification settings - Fork 10.5k
fix(SignalR): retry access token refresh on 401 in TS client #63740
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
Closed
Closed
Changes from 1 commit
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
873a113
fix(SignalR): ensure 401 triggers access token refresh retry in TS cl…
daniloneto 857315c
Update src/SignalR/clients/ts/signalr/src/AccessTokenHttpClient.ts
daniloneto f88b82c
Update src/SignalR/clients/ts/signalr/tests/AccessTokenHttpClient.tes…
daniloneto 0b490cf
Update src/SignalR/clients/ts/signalr/src/AccessTokenHttpClient.ts
daniloneto 372a70a
Update src/SignalR/clients/ts/signalr/tests/AccessTokenHttpClient.tes…
daniloneto 75ca574
fix(SignalR/TS): 401 retry + no-token path cleans Authorization and r…
daniloneto 665288d
Merge branch 'dotnet:main' into fix-signalr-401-retry
daniloneto File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or 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
248 changes: 248 additions & 0 deletions
248
src/SignalR/clients/ts/signalr/tests/AccessTokenHttpClient.test.ts
This file contains hidden or 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,248 @@ | ||||||
// Licensed to the .NET Foundation under one or more agreements. | ||||||
// The .NET Foundation licenses this file to you under the MIT license. | ||||||
|
||||||
import { AccessTokenHttpClient } from "../src/AccessTokenHttpClient"; | ||||||
import { HttpError } from "../src/Errors"; | ||||||
import { HttpRequest, HttpResponse } from "../src/HttpClient"; | ||||||
import { TestHttpClient } from "./TestHttpClient"; | ||||||
import { registerUnhandledRejectionHandler } from "./Utils"; | ||||||
import { VerifyLogger } from "./Common"; | ||||||
import { LongPollingTransport } from "../src/LongPollingTransport"; | ||||||
import { TransferFormat } from "../src/ITransport"; | ||||||
|
||||||
describe("AccessTokenHttpClient", () => { | ||||||
beforeAll(() => { | ||||||
registerUnhandledRejectionHandler(); | ||||||
}); | ||||||
|
||||||
afterAll(() => { | ||||||
// Optional cleanup could go here. | ||||||
}); | ||||||
|
||||||
it("retries exactly once on 401 HttpError when accessTokenFactory provided", async () => { | ||||||
let call = 0; | ||||||
let primed = false; | ||||||
const inner = new TestHttpClient(); | ||||||
inner.on(() => { | ||||||
if (!primed) { | ||||||
primed = true; // prime request returns 200 and sets initial token | ||||||
return new HttpResponse(200, "OK", "prime"); | ||||||
} | ||||||
call++; | ||||||
if (call === 1) { | ||||||
throw new HttpError("Unauthorized", 401); | ||||||
} | ||||||
return new HttpResponse(200, "OK", "done"); | ||||||
}); | ||||||
|
||||||
let factoryCalls = 0; | ||||||
const client = new AccessTokenHttpClient(inner, () => { | ||||||
factoryCalls++; | ||||||
return `token${factoryCalls}`; | ||||||
}); | ||||||
|
||||||
// Prime token via public API | ||||||
await client.get("http://example.com/prime"); | ||||||
|
||||||
const response = await client.get("http://example.com/resource"); | ||||||
expect(response.statusCode).toBe(200); | ||||||
expect(factoryCalls).toBe(2); // prime + retry refresh | ||||||
expect(call).toBe(2); // failing attempt + successful retry | ||||||
}); | ||||||
|
||||||
[403, 500].forEach(status => { | ||||||
it(`does not retry on status ${status} HttpError`, async () => { | ||||||
let primed = false; | ||||||
let failingCalls = 0; | ||||||
const inner = new TestHttpClient(); | ||||||
inner.on(() => { | ||||||
if (!primed) { | ||||||
primed = true; | ||||||
return new HttpResponse(200, "OK", "prime"); | ||||||
} | ||||||
failingCalls++; | ||||||
throw new HttpError("Error", status); | ||||||
}); | ||||||
|
||||||
let factoryCalls = 0; | ||||||
const client = new AccessTokenHttpClient(inner, () => { | ||||||
factoryCalls++; | ||||||
return `token${factoryCalls}`; | ||||||
}); | ||||||
|
||||||
await client.get("http://example.com/prime"); | ||||||
try { | ||||||
await client.get("http://example.com/resource"); | ||||||
fail("expected to throw"); | ||||||
daniloneto marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||||||
} catch (e: any) { | ||||||
expect(e).toBeInstanceOf(HttpError); | ||||||
expect(e.statusCode ?? e.status).toBe(status); | ||||||
} | ||||||
expect(factoryCalls).toBe(1); | ||||||
expect(failingCalls).toBe(1); | ||||||
}); | ||||||
}); | ||||||
|
||||||
it("LongPollingTransport continues running after 401 during poll and refreshes token", async () => { | ||||||
await VerifyLogger.run(async (logger) => { | ||||||
let pollIteration = 0; | ||||||
let primed = false; | ||||||
const tokens: string[] = []; | ||||||
const accessTokenFactory = () => { | ||||||
const t = `tok${tokens.length + 1}`; | ||||||
tokens.push(t); | ||||||
return t; | ||||||
}; | ||||||
const httpClient = new AccessTokenHttpClient(new TestHttpClient() | ||||||
.on("GET", (r: HttpRequest) => { | ||||||
// Prime request separate from polling loop | ||||||
if (!primed && r.url!.includes("/prime")) { | ||||||
primed = true; | ||||||
return new HttpResponse(200, "OK", "prime"); | ||||||
} | ||||||
pollIteration++; | ||||||
if (pollIteration === 1) { // initial connect poll | ||||||
return new HttpResponse(200, "OK", ""); | ||||||
} | ||||||
if (pollIteration === 2) { // trigger 401 -> retry | ||||||
return new HttpResponse(401); | ||||||
} | ||||||
if (pollIteration === 3) { // post-refresh poll | ||||||
expect(r.headers).toBeDefined(); | ||||||
expect(r.headers?.Authorization).toBeDefined(); | ||||||
expect(r.headers?.Authorization).toContain(tokens[tokens.length - 1]); | ||||||
return new HttpResponse(204); | ||||||
} | ||||||
return new HttpResponse(204); | ||||||
}), accessTokenFactory); | ||||||
|
||||||
// Prime token using public API | ||||||
await httpClient.get("http://example.com/prime"); | ||||||
|
||||||
const transport = new LongPollingTransport(httpClient, logger, { withCredentials: true, headers: {}, logMessageContent: false }); | ||||||
await transport.connect("http://example.com?connectionId=abc", TransferFormat.Text); | ||||||
await transport.stop(); | ||||||
|
||||||
expect(tokens.length).toBe(2); // primed + refreshed | ||||||
expect(pollIteration).toBeGreaterThanOrEqual(3); | ||||||
}); | ||||||
}); | ||||||
|
||||||
it("retries once on 401 HttpResponse status (non-throwing path)", async () => { | ||||||
let primed = false; | ||||||
let attempts = 0; | ||||||
let retryAuthHeader: string | undefined; | ||||||
const inner = new TestHttpClient(); | ||||||
inner.on((r: HttpRequest) => { | ||||||
if (!primed && r.url!.includes("/prime")) { | ||||||
primed = true; | ||||||
return new HttpResponse(200, "OK", "prime"); | ||||||
} | ||||||
attempts++; | ||||||
if (attempts === 1) { | ||||||
return new HttpResponse(401); | ||||||
} | ||||||
// second attempt after refresh | ||||||
retryAuthHeader = r.headers?.Authorization; | ||||||
return new HttpResponse(200, "OK", "after-retry"); | ||||||
}); | ||||||
|
||||||
let factoryCalls = 0; | ||||||
const client = new AccessTokenHttpClient(inner, () => { | ||||||
factoryCalls++; | ||||||
return `token${factoryCalls}`; | ||||||
}); | ||||||
|
||||||
await client.get("http://example.com/prime"); | ||||||
const resp = await client.get("http://example.com/resource"); | ||||||
expect(resp.statusCode).toBe(200); | ||||||
expect(factoryCalls).toBe(2); // prime + refresh | ||||||
expect(attempts).toBe(2); // original 401 + retry 200 | ||||||
expect(retryAuthHeader).toContain("token2"); | ||||||
}); | ||||||
|
||||||
it("does not retry when allowRetry is false (initial token acquisition)", async () => { | ||||||
let sends = 0; | ||||||
const inner = new TestHttpClient(); | ||||||
inner.on(() => { | ||||||
sends++; | ||||||
return new HttpResponse(401); | ||||||
}); | ||||||
|
||||||
let factoryCalls = 0; | ||||||
const client = new AccessTokenHttpClient(inner, () => { | ||||||
factoryCalls++; | ||||||
return `token${factoryCalls}`; // Explicitly call send with allowRetry=false to ensure no retry is attempted. | ||||||
daniloneto marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||||||
}); | ||||||
|
||||||
const request: HttpRequest = { method: "GET", url: "http://example.com/resource" }; | ||||||
const resp = await client.send(request); // send path with existing logic; allowRetry=false triggered by initial token acquisition above | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The comment mentions 'allowRetry=false triggered by initial token acquisition above' but there's no token acquisition visible in this test method above this line. The comment appears to be inaccurate or misleading.
Suggested change
Copilot uses AI. Check for mistakes. Positive FeedbackNegative Feedback |
||||||
expect(resp.statusCode).toBe(401); | ||||||
expect(factoryCalls).toBe(1); | ||||||
expect(sends).toBe(1); | ||||||
}); | ||||||
|
||||||
it("does not retry when refreshed token is empty", async () => { | ||||||
let primed = false; | ||||||
let attempts = 0; | ||||||
const inner = new TestHttpClient(); | ||||||
inner.on((r: HttpRequest) => { | ||||||
if (!primed && r.url!.includes("/prime")) { | ||||||
primed = true; | ||||||
return new HttpResponse(200, "OK", "prime"); | ||||||
} | ||||||
attempts++; | ||||||
return new HttpResponse(401); // cause retry path | ||||||
}); | ||||||
|
||||||
let factoryCalls = 0; | ||||||
const client = new AccessTokenHttpClient(inner, () => { | ||||||
factoryCalls++; | ||||||
if (factoryCalls === 1) { | ||||||
return "tok1"; // prime | ||||||
} | ||||||
return ""; // refresh returns empty -> should not retry send again | ||||||
}); | ||||||
|
||||||
await client.get("http://example.com/prime"); | ||||||
const resp = await client.get("http://example.com/resource"); | ||||||
expect(resp.statusCode).toBe(401); // original response returned | ||||||
expect(factoryCalls).toBe(2); // prime + attempted refresh | ||||||
expect(attempts).toBe(1); // no second send | ||||||
}); | ||||||
|
||||||
it("retries once when HttpError.status is string '401'", async () => { | ||||||
let primed = false; | ||||||
let attempt = 0; | ||||||
let retryAuth: string | undefined; | ||||||
const inner = new TestHttpClient(); | ||||||
inner.on((r: HttpRequest) => { | ||||||
if (!primed && r.url!.includes("/prime")) { | ||||||
primed = true; | ||||||
return new HttpResponse(200, "OK", "prime"); | ||||||
} | ||||||
attempt++; | ||||||
if (attempt === 1) { | ||||||
const err: any = new Error("Unauthorized: Status code '401'"); | ||||||
err.name = "HttpError"; // mimic HttpError shape without statusCode | ||||||
err.status = "401"; // string status to trigger normalization path | ||||||
throw err; | ||||||
} | ||||||
retryAuth = r.headers?.Authorization; | ||||||
return new HttpResponse(200, "OK", "ok"); | ||||||
}); | ||||||
|
||||||
let factoryCalls = 0; | ||||||
const client = new AccessTokenHttpClient(inner, () => { | ||||||
factoryCalls++; | ||||||
return `token${factoryCalls}`; | ||||||
}); | ||||||
|
||||||
await client.get("http://example.com/prime"); | ||||||
const resp = await client.get("http://example.com/resource"); | ||||||
expect(resp.statusCode).toBe(200); | ||||||
expect(factoryCalls).toBe(2); // prime + refresh after string status retry | ||||||
expect(attempt).toBe(2); // original throw + retry | ||||||
expect(retryAuth).toContain("token2"); | ||||||
}); | ||||||
}); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.