Skip to content

Commit 83f102d

Browse files
committed
fix(connect): preserve OAuth rejection codes through body failures
1 parent f398fa6 commit 83f102d

2 files changed

Lines changed: 208 additions & 38 deletions

File tree

‎apps/server/src/cloud/CliTokenManager.test.ts‎

Lines changed: 121 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import * as Schema from "effect/Schema";
1414
import * as Terminal from "effect/Terminal";
1515
import * as TestClock from "effect/testing/TestClock";
1616
import * as HttpClient from "effect/http/HttpClient";
17+
import * as HttpClientError from "effect/http/HttpClientError";
1718
import * as HttpClientResponse from "effect/http/HttpClientResponse";
1819

1920
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
@@ -178,23 +179,24 @@ const layerDeviceFlow = (server: DeviceFlowServer) =>
178179
const tokenRequests = (requests: ReadonlyArray<RecordedTokenRequest>) =>
179180
requests.filter((request) => request.url.endsWith("/oauth/token"));
180181

181-
// The endpoint sends 200 headers, then the JSON body never finishes.
182-
const layerStalledBody = Layer.succeed(
183-
HttpClient.HttpClient,
184-
HttpClient.make((request) =>
185-
Effect.succeed(
186-
HttpClientResponse.fromWeb(
187-
request,
188-
new Response(
189-
new ReadableStream({
190-
start: (controller) => controller.enqueue(new TextEncoder().encode("{")),
191-
}),
192-
{ status: 200, headers: { "content-type": "application/json" } },
182+
// The endpoint sends headers, then the JSON body never finishes.
183+
const layerStalledBody = (status: number) =>
184+
Layer.succeed(
185+
HttpClient.HttpClient,
186+
HttpClient.make((request) =>
187+
Effect.succeed(
188+
HttpClientResponse.fromWeb(
189+
request,
190+
new Response(
191+
new ReadableStream({
192+
start: (controller) => controller.enqueue(new TextEncoder().encode("{")),
193+
}),
194+
{ status, headers: { "content-type": "application/json" } },
195+
),
193196
),
194197
),
195198
),
196-
),
197-
);
199+
);
198200

199201
const expiredStoredToken = new TextEncoder().encode(
200202
JSON.stringify({ accessToken: "expired", refreshToken: "refresh-token-1", expiresAtEpochMs: 0 }),
@@ -216,6 +218,24 @@ const layerRefreshResponse = (reply: { readonly status: number; readonly body: s
216218
),
217219
);
218220

221+
const layerUnreadableResponseBody = (status: number) =>
222+
Layer.succeed(
223+
HttpClient.HttpClient,
224+
HttpClient.make((request) =>
225+
Effect.succeed(
226+
HttpClientResponse.fromWeb(
227+
request,
228+
new Response(
229+
new ReadableStream({
230+
start: (controller) => controller.error(new Error("body read failed")),
231+
}),
232+
{ status, headers: { "content-type": "application/json" } },
233+
),
234+
),
235+
),
236+
),
237+
);
238+
219239
it.effect("persists a rotated refresh token before parent interruption is delivered", () =>
220240
Effect.gen(function* () {
221241
const requestStarted = yield* Deferred.make<void>();
@@ -308,6 +328,7 @@ it.effect.each([
308328
assert.instanceOf(error, CliTokenManager.CloudCliCredentialRefreshError);
309329
assert.equal(error.requiresLogin, requiresLogin);
310330
assert.equal(error.message.includes("t3 connect login"), requiresLogin);
331+
assert.equal(error.message.includes("OAuth error: invalid_grant"), requiresLogin);
311332
assert.notInclude(error.message, "private-oauth-diagnostic");
312333
}).pipe(
313334
Effect.provide(
@@ -334,22 +355,66 @@ it.effect.each([
334355
),
335356
);
336357

337-
it.effect("a stalled token refresh fails and releases the credential lock", () =>
358+
it.effect("only includes an allowlisted OAuth error code in a login prompt", () =>
338359
Effect.gen(function* () {
339360
const manager = yield* CliTokenManager.CloudCliTokenManager;
340-
const refresh = yield* manager.getExisting.pipe(Effect.flip, Effect.forkChild);
341-
const hasCredential = yield* manager.hasCredential.pipe(Effect.forkChild);
361+
const error = yield* manager.getExisting.pipe(Effect.flip);
362+
363+
assert.instanceOf(error, CliTokenManager.CloudCliCredentialRefreshError);
364+
assert.isTrue(error.requiresLogin);
365+
assert.include(error.message, "t3 connect login");
366+
assert.notInclude(error.message, "provider_secret");
367+
assert.notInclude(error.message, "private-oauth-diagnostic");
368+
assert.notInclude(error.message, "OAuth error:");
369+
}).pipe(
370+
Effect.provide(
371+
CliTokenManager.layer.pipe(
372+
Layer.provide(
373+
Layer.mergeAll(
374+
layerRefreshResponse({
375+
status: 400,
376+
body: JSON.stringify({
377+
error: "provider_secret",
378+
error_description: "private-oauth-diagnostic",
379+
}),
380+
}),
381+
Layer.mock(ServerSecretStore.ServerSecretStore)({
382+
get: () => Effect.succeedSome(expiredStoredToken),
383+
}),
384+
Layer.mock(ExternalLauncher.ExternalLauncher)({}),
385+
NodeServices.layer,
386+
),
387+
),
388+
),
389+
),
390+
provideTestEnv,
391+
),
392+
);
342393

343-
yield* TestClock.adjust(Duration.seconds(10));
394+
it.effect.each([
395+
{ name: "malformed", layer: layerRefreshResponse({ status: 400, body: "{" }) },
396+
{ name: "unreadable", layer: layerUnreadableResponseBody(400) },
397+
])("keeps the permanent status for a $name refresh error body", ({ layer }) =>
398+
Effect.gen(function* () {
399+
const manager = yield* CliTokenManager.CloudCliTokenManager;
400+
const error = yield* manager.getExisting.pipe(Effect.flip);
344401

345-
assert.instanceOf(yield* Fiber.join(refresh), CliTokenManager.CloudCliCredentialRefreshError);
346-
assert.isTrue(yield* Fiber.join(hasCredential));
402+
assert.instanceOf(error, CliTokenManager.CloudCliCredentialRefreshError);
403+
assert.isTrue(error.requiresLogin);
404+
assert.include(error.message, "t3 connect login");
405+
assert.isTrue(HttpClientError.isHttpClientError(error.cause));
406+
if (HttpClientError.isHttpClientError(error.cause)) {
407+
assert.equal(error.cause.reason._tag, "StatusCodeError");
408+
if (error.cause.reason._tag === "StatusCodeError") {
409+
assert.equal(error.cause.reason.response.status, 400);
410+
}
411+
}
347412
}).pipe(
348413
Effect.provide(
349414
CliTokenManager.layer.pipe(
350415
Layer.provide(
351416
Layer.mergeAll(
352-
layerStalledBody,
417+
layer,
353418
Layer.mock(ServerSecretStore.ServerSecretStore)({
354419
get: () => Effect.succeedSome(expiredStoredToken),
355420
}),
@@ -363,6 +428,40 @@ it.effect("a stalled token refresh fails and releases the credential lock", () =
363428
),
364429
);
365430

431+
it.effect.each([200, 400])(
432+
"a stalled $status token refresh fails and releases the credential lock",
433+
(status) =>
434+
Effect.gen(function* () {
435+
const manager = yield* CliTokenManager.CloudCliTokenManager;
436+
const refresh = yield* manager.getExisting.pipe(Effect.flip, Effect.forkChild);
437+
const hasCredential = yield* manager.hasCredential.pipe(Effect.forkChild);
438+
439+
yield* TestClock.adjust(Duration.seconds(10));
440+
441+
const error = yield* Fiber.join(refresh);
442+
assert.instanceOf(error, CliTokenManager.CloudCliCredentialRefreshError);
443+
assert.equal(error.requiresLogin, status === 400);
444+
assert.equal(error.message.includes("t3 connect login"), status === 400);
445+
assert.isTrue(yield* Fiber.join(hasCredential));
446+
}).pipe(
447+
Effect.provide(
448+
CliTokenManager.layer.pipe(
449+
Layer.provide(
450+
Layer.mergeAll(
451+
layerStalledBody(status),
452+
Layer.mock(ServerSecretStore.ServerSecretStore)({
453+
get: () => Effect.succeedSome(expiredStoredToken),
454+
}),
455+
Layer.mock(ExternalLauncher.ExternalLauncher)({}),
456+
NodeServices.layer,
457+
),
458+
),
459+
),
460+
),
461+
provideTestEnv,
462+
),
463+
);
464+
366465
it.layer(NodeServices.layer)("CliTokenManager.deviceAuthorizationLogin", (it) => {
367466
it.effect("requests a device code, shows it, and polls until Clerk grants the token", () =>
368467
Effect.gen(function* () {
@@ -525,7 +624,7 @@ it.layer(NodeServices.layer)("CliTokenManager.deviceAuthorizationLogin", (it) =>
525624
it.effect("fails instead of hanging when the device authorization response stalls", () =>
526625
Effect.gen(function* () {
527626
const fiber = yield* CliTokenManager.deviceAuthorizationLogin(() => Effect.void).pipe(
528-
Effect.provide(layerStalledBody),
627+
Effect.provide(layerStalledBody(200)),
529628
provideTestEnv,
530629
Effect.flip,
531630
Effect.forkChild,

‎apps/server/src/cloud/CliTokenManager.ts‎

Lines changed: 87 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,29 @@ const OAuthErrorResponse = Schema.Struct({
146146
error: Schema.String,
147147
error_description: Schema.optional(Schema.String),
148148
});
149+
const OAuthRefreshErrorCode = Schema.Literals([
150+
"invalid_grant",
151+
"invalid_client",
152+
"unauthorized_client",
153+
"unsupported_grant_type",
154+
"invalid_request",
155+
"invalid_scope",
156+
"access_denied",
157+
]);
158+
type OAuthRefreshErrorCode = typeof OAuthRefreshErrorCode.Type;
159+
const isOAuthRefreshErrorCode = Schema.is(OAuthRefreshErrorCode);
160+
const OAuthRefreshErrorResponse = Schema.Struct({
161+
error: OAuthRefreshErrorCode,
162+
error_description: Schema.optional(Schema.String),
163+
});
164+
const decodeOAuthRefreshErrorResponse = Schema.decodeUnknownOption(
165+
Schema.fromJsonString(OAuthRefreshErrorResponse),
166+
);
167+
168+
function sanitizedOAuthErrorCode(body: string): OAuthRefreshErrorCode | undefined {
169+
const decoded = decodeOAuthRefreshErrorResponse(body);
170+
return Option.isSome(decoded) ? decoded.value.error : undefined;
171+
}
149172

150173
const DeviceAuthorizationResponse = Schema.Struct({
151174
device_code: Schema.String,
@@ -200,11 +223,14 @@ export class CloudCliCredentialRefreshError extends Schema.TaggedError<CloudCliC
200223
requiresLogin: Schema.optional(Schema.Boolean).pipe(
201224
Schema.withConstructorDefault(Effect.succeed(false)),
202225
),
226+
oauthErrorCode: Schema.optional(OAuthRefreshErrorCode),
203227
},
204228
) {
205229
override get message(): string {
206230
return this.requiresLogin
207-
? "Could not refresh the T3 Connect CLI credential. Run `t3 connect login` to authorize again."
231+
? `Could not refresh the T3 Connect CLI credential${
232+
this.oauthErrorCode === undefined ? "" : ` (OAuth error: ${this.oauthErrorCode})`
233+
}. Run \`t3 connect login\` to authorize again.`
208234
: "Could not refresh the T3 Connect CLI credential.";
209235
}
210236
}
@@ -298,16 +324,57 @@ const readTokenResponse = Effect.fn("cloud.cli_token.read_token_response")(funct
298324
};
299325
});
300326

327+
const isPermanentRefreshStatus = (status: number): boolean =>
328+
status >= 400 && status < 500 && status !== 408 && status !== 429;
329+
330+
const makeStatusCodeError = (
331+
response: HttpClientResponse.HttpClientResponse,
332+
oauthErrorCode?: OAuthRefreshErrorCode,
333+
) =>
334+
new HttpClientError.HttpClientError({
335+
reason: new HttpClientError.StatusCodeError({
336+
request: response.request,
337+
response,
338+
...(oauthErrorCode === undefined ? {} : { cause: oauthErrorCode }),
339+
}),
340+
});
341+
342+
const isStatusCodeError = (cause: unknown): cause is HttpClientError.HttpClientError =>
343+
HttpClientError.isHttpClientError(cause) && cause.reason._tag === "StatusCodeError";
344+
301345
const exchangeToken = Effect.fn("cloud.cli_token.exchange")(function* (
302346
metadata: Pick<CloudCliOAuthConfig, "tokenEndpoint">,
303347
params: Record<string, string>,
304348
) {
305-
const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
349+
const httpClient = yield* HttpClient.HttpClient;
350+
const isRefreshGrant = params.grant_type === "refresh_token";
351+
let responseWithStatus: HttpClientResponse.HttpClientResponse | undefined;
306352
return yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe(
307353
HttpClientRequest.bodyUrlParams(params),
308354
httpClient.execute,
309-
Effect.flatMap((response) => readTokenResponse(response, params)),
355+
Effect.flatMap((response) => {
356+
responseWithStatus = response;
357+
if (response.status >= 200 && response.status < 300) {
358+
return readTokenResponse(response, params);
359+
}
360+
if (!isRefreshGrant || !isPermanentRefreshStatus(response.status)) {
361+
return Effect.fail(makeStatusCodeError(response));
362+
}
363+
return response.text.pipe(
364+
Effect.flatMap((body) =>
365+
Effect.fail(makeStatusCodeError(response, sanitizedOAuthErrorCode(body))),
366+
),
367+
);
368+
}),
310369
Effect.timeout(OAUTH_REQUEST_TIMEOUT),
370+
Effect.catch((cause) =>
371+
responseWithStatus !== undefined &&
372+
isRefreshGrant &&
373+
isPermanentRefreshStatus(responseWithStatus.status) &&
374+
!isStatusCodeError(cause)
375+
? Effect.fail(makeStatusCodeError(responseWithStatus))
376+
: Effect.fail(cause),
377+
),
311378
);
312379
});
313380

@@ -556,19 +623,23 @@ export const make = Effect.gen(function* () {
556623

557624
const getExisting = semaphore.withPermits(1)(
558625
getExistingNoLock().pipe(
559-
Effect.mapError(
560-
(cause) =>
561-
new CloudCliCredentialRefreshError({
562-
cause,
563-
requiresLogin:
564-
HttpClientError.isHttpClientError(cause) &&
565-
cause.reason._tag === "StatusCodeError" &&
566-
cause.reason.response.status >= 400 &&
567-
cause.reason.response.status < 500 &&
568-
cause.reason.response.status !== 408 &&
569-
cause.reason.response.status !== 429,
570-
}),
571-
),
626+
Effect.mapError((cause) => {
627+
const statusReason =
628+
HttpClientError.isHttpClientError(cause) && cause.reason._tag === "StatusCodeError"
629+
? cause.reason
630+
: undefined;
631+
const requiresLogin =
632+
statusReason !== undefined && isPermanentRefreshStatus(statusReason.response.status);
633+
const oauthErrorCode =
634+
requiresLogin && isOAuthRefreshErrorCode(statusReason?.cause)
635+
? statusReason.cause
636+
: undefined;
637+
return new CloudCliCredentialRefreshError({
638+
cause,
639+
requiresLogin,
640+
...(oauthErrorCode === undefined ? {} : { oauthErrorCode }),
641+
});
642+
}),
572643
Effect.provide(services),
573644
),
574645
);

0 commit comments

Comments
 (0)