Skip to content
Open
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
- Fixed the Functions emulator with `--inspect-functions` sometimes running the previously called function.
- Updated `glob` to `^14.0.6` and transitive `minimatch` floors to `^11.0.8` to resolve `glob` and `minimatch` security advisories.
- Updated `tar` override to `^8.1.2` in the `firebase-cli` Docker image to resolve `tar` security advisories.
- Fixed CVE-2026-137199 by updating `cross-spawn` to `^7.1.2`.
Expand Down
20 changes: 17 additions & 3 deletions scripts/emulator-tests/functionsEmulatorRuntime.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,21 @@
import * as fs from "fs/promises";
import * as spawn from "cross-spawn";
import * as path from "path";
import { ChildProcess } from "child_process";
import { ChildProcess, Serializable } from "child_process";

import * as express from "express";
import { Change } from "firebase-functions";
import { DocumentSnapshot } from "firebase-functions/v1/firestore";

import { FunctionRuntimeBundles, TIMEOUT_LONG, MODULE_ROOT } from "./fixtures";
import {
DEBUG_MSG_HANDLED,
FunctionsRuntimeBundle,
getTemporarySocketPath,
SignatureType,
} from "../../src/emulator/functionsEmulatorShared";
import { streamToString } from "../../src/utils";
import { EmulatorLog } from "../../src/emulator/types";

