Skip to content

Commit 229f48c

Browse files
committed
fix(sdk): TypeScript refuses an answer its fetch reached by redirect, and cancels bodies it stops reading
1 parent 043b145 commit 229f48c

3 files changed

Lines changed: 83 additions & 19 deletions

File tree

‎docs/architecture/sdk.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,9 +63,9 @@ resend a code or token elsewhere, and a request that takes over 10 seconds, from
6363
connecting to its last body byte, fails. The Rust SDK sets this policy on the
6464
client it builds. The TypeScript SDK checks the URL itself, asks `fetch` not to
6565
follow redirects and refuses any it gets, and holds its own deadline, which does
66-
not wait on `fetch` to honour its abort signal. Only an injected `fetch` that
67-
follows redirects despite `redirect: 'manual'` can resend a request before the SDK
68-
refuses it.
66+
not wait on `fetch` to honour its abort signal and cancels a body it stops reading.
67+
Only an injected `fetch` that follows redirects despite `redirect: 'manual'` can
68+
resend a request; the SDK still refuses the answer it reached.
6969

7070
## Token validation
7171

‎packages/auth/src/http.ts‎

Lines changed: 38 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -97,23 +97,33 @@ export class Http {
9797
});
9898
}
9999

100-
/** @internal Reads `body` whole, or `undefined` once it holds more than `limit` bytes. */
100+
/**
101+
* @internal Reads `body` whole, or `undefined` once it holds more than `limit` bytes.
102+
* `signal` aborting cancels the body, so a stalled one is released.
103+
*/
101104
static async readBody(
102105
body: ReadableStream<Uint8Array> | null,
103-
limit: number
106+
limit: number,
107+
signal?: AbortSignal
104108
): Promise<Uint8Array | undefined> {
105109
const chunks: Uint8Array[] = [];
106110
let length = 0;
107111
const reader = body?.getReader();
108-
for (;;) {
109-
const chunk = await reader?.read();
110-
if (chunk === undefined || chunk.done) break;
111-
length += chunk.value.length;
112-
if (length > limit) {
113-
await reader?.cancel();
114-
return undefined;
112+
const cancel = () => void reader?.cancel().catch(() => undefined);
113+
signal?.addEventListener('abort', cancel, { once: true });
114+
try {
115+
for (;;) {
116+
const chunk = await reader?.read();
117+
if (chunk === undefined || chunk.done) break;
118+
length += chunk.value.length;
119+
if (length > limit) {
120+
await reader?.cancel();
121+
return undefined;
122+
}
123+
chunks.push(chunk.value);
115124
}
116-
chunks.push(chunk.value);
125+
} finally {
126+
signal?.removeEventListener('abort', cancel);
117127
}
118128
const whole = new Uint8Array(length);
119129
let offset = 0;
@@ -165,16 +175,30 @@ export class Http {
165175
} catch (error) {
166176
throw failed(error);
167177
}
168-
// A browser's `fetch` hides a manual redirect behind an opaque response.
169-
if (response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400)) {
178+
// A response that comes after the deadline, or that redirected, is not read: its
179+
// body is cancelled so the connection is released.
180+
const discard = () => void response.body?.cancel().catch(() => undefined);
181+
if (signal.aborted) {
182+
discard();
183+
throw failed(signal.reason);
184+
}
185+
// A browser's `fetch` hides a manual redirect behind an opaque response, and one
186+
// that ignored `redirect: 'manual'` marks the response it followed to.
187+
const status = response.status;
188+
if (
189+
response.redirected ||
190+
response.type === 'opaqueredirect' ||
191+
(status >= 300 && status < 400)
192+
) {
193+
discard();
170194
throw new AuthError(
171195
{ code: 'network', url },
172-
`${url} redirected with HTTP ${String(response.status)}`
196+
`${url} redirected with HTTP ${String(status)}`
173197
);
174198
}
175199
let body: Uint8Array | undefined;
176200
try {
177-
body = await Http.readBody(response.body, MAX_BODY_BYTES);
201+
body = await Http.readBody(response.body, MAX_BODY_BYTES, signal);
178202
} catch (error) {
179203
throw failed(error);
180204
}

‎packages/auth/test/http.test.ts‎

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,16 +22,56 @@ test('a server that never answers times out, though the fetch ignores its signal
2222
}
2323
});
2424

25-
test('a redirect is refused, and never asked to be followed', async () => {
25+
/** A body that never sends a byte, and records whether it was cancelled. */
26+
class StalledBody {
27+
cancelled = false;
28+
readonly stream = new ReadableStream<Uint8Array>({
29+
cancel: () => {
30+
this.cancelled = true;
31+
}
32+
});
33+
}
34+
35+
test('a body that stalls times out, and is cancelled', async () => {
36+
mock.timers.enable({ apis: ['setTimeout'] });
37+
try {
38+
const body = new StalledBody();
39+
const http = new Http(() => Promise.resolve(new Response(body.stream)));
40+
const sent = http.get(TOKEN_URL);
41+
// Let the response arrive and its body start being read.
42+
await new Promise((resolve) => setImmediate(resolve));
43+
mock.timers.tick(10_000);
44+
await assert.rejects(sent, network);
45+
assert.equal(body.cancelled, true);
46+
} finally {
47+
mock.timers.reset();
48+
}
49+
});
50+
51+
test('a redirect is refused and its body cancelled, and it is never asked to be followed', async () => {
2652
let redirect: RequestRedirect | undefined;
53+
const body = new StalledBody();
2754
const http = new Http((_, init) => {
2855
redirect = init.redirect;
2956
return Promise.resolve(
30-
new Response(null, { status: 307, headers: { location: 'https://elsewhere.example' } })
57+
new Response(body.stream, {
58+
status: 307,
59+
headers: { location: 'https://elsewhere.example' }
60+
})
3161
);
3262
});
3363
await assert.rejects(http.post(TOKEN_URL, { refresh_token: 'prt_v1_secret' }), network);
3464
assert.equal(redirect, 'manual');
65+
assert.equal(body.cancelled, true);
66+
});
67+
68+
test('a response a fetch reached by following a redirect is refused', async () => {
69+
const http = new Http(() => {
70+
const followed = Response.json({ access_token: 'stolen' });
71+
Object.defineProperty(followed, 'redirected', { value: true });
72+
return Promise.resolve(followed);
73+
});
74+
await assert.rejects(http.get(TOKEN_URL), network);
3575
});
3676

3777
test('only https URLs are requested', async () => {

0 commit comments

Comments
 (0)