Skip to content

Commit 478fdfc

Browse files
fix(server): keep managed Codex token renewal in the server (pingdotgg#21786)
1 parent c7e3993 commit 478fdfc

4 files changed

Lines changed: 534 additions & 1 deletion

File tree

‎apps/server/src/provider/CodexChatGptAuth.test.ts‎

Lines changed: 218 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
11
// @effect-diagnostics nodeBuiltinImport:off globalFetchInEffect:off - Local mock OAuth server validates the browser callback boundary.
2+
import * as NodeNet from "node:net";
3+
import * as Context from "effect/Context";
4+
import * as Scope from "effect/Scope";
5+
import * as ServerConfig from "../config.ts";
6+
import * as CodexManagedTokenBroker from "./CodexManagedTokenBroker.ts";
27
import * as NodeHttp from "node:http";
38
import * as NodeCrypto from "node:crypto";
49
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -11,7 +16,7 @@ import * as Stream from "effect/Stream";
1116
import * as Fiber from "effect/Fiber";
1217
import * as Deferred from "effect/Deferred";
1318
import { subscribeChatGptHandoff } from "./CodexChatGptHandoff.ts";
14-
import { FetchHttpClient } from "effect/http";
19+
import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";
1520
import { exportJWK, generateKeyPair, SignJWT } from "jose";
1621
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
1722
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
@@ -320,6 +325,16 @@ const makeHarnessFor = Effect.fnUntraced(function* (
320325
);
321326
return { auth: destination, bytes: destinationBytes };
322327
}),
328+
bindProfile: (expectedProfileKey: string) =>
329+
makeCodexChatGptAuth({
330+
instanceId,
331+
expectedProfileKey,
332+
discoveryUrl: `${origin}/discovery`,
333+
resource: `${origin}/v1`,
334+
}).pipe(
335+
Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),
336+
Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, environment),
337+
),
323338
recreateAuth: makeCodexChatGptAuth({
324339
instanceId,
325340
discoveryUrl: `${origin}/discovery`,
@@ -1604,3 +1619,205 @@ it.effect("telemetry failures do not fail a verified ChatGPT sign-in", () =>
16041619
}),
16051620
),
16061621
);
1622+
it.effect("a running session renews its bound profile but refuses a replacement sign-in", () =>
1623+
provision(
1624+
Effect.gen(function* () {
1625+
const h = yield* makeHarness;
1626+
yield* h.signIn;
1627+
yield* h.phase("succeeded");
1628+
const profileKey = yield* h.auth.profileKey(Option.getOrThrow(yield* h.auth.read));
1629+
const first = yield* h.bindProfile(profileKey);
1630+
const second = yield* h.bindProfile(profileKey);
1631+
yield* h.seedExpired;
1632+
const renewed = yield* Effect.all([first.access, second.access], {
1633+
concurrency: "unbounded",
1634+
});
1635+
assert.equal(h.refreshes(), 1);
1636+
assert.equal(renewed[0].accessToken, "access-1");
1637+
assert.deepEqual(renewed[0], renewed[1]);
1638+
assert.equal(yield* h.auth.profileKey(renewed[0]), profileKey);
1639+
1640+
// Reconnecting the same account replaces its sign-in identity, too.
1641+
yield* h.reconnectProfile("oaiapp_test");
1642+
yield* h.phase("succeeded");
1643+
const replacement = Option.getOrThrow(yield* h.auth.read);
1644+
assert.equal(replacement.clientId, renewed[0].clientId);
1645+
assert.equal(replacement.subject, renewed[0].subject);
1646+
yield* h.seedExpired;
1647+
assert.equal((yield* first.access.pipe(Effect.flip)).operation, "access");
1648+
assert.equal(h.refreshes(), 1);
1649+
yield* h.auth.revoke;
1650+
assert.equal((yield* second.access.pipe(Effect.flip)).operation, "access");
1651+
assert.isTrue(Option.isNone(yield* h.auth.read));
1652+
}),
1653+
),
1654+
);
1655+
1656+
const makeRenewalBroker = Effect.gen(function* () {
1657+
const oauthEntered = yield* Deferred.make<void>();
1658+
const oauthRelease = yield* Deferred.make<void>();
1659+
let pauseOAuth = false;
1660+
const refreshTokens: string[] = [];
1661+
const credentials = {
1662+
clientId: "oaiapp_broker",
1663+
subject: "broker-user",
1664+
idToken: "broker-sign-in",
1665+
email: null,
1666+
accessToken: "expired-access",
1667+
refreshToken: "single-use-refresh",
1668+
expiresAt: 0,
1669+
earliestRefreshAt: null,
1670+
scopes: ["chatgpt.tokens.use.direct"],
1671+
};
1672+
const environmentId = EnvironmentId.make("00000000-0000-4000-8000-000000000001");
1673+
const http = HttpClient.make((request) =>
1674+
Effect.gen(function* () {
1675+
if (request.url.endsWith("openid-configuration")) {
1676+
return HttpClientResponse.fromWeb(
1677+
request,
1678+
Response.json({
1679+
issuer: "https://auth.openai.com",
1680+
authorization_endpoint: "https://auth.openai.com/authorize",
1681+
token_endpoint: "https://auth.openai.com/token",
1682+
jwks_uri: "https://auth.openai.com/jwks",
1683+
}),
1684+
);
1685+
}
1686+
assert.equal(request.url, "https://auth.openai.com/token");
1687+
assert.equal(request.body._tag, "Uint8Array");
1688+
if (request.body._tag !== "Uint8Array") return yield* Effect.die("Missing refresh body");
1689+
const body = new URLSearchParams(new TextDecoder().decode(request.body.body));
1690+
refreshTokens.push(body.get("refresh_token")!);
1691+
yield* Deferred.succeed(oauthEntered, undefined);
1692+
if (pauseOAuth) yield* Deferred.await(oauthRelease);
1693+
return HttpClientResponse.fromWeb(
1694+
request,
1695+
Response.json({
1696+
access_token: "renewed-access",
1697+
refresh_token: "rotated-refresh",
1698+
expires_in: 3600,
1699+
token_type: "Bearer",
1700+
scope: "chatgpt.tokens.use.direct",
1701+
}),
1702+
);
1703+
}),
1704+
);
1705+
return yield* Effect.gen(function* () {
1706+
const store = yield* ProviderCredentialStore.make("codex-chatgpt", instanceId);
1707+
yield* store.set(new TextEncoder().encode(JSON.stringify(credentials)));
1708+
const auth = yield* makeCodexChatGptAuth({ instanceId });
1709+
const profileKey = yield* auth.profileKey(credentials);
1710+
const scope = yield* Scope.make();
1711+
yield* Effect.addFinalizer((exit) => Scope.close(scope, exit));
1712+
const context = yield* Layer.buildWithScope(CodexManagedTokenBroker.layer, scope);
1713+
const broker = Context.get(context, CodexManagedTokenBroker.CodexManagedTokenBroker);
1714+
const endpoint = yield* broker.endpoint;
1715+
yield* Effect.addFinalizer(() => Deferred.succeed(oauthRelease, undefined));
1716+
return {
1717+
auth,
1718+
store,
1719+
broker,
1720+
endpoint,
1721+
refreshTokens,
1722+
request: { version: 1, instanceId, environmentId, profileKey },
1723+
oauthEntered,
1724+
oauthRelease,
1725+
pause: () => {
1726+
pauseOAuth = true;
1727+
},
1728+
};
1729+
}).pipe(
1730+
Effect.provide(ServerSecretStore.layer),
1731+
Effect.provideService(HttpClient.HttpClient, http),
1732+
Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, {
1733+
getEnvironmentId: Effect.succeed(environmentId),
1734+
}),
1735+
);
1736+
});
1737+
1738+
const brokerClient = (endpoint: string, request: unknown) =>
1739+
Effect.acquireRelease(
1740+
Effect.callback<{ socket: NodeNet.Socket; response: Promise<string> }, Error>((resume) => {
1741+
const socket = NodeNet.createConnection(endpoint);
1742+
let text = "";
1743+
socket.setEncoding("utf8");
1744+
socket.on("data", (chunk) => {
1745+
text += chunk;
1746+
});
1747+
const response = new Promise<string>((resolve) => socket.once("close", () => resolve(text)));
1748+
socket.on("error", () => {});
1749+
socket.once("error", (error) => resume(Effect.fail(error)));
1750+
socket.once("connect", () => {
1751+
socket.write(JSON.stringify(request) + "\n");
1752+
resume(Effect.succeed({ socket, response }));
1753+
});
1754+
return Effect.sync(() => {
1755+
if (socket.connecting) socket.destroy();
1756+
});
1757+
}),
1758+
({ socket }) => Effect.sync(() => socket.destroy()),
1759+
);
1760+
const provideBroker = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
1761+
effect.pipe(
1762+
Effect.scoped,
1763+
Effect.provide(
1764+
ServerConfig.layerTest(process.cwd(), { prefix: "t3-renewal-test-" }).pipe(
1765+
Layer.provideMerge(NodeServices.layer),
1766+
),
1767+
),
1768+
);
1769+
1770+
// regression: #16132 a renewal must outlive the Codex helper that asked for it, because the
1771+
// refresh token it spends is single-use.
1772+
it.effect("server-owned renewal persists rotated credentials after the helper disconnects", () =>
1773+
provideBroker(
1774+
Effect.gen(function* () {
1775+
const h = yield* makeRenewalBroker;
1776+
h.pause();
1777+
const client = yield* brokerClient(h.endpoint, h.request);
1778+
yield* Deferred.await(h.oauthEntered);
1779+
client.socket.destroy();
1780+
yield* Effect.promise(() => client.response);
1781+
assert.equal(Option.getOrThrow(yield* h.auth.read).refreshToken, "single-use-refresh");
1782+
yield* Deferred.succeed(h.oauthRelease, undefined);
1783+
yield* h.broker.awaitIdle;
1784+
const persisted = Option.getOrThrow(yield* h.auth.read);
1785+
assert.equal(persisted.refreshToken, "rotated-refresh");
1786+
assert.equal((yield* h.auth.access).accessToken, "renewed-access");
1787+
assert.deepEqual(h.refreshTokens, ["single-use-refresh"]);
1788+
}),
1789+
),
1790+
);
1791+
1792+
it.live("the private broker refuses another environment, instance, or sign-in profile", () =>
1793+
provideBroker(
1794+
Effect.gen(function* () {
1795+
const h = yield* makeRenewalBroker;
1796+
yield* Effect.forEach(
1797+
[
1798+
{
1799+
...h.request,
1800+
environmentId: EnvironmentId.make("00000000-0000-4000-8000-000000000002"),
1801+
},
1802+
{ ...h.request, instanceId: ProviderInstanceId.make("another-instance") },
1803+
{ ...h.request, profileKey: "0".repeat(64) },
1804+
],
1805+
(request) =>
1806+
Effect.scoped(
1807+
Effect.gen(function* () {
1808+
const client = yield* brokerClient(h.endpoint, request);
1809+
assert.equal(yield* Effect.promise(() => client.response), "");
1810+
}),
1811+
),
1812+
);
1813+
yield* h.broker.awaitIdle;
1814+
assert.deepEqual(h.refreshTokens, []);
1815+
const client = yield* brokerClient(h.endpoint, h.request);
1816+
assert.deepEqual(JSON.parse(yield* Effect.promise(() => client.response)), {
1817+
token: "renewed-access",
1818+
});
1819+
yield* h.broker.awaitIdle;
1820+
assert.deepEqual(h.refreshTokens, ["single-use-refresh"]);
1821+
}),
1822+
),
1823+
);