const FUNCTIONS_DIR = `./scripts/emulator-tests/functions`;
const ADMIN_SDK_CONFIG = {
Expand Down Expand Up @@ -63,9 +65,9 @@
try {
await Promise.race([isSocketReady(socketPath), timeout]);
break;
} catch (err: any) {

Check warning on line 68 in scripts/emulator-tests/functionsEmulatorRuntime.spec.ts

View workflow job for this annotation

GitHub Actions / lint (24)

Unexpected any. Specify a different type
// Allow us to wait until the server is listening.
if (["ECONNREFUSED", "ENOENT"].includes(err?.code)) {

Check warning on line 70 in scripts/emulator-tests/functionsEmulatorRuntime.spec.ts

View workflow job for this annotation

GitHub Actions / lint (24)

Unsafe member access .code on an `any` value

Check warning on line 70 in scripts/emulator-tests/functionsEmulatorRuntime.spec.ts

View workflow job for this annotation

GitHub Actions / lint (24)

Unsafe argument of type `any` assigned to a parameter of type `string`
await sleep(100);
continue;
}
Expand Down Expand Up @@ -116,10 +118,10 @@
const msg = message.toString();
runtime.rawMsg.push(msg);
try {
const m = JSON.parse(msg);

Check warning on line 121 in scripts/emulator-tests/functionsEmulatorRuntime.spec.ts

View workflow job for this annotation

GitHub Actions / lint (24)

Unsafe assignment of an `any` value
if (m.type) {

Check warning on line 122 in scripts/emulator-tests/functionsEmulatorRuntime.spec.ts

View workflow job for this annotation

GitHub Actions / lint (24)

Unsafe member access .type on an `any` value
runtime.sysMsg[m.type] = runtime.sysMsg[m.type] || [];

Check warning on line 123 in scripts/emulator-tests/functionsEmulatorRuntime.spec.ts

View workflow job for this annotation

GitHub Actions / lint (24)

Computed name [m.type] resolves to an any value

Check warning on line 123 in scripts/emulator-tests/functionsEmulatorRuntime.spec.ts

View workflow job for this annotation

GitHub Actions / lint (24)

Unsafe member access .type on an `any` value

Check warning on line 123 in scripts/emulator-tests/functionsEmulatorRuntime.spec.ts

View workflow job for this annotation

GitHub Actions / lint (24)

Computed name [m.type] resolves to an any value

Check warning on line 123 in scripts/emulator-tests/functionsEmulatorRuntime.spec.ts

View workflow job for this annotation

GitHub Actions / lint (24)

Unsafe member access .type on an `any` value
runtime.sysMsg[m.type].push(`text: ${m.text};data: ${JSON.stringify(m.data)}`);

Check warning on line 124 in scripts/emulator-tests/functionsEmulatorRuntime.spec.ts

View workflow job for this annotation

GitHub Actions / lint (24)

Unsafe member access .type on an `any` value
}
} catch {
// Carry on;
Expand Down Expand Up @@ -179,8 +181,20 @@
}

async function sendDebugBundle(runtime: Runtime, debug: FunctionsRuntimeBundle["debug"]) {
return new Promise((resolve) => {
runtime.proc.send(JSON.stringify(debug), resolve);
return new Promise<void>((resolve) => {
const onMessage = (message: Serializable) => {
const log = EmulatorLog.fromJSON(message.toString());
if (
log.level === "SYSTEM" &&
log.type === "runtime-status" &&
log.text === DEBUG_MSG_HANDLED
) {
runtime.proc.off("message", onMessage);
resolve();
}
};
runtime.proc.on("message", onMessage);
runtime.proc.send(JSON.stringify(debug));
});
}
Comment on lines 183 to 199

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

In the test helper sendDebugBundle, if the runtime process exits or crashes before sending the DEBUG_MSG_HANDLED log, the promise will hang indefinitely because there is no exit listener or reject handler. Additionally, if a non-JSON or malformed message is received, EmulatorLog.fromJSON will throw an unhandled exception and crash the test run. Adding reject to the promise, listening to the exit event, wrapping the JSON parsing in a try-catch block, and ensuring proper cleanup prevents these issues.

async function sendDebugBundle(runtime: Runtime, debug: FunctionsRuntimeBundle["debug"]) {
  return new Promise<void>((resolve, reject) => {
    const onMessage = (message: Serializable) => {
      try {
        const log = EmulatorLog.fromJSON(message.toString());
        if (
          log.level === "SYSTEM" &&
          log.type === "runtime-status" &&
          log.text === DEBUG_MSG_HANDLED
        ) {
          cleanup();
          resolve();
        }
      } catch (err) {
        // Ignore parsing errors for non-log messages
      }
    };
    const onExit = () => {
      cleanup();
      reject(new Error("Runtime process exited before handling the debug message"));
    };
    const cleanup = () => {
      runtime.proc.off("message", onMessage);
      runtime.proc.off("exit", onExit);
    };
    runtime.proc.on("message", onMessage);
    runtime.proc.once("exit", onExit);
    try {
      runtime.proc.send(JSON.stringify(debug), (err) => {
        if (err) {
          cleanup();
          reject(err);
        }
      });
    } catch (err) {
      cleanup();
      reject(err);
    }
  });
}


Expand Down
9 changes: 8 additions & 1 deletion src/emulator/functionsEmulatorRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@ import * as _ from "lodash";
import { EmulatorLog } from "./types";
import { getErrMsg, getErrStack } from "../error";
import { Constants } from "./constants";
import { findModuleRoot, FunctionsRuntimeBundle, SignatureType } from "./functionsEmulatorShared";
import {
DEBUG_MSG_HANDLED,
findModuleRoot,
FunctionsRuntimeBundle,
SignatureType,
} from "./functionsEmulatorShared";
import { compareVersionStrings, isLocalHost } from "./functionsEmulatorUtils";
import { EventUtils } from "./events/types";

Expand Down Expand Up @@ -802,6 +807,8 @@ async function handleMessage(message: string) {
new EmulatorLog("WARN", "runtime-warning", "Expected debug payload while in debug mode.");
}
}
// The parent waits for this before sending a request, since IPC and HTTP are not ordered.
new EmulatorLog("SYSTEM", "runtime-status", DEBUG_MSG_HANDLED).log();
}

async function main(): Promise<void> {
Expand Down
3 changes: 3 additions & 0 deletions src/emulator/functionsEmulatorShared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ export function getEventTenantId(
*/
export const EVENTARC_SOURCE_ENV = "EVENTARC_CLOUD_EVENT_SOURCE";

/** Text of the runtime-status log a Node runtime sends once it has handled a debug message. */
export const DEBUG_MSG_HANDLED = "debug-msg-handled";

export type SignatureType = "http" | "event" | "cloudevent";

export interface ParsedTriggerDefinition {
Expand Down
37 changes: 36 additions & 1 deletion src/emulator/functionsRuntimeWorker.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { expect } from "chai";
import { FunctionsRuntimeInstance, IPCConn } from "./functionsEmulator";
import { EventEmitter } from "events";
import { RuntimeWorker, RuntimeWorkerPool, RuntimeWorkerState } from "./functionsRuntimeWorker";
import { EmulatedTriggerDefinition } from "./functionsEmulatorShared";
import { DEBUG_MSG_HANDLED, EmulatedTriggerDefinition } from "./functionsEmulatorShared";
import { EmulatorLog, FunctionsExecutionMode } from "./types";
import { ChildProcess } from "child_process";

Expand Down Expand Up @@ -188,6 +188,41 @@ describe("FunctionsRuntimeWorker", () => {
expect(counter.counts.FINISHED).to.eql(1);
expect(counter.total).to.eql(5);
});

it("sendDebugMsg resolves only after the runtime confirms it handled the message", async () => {
const runtime = new MockRuntimeInstance();
runtime.process.send = ((msg: string, cb: (err: Error | null) => void) => {
cb(null);
return true;
}) as ChildProcess["send"];
const worker = new RuntimeWorker("trigger", runtime, {});

let resolved = false;
const sent = worker
.sendDebugMsg({ functionTarget: "fn", functionSignature: "http" })
.then(() => {
resolved = true;
});
await new Promise((r) => setImmediate(r));
expect(resolved).to.be.false;

runtime.events.emit("log", new EmulatorLog("SYSTEM", "runtime-status", DEBUG_MSG_HANDLED));
await sent;
expect(resolved).to.be.true;
});

it("sendDebugMsg rejects if the runtime exits before confirming", async () => {
const runtime = new MockRuntimeInstance();
runtime.process.send = ((msg: string, cb: (err: Error | null) => void) => {
cb(null);
return true;
}) as ChildProcess["send"];
const worker = new RuntimeWorker("trigger", runtime, {});

const sent = worker.sendDebugMsg({ functionTarget: "fn", functionSignature: "http" });
runtime.process.emit("exit");
await expect(sent).to.be.rejectedWith("exited before handling the debug message");
});
});

describe("RuntimeWorkerPool", () => {
Expand Down
29 changes: 26 additions & 3 deletions src/emulator/functionsRuntimeWorker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ import { randomUUID } from "crypto";

import { FunctionsRuntimeInstance } from "./functionsEmulator";
import { EmulatorLog, Emulators, FunctionsExecutionMode } from "./types";
import { EmulatedTriggerDefinition, FunctionsRuntimeBundle } from "./functionsEmulatorShared";
import {
DEBUG_MSG_HANDLED,
EmulatedTriggerDefinition,
FunctionsRuntimeBundle,
} from "./functionsEmulatorShared";
import { EventEmitter } from "events";
import { EmulatorLogger, ExtensionLogInfo } from "./emulatorLogger";
import { FirebaseError } from "../error";
Expand Down Expand Up @@ -117,11 +121,30 @@ export class RuntimeWorker {

sendDebugMsg(debug: FunctionsRuntimeBundle["debug"]): Promise<void> {
return new Promise((resolve, reject) => {
const onLog = (log: EmulatorLog) => {
if (
log.level === "SYSTEM" &&
log.type === "runtime-status" &&
log.text === DEBUG_MSG_HANDLED
) {
cleanup();
resolve();
}
};
const onExit = () => {
cleanup();
reject(new FirebaseError("Functions runtime exited before handling the debug message."));
};
const cleanup = () => {
this.runtime.events.off("log", onLog);
this.runtime.process.off("exit", onExit);
};
this.runtime.events.on("log", onLog);
this.runtime.process.once("exit", onExit);
this.runtime.process.send(JSON.stringify(debug), (err) => {
if (err) {
cleanup();
reject(err);
} else {
resolve();
}
});
});
Expand Down
Loading