Skip to content

Fix Firebase Functions Emulator usage on Firebase Studio #9204

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Aug 13, 2025
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
5 changes: 5 additions & 0 deletions .changeset/three-balloons-collect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@firebase/functions": patch
---

Fixed issue where Firebase Functions SDK caused CORS errors when connected to emulators in Firebase Studio
133 changes: 132 additions & 1 deletion packages/functions/src/callable.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,11 @@ import {
AppCheckInternalComponentName
} from '@firebase/app-check-interop-types';
import { makeFakeApp, createTestService } from '../test/utils';
import { FunctionsService, httpsCallable } from './service';
import {
FunctionsService,
httpsCallable,
httpsCallableFromURL
} from './service';
import { FUNCTIONS_TYPE } from './constants';
import { FunctionsError } from './error';

Expand Down Expand Up @@ -523,9 +527,136 @@ describe('Firebase Functions > Stream', () => {
const [_, options] = mockFetch.firstCall.args;
expect(options.headers['Authorization']).to.equal('Bearer auth-token');
expect(options.headers['Content-Type']).to.equal('application/json');
expect(options.credentials).to.equal(undefined);
expect(options.headers['Accept']).to.equal('text/event-stream');
});

it('calls cloud workstations with credentials', async () => {
const authMock: FirebaseAuthInternal = {
getToken: async () => ({ accessToken: 'auth-token' })
} as unknown as FirebaseAuthInternal;
const authProvider = new Provider<FirebaseAuthInternalName>(
'auth-internal',
new ComponentContainer('test')
);
authProvider.setComponent(
new Component('auth-internal', () => authMock, ComponentType.PRIVATE)
);
const appCheckMock: FirebaseAppCheckInternal = {
getToken: async () => ({ token: 'app-check-token' })
} as unknown as FirebaseAppCheckInternal;
const appCheckProvider = new Provider<AppCheckInternalComponentName>(
'app-check-internal',
new ComponentContainer('test')
);
appCheckProvider.setComponent(
new Component(
'app-check-internal',
() => appCheckMock,
ComponentType.PRIVATE
)
);

const functions = createTestService(
app,
region,
authProvider,
undefined,
appCheckProvider
);
functions.emulatorOrigin = 'test.cloudworkstations.dev';
const mockFetch = sinon.stub(functions, 'fetchImpl' as any);

const mockResponse = new ReadableStream({
start(controller) {
controller.enqueue(
new TextEncoder().encode('data: {"result":"Success"}\n')
);
controller.close();
}
});

mockFetch.resolves({
body: mockResponse,
headers: new Headers({ 'Content-Type': 'text/event-stream' }),
status: 200,
statusText: 'OK'
} as Response);

const func = httpsCallable<Record<string, any>, string, string>(
functions,
'stream'
);
await func.stream({});

expect(mockFetch.calledOnce).to.be.true;
const [_, options] = mockFetch.firstCall.args;
expect(options.credentials).to.equal('include');
});

it('calls streamFromURL cloud workstations with credentials', async () => {
const authMock: FirebaseAuthInternal = {
getToken: async () => ({ accessToken: 'auth-token' })
} as unknown as FirebaseAuthInternal;
const authProvider = new Provider<FirebaseAuthInternalName>(
'auth-internal',
new ComponentContainer('test')
);
authProvider.setComponent(
new Component('auth-internal', () => authMock, ComponentType.PRIVATE)
);
const appCheckMock: FirebaseAppCheckInternal = {
getToken: async () => ({ token: 'app-check-token' })
} as unknown as FirebaseAppCheckInternal;
const appCheckProvider = new Provider<AppCheckInternalComponentName>(
'app-check-internal',
new ComponentContainer('test')
);
appCheckProvider.setComponent(
new Component(
'app-check-internal',
() => appCheckMock,
ComponentType.PRIVATE
)
);

const functions = createTestService(
app,
region,
authProvider,
undefined,
appCheckProvider
);
functions.emulatorOrigin = 'test.cloudworkstations.dev';
const mockFetch = sinon.stub(functions, 'fetchImpl' as any);

const mockResponse = new ReadableStream({
start(controller) {
controller.enqueue(
new TextEncoder().encode('data: {"result":"Success"}\n')
);
controller.close();
}
});

mockFetch.resolves({
body: mockResponse,
headers: new Headers({ 'Content-Type': 'text/event-stream' }),
status: 200,
statusText: 'OK'
} as Response);

const func = httpsCallableFromURL<Record<string, any>, string, string>(
functions,
'stream'
);
await func.stream({});

expect(mockFetch.calledOnce).to.be.true;
const [_, options] = mockFetch.firstCall.args;
expect(options.credentials).to.equal('include');
});

it('aborts during initial fetch', async () => {
const controller = new AbortController();

Expand Down
29 changes: 24 additions & 5 deletions packages/functions/src/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ export function connectFunctionsEmulator(
}://${host}:${port}`;
// Workaround to get cookies in Firebase Studio
if (useSsl) {
void pingServer(functionsInstance.emulatorOrigin);
void pingServer(functionsInstance.emulatorOrigin + '/backends');
updateEmulatorBanner('Functions', true);
}
}
Expand Down Expand Up @@ -245,18 +245,29 @@ export function httpsCallableFromURL<
return callable as HttpsCallable<RequestData, ResponseData, StreamData>;
}

function getCredentials(
functionsInstance: FunctionsService
): 'include' | undefined {
return functionsInstance.emulatorOrigin &&
isCloudWorkstation(functionsInstance.emulatorOrigin)
? 'include'
: undefined;
}

/**
* Does an HTTP POST and returns the completed response.
* @param url The url to post to.
* @param body The JSON body of the post.
* @param headers The HTTP headers to include in the request.
* @param functionsInstance functions instance that is calling postJSON
* @return A Promise that will succeed when the request finishes.
*/
async function postJSON(
url: string,
body: unknown,
headers: { [key: string]: string },
fetchImpl: typeof fetch
fetchImpl: typeof fetch,
functionsInstance: FunctionsService
): Promise<HttpResponse> {
headers['Content-Type'] = 'application/json';

Expand All @@ -265,7 +276,8 @@ async function postJSON(
response = await fetchImpl(url, {
method: 'POST',
body: JSON.stringify(body),
headers
headers,
credentials: getCredentials(functionsInstance)
});
} catch (e) {
// This could be an unhandled error on the backend, or it could be a
Expand Down Expand Up @@ -353,7 +365,13 @@ async function callAtURL(

const failAfterHandle = failAfter(timeout);
const response = await Promise.race([
postJSON(url, body, headers, functionsInstance.fetchImpl),
postJSON(
url,
body,
headers,
functionsInstance.fetchImpl,
functionsInstance
),
failAfterHandle.promise,
functionsInstance.cancelAllRequests
]);
Expand Down Expand Up @@ -439,7 +457,8 @@ async function streamAtURL(
method: 'POST',
body: JSON.stringify(body),
headers,
signal: options?.signal
signal: options?.signal,
credentials: getCredentials(functionsInstance)
});
} catch (e) {
if (e instanceof Error && e.name === 'AbortError') {
Expand Down
Loading