Skip to content
TypeScript

fix(connect): preserve rotated credentials during shutdown (#19499)

James Ce21dff1988bb
diff --git a/apps/server/src/cloud/CliTokenManager.test.ts b/apps/server/src/cloud/CliTokenManager.test.ts
index a17e33f122b..76e8efa3d01 100644
--- a/apps/server/src/cloud/CliTokenManager.test.ts
+++ b/apps/server/src/cloud/CliTokenManager.test.ts
@@ -14,6 +14,7 @@ import * as Schema from "effect/Schema";
import * as Terminal from "effect/Terminal";
import * as TestClock from "effect/testing/TestClock";
import * as HttpClient from "effect/http/HttpClient";
+import * as HttpClientError from "effect/http/HttpClientError";
import * as HttpClientResponse from "effect/http/HttpClientResponse";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
@@ -184,6 +185,205 @@ const expiredStoredToken = new TextEncoder().encode(
JSON.stringify({ accessToken: "expired", refreshToken: "refresh-token-1", expiresAtEpochMs: 0 }),
);
+const provideRefreshManager = (
+ httpClient: HttpClient.HttpClient,
+ secrets = Layer.mock(ServerSecretStore.ServerSecretStore)({
+ get: () => Effect.succeedSome(expiredStoredToken),
+ }),
+) =>
+ Effect.provide(
+ CliTokenManager.layer.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ Layer.succeed(HttpClient.HttpClient, httpClient),
+ secrets,
+ Layer.mock(ExternalLauncher.ExternalLauncher)({}),
+ NodeServices.layer,
+ ),
+ ),
+ Layer.provideMerge(ConfigProvider.layer(ConfigProvider.fromEnv({ env: TEST_ENV }))),
+ ),
+ );
+
+it.effect(
+ "persists rotated credentials under the lock despite shutdown, while queued callers can cancel",
+ () =>
+ Effect.gen(function* () {
+ const requestStarted = yield* Deferred.make<void>();
+ const releaseRequest = yield* Deferred.make<void>();
+ const persistStarted = yield* Deferred.make<void>();
+ const releasePersist = yield* Deferred.make<void>();
+ let stored = expiredStoredToken;
+ let reads = 0;
+ const httpClient = HttpClient.make((request) =>
+ Effect.gen(function* () {
+ yield* Deferred.succeed(requestStarted, undefined);
+ yield* Deferred.await(releaseRequest);
+ return HttpClientResponse.fromWeb(
+ request,
+ Response.json({
+ access_token: "rotated-access",
+ refresh_token: "rotated-refresh",
+ expires_in: 3600,
+ token_type: "bearer",
+ }),
+ );
+ }),
+ );
+ const secrets = Layer.mock(ServerSecretStore.ServerSecretStore)({
+ get: () =>
+ Effect.sync(() => {
+ reads++;
+ return Option.some(stored);
+ }),
+ set: (_name, value) =>
+ Effect.gen(function* () {
+ yield* Deferred.succeed(persistStarted, undefined);
+ yield* Deferred.await(releasePersist);
+ stored = new Uint8Array(value);
+ }),
+ });
+
+ yield* Effect.gen(function* () {
+ const manager = yield* CliTokenManager.CloudCliTokenManager;
+ const refresh = yield* manager.getExisting.pipe(Effect.forkChild);
+ assert.isTrue(
+ yield* Effect.raceFirst(
+ Deferred.await(requestStarted).pipe(Effect.as(true)),
+ Fiber.await(refresh).pipe(Effect.as(false)),
+ ),
+ "refresh failed before reaching the endpoint",
+ );
+ const waiter = yield* manager.getExisting.pipe(
+ Effect.forkChild({ startImmediately: true }),
+ );
+ yield* Fiber.interrupt(waiter);
+ assert.equal(reads, 1, "queued caller must not read credentials during refresh");
+ const interruption = yield* Fiber.interrupt(refresh).pipe(
+ Effect.forkChild({ startImmediately: true }),
+ );
+ yield* Deferred.succeed(releaseRequest, undefined);
+ const reachedPersist = yield* Effect.raceFirst(
+ Deferred.await(persistStarted).pipe(Effect.as(true)),
+ Fiber.await(refresh).pipe(Effect.as(false)),
+ );
+ assert.isTrue(reachedPersist, "shutdown discarded the rotated credential");
+ const reader = yield* manager.getExisting.pipe(
+ Effect.forkChild({ startImmediately: true }),
+ );
+ assert.equal(reads, 1, "credential lock must cover persistence");
+ yield* Deferred.succeed(releasePersist, undefined);
+ yield* Fiber.join(interruption);
+ const token = Option.getOrThrow(yield* Fiber.join(reader));
+ assert.equal(token.refreshToken, "rotated-refresh");
+ assert.equal(token.accessToken, "rotated-access");
+ }).pipe(
+ Effect.ensuring(Deferred.succeed(releaseRequest, undefined)),
+ Effect.ensuring(Deferred.succeed(releasePersist, undefined)),
+ provideRefreshManager(httpClient, secrets),
+ );
+ }),
+);
+
+it.effect.each([
+ { status: 400, code: "invalid_grant", requiresLogin: true, diagnostic: true },
+ { status: 403, code: "private-provider-secret", requiresLogin: true, diagnostic: false },
+ { status: 408, code: "invalid_grant", requiresLogin: false, diagnostic: false },
+ { status: 429, code: "invalid_grant", requiresLogin: false, diagnostic: false },
+ { status: 500, code: "invalid_grant", requiresLogin: false, diagnostic: false },
+])(
+ "refresh HTTP $status exposes only a safe login diagnostic",
+ ({ status, code, requiresLogin, diagnostic }) =>
+ Effect.gen(function* () {
+ const manager = yield* CliTokenManager.CloudCliTokenManager;
+ const error = yield* manager.getExisting.pipe(Effect.flip);
+ assert.instanceOf(error, CliTokenManager.CloudCliCredentialRefreshError);
+ assert.equal(error.requiresLogin, requiresLogin);
+ assert.equal(error.message.includes("t3 connect login"), requiresLogin);
+ assert.equal(error.message.includes("OAuth error: invalid_grant"), diagnostic);
+ assert.notInclude(error.message, "private");
+ assert.equal(error.message.includes("OAuth error:"), diagnostic);
+ assert.isTrue(yield* manager.hasCredential);
+ }).pipe(
+ provideRefreshManager(
+ HttpClient.make((request) =>
+ Effect.succeed(
+ HttpClientResponse.fromWeb(
+ request,
+ Response.json(
+ {
+ error: code,
+ error_description: "private-description",
+ refresh_token: "private-refresh-token",
+ },
+ { status },
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+);
+
+it.effect.each(["malformed", "unreadable", "stalled"] as const)(
+ "a $0 rejection body preserves HTTP status and its underlying failure",
+ (bodyKind) =>
+ Effect.gen(function* () {
+ const readerFailure = new Error("private-reader-failure");
+ const client = HttpClient.make((request) =>
+ Effect.succeed(
+ HttpClientResponse.fromWeb(
+ request,
+ new Response(
+ bodyKind === "malformed"
+ ? "{"
+ : new ReadableStream({
+ start: (controller) => {
+ if (bodyKind === "unreadable") controller.error(readerFailure);
+ else controller.enqueue(new TextEncoder().encode("{"));
+ },
+ }),
+ { status: 400 },
+ ),
+ ),
+ ).pipe(Effect.delay(bodyKind === "stalled" ? Duration.seconds(4) : Duration.zero)),
+ );
+ yield* Effect.gen(function* () {
+ const manager = yield* CliTokenManager.CloudCliTokenManager;
+ const refresh = yield* manager.getExisting.pipe(
+ Effect.flip,
+ Effect.timed,
+ Effect.forkChild,
+ );
+ const reader = yield* manager.hasCredential.pipe(Effect.forkChild);
+ if (bodyKind === "stalled") yield* TestClock.adjust(Duration.seconds(14));
+ const [duration, error] = yield* Fiber.join(refresh);
+ if (bodyKind === "stalled") assert.equal(Duration.toMillis(duration), 10_000);
+ assert.instanceOf(error, CliTokenManager.CloudCliCredentialRefreshError);
+ assert.isTrue(error.requiresLogin);
+ assert.include(error.message, "t3 connect login");
+ assert.notInclude(error.message, "private");
+ assert.notInclude(error.message, "OAuth error:");
+ assert.isTrue(HttpClientError.isHttpClientError(error.cause));
+ if (!HttpClientError.isHttpClientError(error.cause)) return;
+ assert.equal(error.cause.reason._tag, "StatusCodeError");
+ if (error.cause.reason._tag !== "StatusCodeError") return;
+ assert.equal(error.cause.reason.response.status, 400);
+ const underlying = error.cause.reason.cause;
+ if (bodyKind === "unreadable") {
+ assert.isTrue(HttpClientError.isHttpClientError(underlying));
+ if (!HttpClientError.isHttpClientError(underlying)) return;
+ assert.equal(underlying.reason._tag, "DecodeError");
+ if (underlying.reason._tag === "DecodeError")
+ assert.strictEqual(underlying.reason.cause, readerFailure);
+ } else if (bodyKind === "stalled") {
+ assert.isTrue(Cause.isTimeoutError(underlying));
+ }
+ assert.isTrue(yield* Fiber.join(reader));
+ }).pipe(provideRefreshManager(client));
+ }),
+);
+
it.effect("a stalled token refresh fails and releases the credential lock", () =>
Effect.gen(function* () {
const manager = yield* CliTokenManager.CloudCliTokenManager;
@@ -192,7 +392,9 @@ it.effect("a stalled token refresh fails and releases the credential lock", () =
yield* TestClock.adjust(Duration.seconds(10));
- assert.instanceOf(yield* Fiber.join(refresh), CliTokenManager.CloudCliCredentialRefreshError);
+ const error = yield* Fiber.join(refresh);
+ assert.instanceOf(error, CliTokenManager.CloudCliCredentialRefreshError);
+ assert.isFalse(error.requiresLogin);
assert.isTrue(yield* Fiber.join(hasCredential));
}).pipe(
Effect.provide(
diff --git a/apps/server/src/cloud/CliTokenManager.ts b/apps/server/src/cloud/CliTokenManager.ts
index 2b09821ffca..5b041a9efba 100644
--- a/apps/server/src/cloud/CliTokenManager.ts
+++ b/apps/server/src/cloud/CliTokenManager.ts
@@ -146,6 +146,21 @@ const OAuthErrorResponse = Schema.Struct({
error: Schema.String,
error_description: Schema.optional(Schema.String),
});
+const OAuthRefreshErrorCode = Schema.Literals([
+ "invalid_grant",
+ "invalid_client",
+ "unauthorized_client",
+ "unsupported_grant_type",
+ "invalid_request",
+ "invalid_scope",
+ "access_denied",
+]);
+const decodeOAuthRefreshErrorResponse = Schema.decodeUnknownOption(
+ Schema.Struct({ error: OAuthRefreshErrorCode }),
+);
+
+const isPermanentRefreshStatus = (status: number): boolean =>
+ status >= 400 && status < 500 && status !== 408 && status !== 429;
const DeviceAuthorizationResponse = Schema.Struct({
device_code: Schema.String,
@@ -190,13 +205,27 @@ export class CloudCliCredentialRemovalError extends Schema.TaggedError<CloudCliC
export class CloudCliCredentialRefreshError extends Schema.TaggedError<CloudCliCredentialRefreshError>()(
"CloudCliCredentialRefreshError",
- { cause: Schema.Defect() },
+ {
+ cause: Schema.Defect(),
+ status: Schema.optional(Schema.Number),
+ oauthErrorCode: Schema.optional(OAuthRefreshErrorCode),
+ },
) {
+ get requiresLogin(): boolean {
+ return this.status !== undefined && isPermanentRefreshStatus(this.status);
+ }
+
override get message(): string {
- return "Could not refresh the T3 Connect CLI credential.";
+ return this.requiresLogin
+ ? `Could not refresh the T3 Connect CLI credential${
+ this.oauthErrorCode === undefined ? "" : ` (OAuth error: ${this.oauthErrorCode})`
+ }. Run \`t3 connect login\` to authorize again.`
+ : "Could not refresh the T3 Connect CLI credential.";
}
}
+export const isCloudCliCredentialRefreshError = Schema.is(CloudCliCredentialRefreshError);
+
export class CloudCliCredentialReadError extends Schema.TaggedError<CloudCliCredentialReadError>()(
"CloudCliCredentialReadError",
{ cause: Schema.Defect() },
@@ -289,11 +318,52 @@ const exchangeToken = Effect.fn("cloud.cli_token.exchange")(function* (
params: Record<string, string>,
) {
const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
+ const startedAt = yield* Clock.monotonicTimeNanos;
return yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe(
HttpClientRequest.bodyUrlParams(params),
httpClient.execute,
Effect.flatMap((response) => readTokenResponse(response, params)),
Effect.timeout(OAUTH_REQUEST_TIMEOUT),
+ Effect.catchTags({
+ HttpClientError: (cause) =>
+ Effect.gen(function* () {
+ const reason = cause.reason;
+ if (
+ params.grant_type !== "refresh_token" ||
+ reason._tag !== "StatusCodeError" ||
+ !isPermanentRefreshStatus(reason.response.status)
+ ) {
+ return yield* cause;
+ }
+ // Reading a rejection body shares the exchange budget without losing
+ // the known status when the body stalls or cannot be decoded.
+ const elapsed = Duration.toMillis(
+ Duration.nanos((yield* Clock.monotonicTimeNanos) - startedAt),
+ );
+ const body = yield* reason.response.json.pipe(
+ Effect.timeout(Math.max(0, Duration.toMillis(OAUTH_REQUEST_TIMEOUT) - elapsed)),
+ Effect.mapError(
+ (cause) =>
+ new CloudCliCredentialRefreshError({
+ status: reason.response.status,
+ cause: new HttpClientError.HttpClientError({
+ reason: new HttpClientError.StatusCodeError({
+ request: reason.request,
+ response: reason.response,
+ cause,
+ }),
+ }),
+ }),
+ ),
+ );
+ const diagnostic = decodeOAuthRefreshErrorResponse(body);
+ return yield* new CloudCliCredentialRefreshError({
+ cause,
+ status: reason.response.status,
+ ...(Option.isSome(diagnostic) ? { oauthErrorCode: diagnostic.value.error } : {}),
+ });
+ }),
+ }),
);
});
@@ -516,12 +586,26 @@ export const make = Effect.gen(function* () {
if (token.value.expiresAtEpochMs - CLOUD_CLI_OAUTH_REFRESH_EARLY_MS > now) {
return token;
}
- return Option.some(yield* refresh(token.value).pipe(Effect.flatMap(persist)));
+ return Option.some(
+ // The endpoint can rotate the refresh token before shutdown interrupts us.
+ // Keep the lock through persistence; the exchange still times out internally.
+ yield* refresh(token.value).pipe(Effect.flatMap(persist), Effect.uninterruptible),
+ );
});
const getExisting = semaphore.withPermits(1)(
getExistingNoLock().pipe(
- Effect.mapError((cause) => new CloudCliCredentialRefreshError({ cause })),
+ Effect.mapError((cause) =>
+ isCloudCliCredentialRefreshError(cause)
+ ? cause
+ : new CloudCliCredentialRefreshError({
+ cause,
+ ...(HttpClientError.isHttpClientError(cause) &&
+ cause.reason._tag === "StatusCodeError"
+ ? { status: cause.reason.response.status }
+ : {}),
+ }),
+ ),
Effect.provide(services),
),
);
diff --git a/apps/server/src/cloud/CloudLink.lifecycle.test.ts b/apps/server/src/cloud/CloudLink.lifecycle.test.ts
index 35285fddd26..fea003fe3d5 100644
--- a/apps/server/src/cloud/CloudLink.lifecycle.test.ts
+++ b/apps/server/src/cloud/CloudLink.lifecycle.test.ts
@@ -242,6 +242,7 @@ describe("releaseManagedTunnelOnShutdown", () => {
readonly respond?: () => Response;
readonly address?: HttpServer.HttpServer["Service"]["address"];
readonly respondEffect?: Effect.Effect<Response>;
+ readonly getExisting?: CliTokenManager.CloudCliTokenManager["Service"]["getExisting"];
}
const writeLauncherState = (update: ServiceUpdateRecord) =>
@@ -318,7 +319,7 @@ describe("releaseManagedTunnelOnShutdown", () => {
CliTokenManager.CloudCliTokenManager,
CliTokenManager.CloudCliTokenManager.of({
get: unusedSecretStoreOperation(),
- getExisting: Effect.succeedSome(cliToken),
+ getExisting: harness.getExisting ?? Effect.succeedSome(cliToken),
hasCredential: unusedSecretStoreOperation(),
store: () => unusedSecretStoreOperation(),
clear: unusedSecretStoreOperation(),
@@ -1337,6 +1338,45 @@ describe("releaseManagedTunnelOnShutdown", () => {
);
});
+ it.effect("startup retries transient refresh failures but stops when login is required", () => {
+ const { store } = makeMemorySecretStore(managedLinkSecrets);
+ const requests: Array<HttpClientRequest.HttpClientRequest> = [];
+ const applyConfigCalls: Array<unknown> = [];
+ const permanent = new CliTokenManager.CloudCliCredentialRefreshError({
+ cause: new Error("private-oauth-failure"),
+ status: 400,
+ oauthErrorCode: "invalid_grant",
+ });
+ let attempts = 0;
+ const getExisting = Effect.suspend(() => {
+ attempts++;
+ if (attempts > 2) return Effect.die("retried a permanent credential rejection");
+ return Effect.fail(
+ attempts === 2
+ ? permanent
+ : new CliTokenManager.CloudCliCredentialRefreshError({
+ cause: new Error("connection reset"),
+ }),
+ );
+ });
+
+ return Effect.gen(function* () {
+ const link = yield* CloudLink.CloudLink;
+ const registration = yield* retryManagedTunnelRegistration(
+ link.reconcileDesiredLinkIfStillDesired("http://127.0.0.1:3773"),
+ CloudLink.shouldRetryCloudLink,
+ ).pipe(Effect.flip, Effect.forkChild);
+ yield* TestClock.adjust("10 seconds");
+ const error = yield* Fiber.join(registration);
+ expect(attempts).toBe(2);
+ expect(error).toBe(permanent);
+ expect(error.message).toContain("t3 connect login");
+ expect(error.message).not.toContain("private");
+ expect(requests).toEqual([]);
+ expect(applyConfigCalls).toEqual([]);
+ }).pipe(provideReleaseHarness({ store, requests, applyConfigCalls, getExisting }));
+ });
+
it.effect("keeps a tunnel configuration replaced during recovery", () => {
const { store, values } = makeMemorySecretStore([
[CLOUD_ENDPOINT_RUNTIME_CONFIG, "old-config"],
diff --git a/apps/server/src/cloud/CloudLink.ts b/apps/server/src/cloud/CloudLink.ts
index 945fdeef87d..12d6aee4931 100644
--- a/apps/server/src/cloud/CloudLink.ts
+++ b/apps/server/src/cloud/CloudLink.ts
@@ -291,7 +291,9 @@ const isPermanentLinkError = Schema.is(
);
export const shouldRetryCloudLink = (error: unknown): boolean =>
- shouldRetryRelayRequest(error) && !isPermanentLinkError(error);
+ shouldRetryRelayRequest(error) &&
+ !isPermanentLinkError(error) &&
+ !(CliTokenManager.isCloudCliCredentialRefreshError(error) && error.requiresLogin);
const rollbackFailed = (cause: unknown) =>
Effect.logWarning("Could not roll back a T3 Connect preference", { cause });