‎apps/server/src/provider/CodexChatGptAuth.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import * as Cause from "effect/Cause";
1515
import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
1616
import { openAiUserId } from "../telemetry/Identify.ts";
1717
import * as Crypto from "effect/Crypto";
18+
import * as Hex from "effect/encoding/Hex";
1819
import * as Exit from "effect/Exit";
1920
import { codexAuthCallbackPage, codexAuthReturnUrl } from "./CodexAuthCallbackPage.ts";
2021
import * as Effect from "effect/Effect";
@@ -108,6 +109,7 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
108109
readonly defaultReturnUrl?: string;
109110
readonly reconnectProfile?: ChatGptReconnectProfile | null;
110111
readonly telemetryFlow?: "direct" | "primary_handoff";
112+
readonly expectedProfileKey?: string;
111113
}) {
112114
const analytics = yield* Effect.serviceOption(AnalyticsService.AnalyticsService);
113115
const settings = yield* Effect.serviceOption(ServerSettings.ServerSettingsService);
@@ -726,6 +728,17 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
726728
),
727729
);
728730
});
731+
// ID tokens survive renewal but change on sign-in. Bind active children to the
732+
// launch profile without putting an identity token or subject in their argv.
733+
const profileKey = (record: CodexChatGptCredentials) =>
734+
crypto
735+
.digest(
736+
"SHA-256",
737+
new TextEncoder().encode(
738+
JSON.stringify([record.clientId, record.subject, record.idToken ?? null]),
739+
),
740+
)
741+
.pipe(Effect.map(Hex.encode), Effect.orDie);
729742
const access = lock.withPermit(
730743
withSessionLock(
731744
Effect.uninterruptible(
@@ -734,6 +747,11 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
734747
if (Option.isNone(saved))
735748
return yield* failure("access", "Sign in with ChatGPT to use managed Codex.");
736749
let record = saved.value;
750+
if (
751+
options.expectedProfileKey !== undefined &&
752+
(yield* profileKey(record)) !== options.expectedProfileKey
753+
)
754+
return yield* failure("access", "The ChatGPT connection changed. Start a new session.");
737755
if (!record.scopes.includes(REQUIRED_SCOPE))
738756
return yield* failure(
739757
"sharing",
@@ -991,6 +1009,7 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
9911009
controller: { ...controller, reconnectProfile, importProfile },
9921010
read,
9931011
access,
1012+
profileKey,
9941013
exportProfile,
9951014
revoke: lock.withPermit(withSessionLock(remove)),
9961015
};

0 commit comments

Comments
 (0)