Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions apps/api/src/lib/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -649,15 +649,16 @@ function isTestRuntime(): boolean {
* The single managed config location for the Bun test runner. Every test that
* does not provide its own config file shares this path, and the test
* environment deletes the file between tests — so config-file connector writes
* from one test cannot leak into another test's reads. Scoped by pid (and Bun
* worker id) to stay isolated across processes. Lives under the user's home
* dir (not the OS temp dir) so CodeQL does not flag the read path as an
* "insecure temporary file" — the test environment owns its lifecycle.
* from one test cannot leak into another test's reads. Scoped by pid and Bun
* worker id to stay isolated across worker processes. Lives under the user's
* home dir (not the OS temp dir) so CodeQL does not flag the read path as an
* "insecure temporary file" — the test environment owns its lifecycle and
* removes the directory in `afterAll`.
* // Usage: loadConfigForTest({ configFilePath: TEST_MANAGED_CONFIG_PATH })
*/
export const TEST_MANAGED_CONFIG_DIR = join(
homedir(),
`.mangostudio-test-${process.pid}-${process.env.BUN_WORKER_ID ?? '0'}`
`.mangostudio-test-${process.pid}-${process.env.BUN_TEST_WORKER_ID ?? '0'}`
);
export const TEST_MANAGED_CONFIG_PATH = join(TEST_MANAGED_CONFIG_DIR, 'config.toml');

Expand Down
12 changes: 7 additions & 5 deletions apps/api/src/modules/connectors/application/chatgpt-oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
chatGptOAuthProfile,
exchangeAuthorizationCode,
} from '../infrastructure/chatgpt/oauth-client';
import { chatGptRedirectUri } from '../infrastructure/chatgpt/oauth-constants';
import { getChatGptTokenService } from '../infrastructure/chatgpt/token-service';
import { getSecretMetadataById } from '../infrastructure/connector-repository';
import { createOAuthState, createPkcePair } from '../infrastructure/oauth/pkce';
Expand Down Expand Up @@ -149,6 +150,7 @@ export async function startChatGptOAuth(
code,
codeVerifier: verifier,
authBaseUrl: getConfig().chatgpt.authBaseUrl,
redirectUri: chatGptRedirectUri(session.loopback.port),
fetchImpl: deps.fetchImpl,
});
await completeSession(session, bundle, now);
Expand All @@ -168,12 +170,12 @@ export async function startChatGptOAuth(

return {
sessionId,
authorizeUrl: buildAuthorizeUrl(
chatGptOAuthProfile,
getConfig().chatgpt.authBaseUrl,
authorizeUrl: buildAuthorizeUrl(chatGptOAuthProfile, {
authBaseUrl: getConfig().chatgpt.authBaseUrl,
state,
challenge
),
challenge,
redirectUri: chatGptRedirectUri(session.loopback.port),
}),
expiresAt,
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ export class ChatGptOAuthPortBusyError extends Error {
readonly code = ERROR_CODES.PROVIDER_ERROR;
readonly status = 503;

constructor() {
constructor(port: number = CHATGPT_OAUTH_CALLBACK_PORT) {
super(
`Port ${CHATGPT_OAUTH_CALLBACK_PORT} is already in use. ` +
`Port ${port} is already in use. ` +
'Close any other ChatGPT sign-in in progress (for example `codex login`) and retry.'
);
this.name = 'ChatGptOAuthPortBusyError';
Expand All @@ -28,8 +28,25 @@ export class ChatGptOAuthPortBusyError extends Error {

export type ChatGptLoopbackServer = OAuthLoopbackServer;

let testPortOverride: number | null = null;

/**
* Overrides the registered loopback port for tests. The registered port is one
* machine-wide resource, so every test file that drives the sign-in flow
* competes for it — with test files running in worker processes the loser gets
* a spurious `ChatGptOAuthPortBusyError`, and a suite run on a developer's
* machine collides with a real `codex login`. The test environment passes 0, so
* each process takes an OS-assigned port; a test that needs a known-busy port
* passes one it already holds. `null` restores the registered port.
* // Usage: setChatGptLoopbackPortForTest(0)
*/
export function setChatGptLoopbackPortForTest(port: number | null): void {
testPortOverride = port;
}

/**
* Binds 127.0.0.1:1455 and waits for the OAuth redirect.
* Binds 127.0.0.1:1455 and waits for the OAuth redirect. Read the bound port
* back off the returned server rather than assuming the constant.
* @throws ChatGptOAuthPortBusyError when the port is already bound.
*/
export function startChatGptLoopbackServer(
Expand All @@ -38,11 +55,12 @@ export function startChatGptLoopbackServer(
'expectedState' | 'onAuthorizationCode' | 'onFailure' | 'ttlMs'
>
): ChatGptLoopbackServer {
const port = testPortOverride ?? CHATGPT_OAUTH_CALLBACK_PORT;
return startOAuthLoopbackServer({
...options,
providerLabel: 'ChatGPT',
port: CHATGPT_OAUTH_CALLBACK_PORT,
port,
callbackPath: CHATGPT_OAUTH_CALLBACK_PATH,
createPortBusyError: () => new ChatGptOAuthPortBusyError(),
createPortBusyError: () => new ChatGptOAuthPortBusyError(port),
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,8 @@ export function exchangeAuthorizationCode(options: {
code: string;
codeVerifier: string;
authBaseUrl: string;
/** Must repeat the redirect URI the authorize request carried. */
redirectUri?: string;
fetchImpl?: FetchLike;
}): Promise<ChatGptTokenBundle> {
return coreExchangeAuthorizationCode(chatGptOAuthProfile, options);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,18 @@ export const CHATGPT_OAUTH_CALLBACK_PORT = 1455;

export const CHATGPT_OAUTH_CALLBACK_PATH = '/auth/callback';

/**
* Redirect URI for a loopback server listening on `port`. The authorize request
* and the token exchange must carry the same one, and OpenAI accepts only the
* registered port — so in production this is always `CHATGPT_OAUTH_REDIRECT_URI`.
* // Usage: chatGptRedirectUri(loopback.port)
*/
export function chatGptRedirectUri(port: number): string {
return `http://localhost:${port}${CHATGPT_OAUTH_CALLBACK_PATH}`;
}

/** Redirect URI registered for the client — must match exactly, including scheme and port. */
export const CHATGPT_OAUTH_REDIRECT_URI = `http://localhost:${CHATGPT_OAUTH_CALLBACK_PORT}${CHATGPT_OAUTH_CALLBACK_PATH}`;
export const CHATGPT_OAUTH_REDIRECT_URI = chatGptRedirectUri(CHATGPT_OAUTH_CALLBACK_PORT);

export const CHATGPT_OAUTH_SCOPES = 'openid profile email offline_access';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@
*/

export interface OAuthLoopbackServer {
/**
* The port the server actually bound. Equal to the registered port in
* production; tests bind port 0 and read the OS-assigned one back, so the
* redirect URI they send must be built from this rather than the constant.
*/
readonly port: number;
stop(): void;
}

Expand Down Expand Up @@ -118,5 +124,7 @@ export function startOAuthLoopbackServer(options: LoopbackServerOptions): OAuthL
setTimeout(() => server.stop(true), 1_000).unref?.();
}

return { stop };
// `Bun.serve` types the port as optional because unix-socket servers have
// none; a TCP listener always reports one.
return { port: server.port ?? options.port, stop };
}
Original file line number Diff line number Diff line change
Expand Up @@ -83,19 +83,26 @@ export function decodeJwtPayload(token: string): Record<string, unknown> | null
/** Builds the issuer authorize URL for a PKCE authorization-code flow. */
export function buildAuthorizeUrl(
profile: OAuthProviderProfile<object>,
authBaseUrl: string,
state: string,
challenge: string
options: {
authBaseUrl: string;
state: string;
challenge: string;
/**
* Overrides the profile's registered redirect URI. The token exchange must
* repeat whichever one is sent here.
*/
redirectUri?: string;
}
): string {
const url = new URL('/oauth/authorize', authBaseUrl);
const url = new URL('/oauth/authorize', options.authBaseUrl);
url.search = new URLSearchParams({
response_type: 'code',
client_id: profile.clientId,
redirect_uri: profile.redirectUri,
redirect_uri: options.redirectUri ?? profile.redirectUri,
scope: profile.scopes,
code_challenge: challenge,
code_challenge: options.challenge,
code_challenge_method: 'S256',
state,
state: options.state,
}).toString();
return url.toString();
}
Expand Down Expand Up @@ -197,6 +204,8 @@ export async function exchangeAuthorizationCode<TIdentity extends object>(
code: string;
codeVerifier: string;
authBaseUrl: string;
/** Must repeat the redirect URI the authorize request carried. */
redirectUri?: string;
fetchImpl?: FetchLike;
}
): Promise<OAuthTokenBundle<TIdentity>> {
Expand All @@ -206,7 +215,7 @@ export async function exchangeAuthorizationCode<TIdentity extends object>(
{
grant_type: 'authorization_code',
code: options.code,
redirect_uri: profile.redirectUri,
redirect_uri: options.redirectUri ?? profile.redirectUri,
code_verifier: options.codeVerifier,
},
options.fetchImpl ?? fetch
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
resetChatGptOAuthSessions,
startChatGptOAuth,
} from '../../../src/modules/connectors/application/chatgpt-oauth';
import { CHATGPT_OAUTH_CALLBACK_PORT } from '../../../src/modules/connectors/infrastructure/chatgpt/oauth-constants';
import { setChatGptLoopbackPortForTest } from '../../../src/modules/connectors/infrastructure/chatgpt/loopback-server';
import {
createChatGptTokenService,
setChatGptTokenServiceForTests,
Expand All @@ -29,7 +29,20 @@ const TEST_USER = {
email: 'test-chatgpt-oauth@mangostudio.test',
};

const CALLBACK_BASE = `http://127.0.0.1:${CHATGPT_OAUTH_CALLBACK_PORT}`;
/**
* The loopback callback the session advertised. The test environment pins the
* loopback port to 0, so the port is OS-assigned per process and has to be read
* back off the authorize URL rather than assumed.
*/
function callbackUrl(started: { authorizeUrl: string }, query: string): string {
const redirectUri = new URL(started.authorizeUrl).searchParams.get('redirect_uri');
expect(redirectUri).toBeTruthy();
const url = new URL(redirectUri as string);
// The loopback server binds IPv4 only; `localhost` may resolve to ::1 first.
url.hostname = '127.0.0.1';
url.search = query;
return url.toString();
}

/** Behavior toggle for the fake auth server's token endpoint. */
let tokenEndpointBehavior: 'ok' | 'server-error' = 'ok';
Expand Down Expand Up @@ -158,7 +171,7 @@ describe('chatgpt oauth routes', () => {

// Simulate the browser redirect back to the loopback server.
const callbackResponse = await fetch(
`${CALLBACK_BASE}/auth/callback?code=fake-auth-code&state=${state}`
callbackUrl(started, `code=fake-auth-code&state=${state}`)
);
expect(callbackResponse.status).toBe(200);

Expand Down Expand Up @@ -207,7 +220,7 @@ describe('chatgpt oauth routes', () => {
const first = await startOAuthSession(app);
const firstUrl = new URL(first.authorizeUrl);
await fetch(
`${CALLBACK_BASE}/auth/callback?code=fake-auth-code&state=${firstUrl.searchParams.get('state')}`
callbackUrl(first, `code=fake-auth-code&state=${firstUrl.searchParams.get('state')}`)
);
const firstStatus = await fetchStatus(app, first.sessionId);
expect(firstStatus.connectorId).toBeTruthy();
Expand All @@ -225,7 +238,7 @@ describe('chatgpt oauth routes', () => {
const second = await startOAuthSession(app, { name: 'my-chatgpt', connectorId });
const secondUrl = new URL(second.authorizeUrl);
await fetch(
`${CALLBACK_BASE}/auth/callback?code=second-code&state=${secondUrl.searchParams.get('state')}`
callbackUrl(second, `code=second-code&state=${secondUrl.searchParams.get('state')}`)
);
const secondStatus = await fetchStatus(app, second.sessionId);
expect(secondStatus.connectorId).toBe(connectorId);
Expand All @@ -251,7 +264,7 @@ describe('chatgpt oauth routes', () => {
const started = await startOAuthSession(app);
const authorizeUrl = new URL(started.authorizeUrl);
await fetch(
`${CALLBACK_BASE}/auth/callback?code=fake-auth-code&state=${authorizeUrl.searchParams.get('state')}`
callbackUrl(started, `code=fake-auth-code&state=${authorizeUrl.searchParams.get('state')}`)
);
const status = await fetchStatus(app, started.sessionId);
expect(status.connectorId).toBeTruthy();
Expand Down Expand Up @@ -279,7 +292,7 @@ describe('chatgpt oauth routes', () => {
restoreAuth = restore;

const started = await startOAuthSession(app);
await fetch(`${CALLBACK_BASE}/auth/callback?code=fake-auth-code&state=wrong-state`);
await fetch(callbackUrl(started, 'code=fake-auth-code&state=wrong-state'));

const status = await fetchStatus(app, started.sessionId);
expect(status.status).toBe('failed');
Expand All @@ -294,19 +307,24 @@ describe('chatgpt oauth routes', () => {
const started = await startOAuthSession(app);
const authorizeUrl = new URL(started.authorizeUrl);
await fetch(
`${CALLBACK_BASE}/auth/callback?code=bad-code&state=${authorizeUrl.searchParams.get('state')}`
callbackUrl(started, `code=bad-code&state=${authorizeUrl.searchParams.get('state')}`)
);

const status = await fetchStatus(app, started.sessionId);
expect(status.status).toBe('failed');
});

it('returns 503 when the loopback port is already bound', async () => {
// Hold an OS-assigned port first, then point the loopback at it. Binding a
// well-known port here would race every other file that drives this flow.
const blocker = Bun.serve({
hostname: '127.0.0.1',
port: CHATGPT_OAUTH_CALLBACK_PORT,
port: 0,
fetch: () => new Response('busy'),
});
const blockedPort = blocker.port ?? 0;
expect(blockedPort).toBeGreaterThan(0);
setChatGptLoopbackPortForTest(blockedPort);

try {
const { app, restore } = createAuthenticatedApiTestApp(TEST_USER, settingsRoutes);
Expand All @@ -323,8 +341,9 @@ describe('chatgpt oauth routes', () => {
expect(response.status).toBe(503);
const payload = (await response.json()) as ErrorPayload;
expect(payload.code).toBe(ERROR_CODES.PROVIDER_ERROR);
expect(payload.error).toContain('1455');
expect(payload.error).toContain(String(blockedPort));
} finally {
setChatGptLoopbackPortForTest(0);
blocker.stop(true);
}
});
Expand Down
20 changes: 19 additions & 1 deletion apps/api/tests/support/setup/test-environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
* which is after the preload promise resolves.
*/

import { afterEach, beforeEach } from 'bun:test';
import { afterAll, afterEach, beforeEach } from 'bun:test';
import { mkdirSync, rmSync } from 'node:fs';
import { DEFAULT_LIBRARY_LOCATION_SETTINGS } from '@mangostudio/shared/app-settings';
import { Migrator } from 'kysely/migration';
Expand All @@ -31,6 +31,7 @@ import {
TEST_MANAGED_CONFIG_PATH,
} from '../../../src/lib/config';
import { setLibraryLocationDefaultsForTest } from '../../../src/modules/app-settings/application/app-settings-service';
import { setChatGptLoopbackPortForTest } from '../../../src/modules/connectors/infrastructure/chatgpt/loopback-server';
import { setProviderSecretSyncTtlForTest } from '../../../src/services/providers/core/secret-service';
import { registerApplicationServices } from '../../../src/services/register-application-services';

Expand All @@ -43,6 +44,11 @@ let setupPromise: Promise<void> | null = null;
function installBaseTestConfig(): void {
setLibraryLocationDefaultsForTest(DEFAULT_LIBRARY_LOCATION_SETTINGS);
setProviderSecretSyncTtlForTest(0);
// OpenAI's registered loopback port is a single machine-wide resource. Every
// test that drives the ChatGPT sign-in flow takes an OS-assigned port instead,
// so files running in different worker processes cannot evict each other — and
// so a suite run never collides with a real `codex login`.
setChatGptLoopbackPortForTest(0);
loadConfigForTest({
auth: {
secret: 'test-secret-at-least-32-characters-long',
Expand All @@ -63,6 +69,17 @@ function resetManagedConfigFile(): void {
mkdirSync(TEST_MANAGED_CONFIG_DIR, { recursive: true });
}

/**
* Removes the managed directory for good. The path is scoped by pid, so without
* this every test process leaves one behind in the user's home directory —
* `process.on('exit')` does not run under the Bun test runner, but an `afterAll`
* registered here does, once per isolate under `--isolate` and once per process
* without it.
*/
function removeManagedConfigDir(): void {
rmSync(TEST_MANAGED_CONFIG_DIR, { recursive: true, force: true });
}

/** Runs every migration against the in-memory test database. */
async function migrateTestDatabase(): Promise<void> {
const migrator = new Migrator({
Expand Down Expand Up @@ -97,6 +114,7 @@ export function setupTestEnvironment(): Promise<void> {
// config still overrides it in its own beforeEach (which runs after this one).
beforeEach(installBaseTestConfig);
afterEach(resetManagedConfigFile);
afterAll(removeManagedConfigDir);

setupPromise = migrateTestDatabase();
return setupPromise;
Expand Down
Loading
Loading