@fireemu/darwin-arm64 0.48.0 → 0.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @fireemu/darwin-arm64
2
2
 
3
3
  The [fireemu](https://www.npmjs.com/package/fireemu) daemon built for `darwin-arm64`
4
- (Rust target `aarch64-apple-darwin`), version 0.48.0.
4
+ (Rust target `aarch64-apple-darwin`), version 0.50.0.
5
5
 
6
6
  macOS 13 or newer on Apple silicon.
7
7
 
package/bin/fireemu CHANGED
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/bin/fireemu
3
- size: 37625312 bytes
4
- sha256: e64f635ee51fff04e993f996d666a3acb2a4bf344f81620a8fa35ad81fd6bd82
3
+ size: 38418704 bytes
4
+ sha256: 87163cc9eb348debbcb75e474e96e122a20a634891da8c11629ba5d72855eb81
@@ -28,7 +28,7 @@ function transform(source, name) {
28
28
  next = replaceOnce(
29
29
  next,
30
30
  "function encodeSSE(data) {",
31
- `function onCallHandler(options, handler, version) {\n\tconst fn = fireemuOriginalOnCallHandler(options, handler, version);\n\t${REGISTRY}.observe(fn, options);\n\treturn fn;\n}\nfunction encodeSSE(data) {`,
31
+ `function onCallHandler(options, handler, version) {\n\tconst fn = fireemuOriginalOnCallHandler(options, handler, version);\n\treturn ${REGISTRY}.observe(fn, options);\n}\nfunction encodeSSE(data) {`,
32
32
  "encodeSSE",
33
33
  );
34
34
  return next;
@@ -28,6 +28,8 @@ import { createRequire, register } from "node:module";
28
28
  import { dirname, join, parse as parsePath } from "node:path";
29
29
  import { pathToFileURL } from "node:url";
30
30
 
31
+ import { guardCallableWrapper } from "./nested-callable.mjs";
32
+
31
33
  /// `firebase-functions` majors whose callable internals this instrumentation is written for.
32
34
  const SUPPORTED_MAJORS = [6, 7];
33
35
 
@@ -187,15 +189,19 @@ export function instrumentCallables(sourceDir) {
187
189
  ].map((v) => String(v ?? "").toLowerCase());
188
190
 
189
191
  const options = new WeakMap();
192
+ // Returns the callable wrapper to use: the guarded wrapper, which refuses a credential the daemon
193
+ // did not verify when it runs inside a non-callable endpoint (nested-callable.mjs).
190
194
  const observe = (fn, opts) => {
191
- if (typeof fn !== "function" || options.has(fn)) return;
195
+ if (typeof fn !== "function" || options.has(fn)) return fn;
196
+ const guarded = guardCallableWrapper(fn);
192
197
  options.set(
193
- fn,
198
+ guarded,
194
199
  Object.freeze({
195
200
  enforceAppCheck: (opts ?? {}).enforceAppCheck === true,
196
201
  consumeAppCheckToken: consumeState((opts ?? {}).consumeAppCheckToken),
197
202
  }),
198
203
  );
204
+ return guarded;
199
205
  };
200
206
  const carry = (from, to) => {
201
207
  if (typeof to === "function" && !options.has(to) && options.has(from)) {
@@ -205,9 +211,7 @@ export function instrumentCallables(sourceDir) {
205
211
 
206
212
  const originalOnCallHandler = loaded.commonHttps.onCallHandler;
207
213
  loaded.commonHttps.onCallHandler = function onCallHandler(opts, handler, version_) {
208
- const fn = originalOnCallHandler.call(this, opts, handler, version_);
209
- observe(fn, opts);
210
- return fn;
214
+ return observe(originalOnCallHandler.call(this, opts, handler, version_), opts);
211
215
  };
212
216
 
213
217
  const originalWrapTrace = loaded.trace.wrapTraceContext;
@@ -22,10 +22,12 @@ import { createRuntimeClock } from "./clock.mjs";
22
22
  import { instrumentCallables } from "./callable-app-check.mjs";
23
23
  import { createAdminChannel, instrumentAdminAppCheck } from "./admin-app-check.mjs";
24
24
  import { removeAppCheckToken, withholdsAppCheckToken } from "./app-check-token.mjs";
25
+ import { markNonCallableRequest } from "./nested-callable.mjs";
25
26
  import { blockingFailure } from "./blocking-error.mjs";
26
27
  import { blockingEvent, loadIdentityParsers, portedIdentityParsers } from "./blocking-event.mjs";
27
28
  import { blockingResult } from "./blocking-response.mjs";
28
29
  import { boundLogMessage, createInvocationLogger } from "./log-context.mjs";
30
+ import { installTaskAuthEnvironment, runWithTaskAuth, takeTaskIdentityMarker } from "./task-auth.mjs";
29
31
  import { invocationFailure } from "./invocation-error.mjs";
30
32
  import { InvocationBudget, readFrames } from "./protocol.mjs";
31
33
  import { deliverSchedule, v1ScheduleContext } from "./schedule-delivery.mjs";
@@ -355,6 +357,7 @@ startupTrace('argv parsed');
355
357
  const sourceDir = resolve(args.source);
356
358
  startupTrace('source resolved');
357
359
  process.env.FUNCTIONS_EMULATOR = process.env.FUNCTIONS_EMULATOR || "true";
360
+ installTaskAuthEnvironment();
358
361
  process.env.FUNCTION_TARGET = process.env.FUNCTION_TARGET || "";
359
362
  process.env.FUNCTION_SIGNATURE_TYPE = process.env.FUNCTION_SIGNATURE_TYPE || "";
360
363
  process.env.K_SERVICE = process.env.K_SERVICE || "";
@@ -1395,6 +1398,13 @@ async function makeHttpServer(functions, manifest) {
1395
1398
  .send(`no HTTP function ${req.params.project}/${req.params.region}/${req.params.name}`);
1396
1399
  return;
1397
1400
  }
1401
+ // A request to a non-callable HTTP endpoint is marked in the strict profile, so that a callable
1402
+ // wrapper nested in it refuses a credential the daemon did not verify (nested-callable.mjs).
1403
+ markNonCallableRequest(req, {
1404
+ strict: strictProfile(),
1405
+ nonCallableHttp: spec.trigger?.type === "http" && spec.trigger.callable !== true,
1406
+ });
1407
+ const taskIdentity = takeTaskIdentityMarker(req);
1398
1408
  // Without App Check a callable that could consume a token never sees one, whichever path
1399
1409
  // the request took here (spec 13.4; app-check-token.mjs).
1400
1410
  if (withholdsAppCheckToken(spec, process.env)) removeAppCheckToken(req);
@@ -1461,6 +1471,9 @@ async function makeHttpServer(functions, manifest) {
1461
1471
  const payload = blockingResult(value, spec.trigger.eventType, HttpsErrors[0]);
1462
1472
  if (lifetime.canStart()) res.status(200).json(payload);
1463
1473
  }
1474
+ } else if (taskIdentity && strictProfile() && spec.trigger?.type === "tasks") {
1475
+ // In the strict profile, the daemon marker hides only the SDK's request.auth read.
1476
+ await runWithTaskAuth(() => fn(req, res));
1464
1477
  } else {
1465
1478
  await fn(req, res);
1466
1479
  }
@@ -0,0 +1,82 @@
1
+ // A callable's wrapper that runs inside an endpoint the daemon serves as something else.
2
+ //
3
+ // `onRequest(opts, onCall(opts, handler))` deploys the callable's code as a plain HTTPS function:
4
+ // discovery sees an `onRequest` endpoint (`httpsTrigger`, no `callableTrigger`), so the daemon does
5
+ // not treat it as a callable and forwards `Authorization` untouched, as it must for application
6
+ // code that verifies credentials itself. The wrapper inside then runs under `skipTokenVerification`
7
+ // (the trusted callable protocol) and decodes any Bearer without checking it, so an unsigned or
8
+ // malformed token became an identity (`uid: "x"`), where production's wrapper verifies the token and
9
+ // refuses it (FUNCTIONS-HTTP-CALLABLE-INGRESS, run 1: 401 for every unverified shape).
10
+ //
11
+ // In the strict profile the daemon therefore tells the runner whether the one `Authorization` field
12
+ // of a request to a non-callable HTTP endpoint is a Bearer of a user of the project it verified
13
+ // (`x-fireemu-credential-verified: 1`; the daemon removes every caller-supplied copy first). The
14
+ // runner marks such a request, and the callable wrapper, the one place that decodes credentials,
15
+ // receives a credential it cannot read as a Bearer when the daemon did not verify it. The wrapper
16
+ // then refuses it itself, with its own envelope and in its own order of checks, exactly as it does
17
+ // for any value that is not `Bearer <token>`. Nothing else changes: a plain `onRequest` function
18
+ // sees the request it always saw (the marker field is removed), and a real callable never carries
19
+ // the mark, because the daemon has already refused or verified its credential.
20
+
21
+ /// The field the daemon sets on a request to a non-callable HTTP endpoint in the strict profile.
22
+ export const VERIFIED_CREDENTIAL_HEADER = "x-fireemu-credential-verified";
23
+
24
+ const CONTEXT = Symbol.for("fireemu.endpointContext");
25
+
26
+ /// What a callable wrapper receives instead of an unverified credential: not `Bearer <token>`, so
27
+ /// the SDK reads it as an invalid credential without decoding it.
28
+ export const UNVERIFIED_CREDENTIAL = "fireemu-unverified-credential";
29
+
30
+ /// Reads and removes the daemon's marker, then marks the request when it is served by a
31
+ /// non-callable HTTP endpoint in the strict profile. Returns whether the request was marked.
32
+ export function markNonCallableRequest(req, { strict, nonCallableHttp }) {
33
+ const marker = req.headers?.[VERIFIED_CREDENTIAL_HEADER];
34
+ if (req.headers) delete req.headers[VERIFIED_CREDENTIAL_HEADER];
35
+ if (Array.isArray(req.rawHeaders)) {
36
+ const kept = [];
37
+ for (let i = 0; i + 1 < req.rawHeaders.length; i += 2) {
38
+ if (String(req.rawHeaders[i]).toLowerCase() !== VERIFIED_CREDENTIAL_HEADER) {
39
+ kept.push(req.rawHeaders[i], req.rawHeaders[i + 1]);
40
+ }
41
+ }
42
+ req.rawHeaders = kept;
43
+ }
44
+ if (!strict || !nonCallableHttp) return false;
45
+ Object.defineProperty(req, CONTEXT, {
46
+ value: Object.freeze({ credentialVerified: marker === "1" }),
47
+ configurable: true,
48
+ });
49
+ return true;
50
+ }
51
+
52
+ /// The request a callable wrapper should see: the request itself, or, when it was served by a
53
+ /// non-callable endpoint and carries a credential the daemon did not verify, a view of it whose
54
+ /// `Authorization` is [`UNVERIFIED_CREDENTIAL`]. The view leaves the caller's own request untouched.
55
+ export function requestForCallableWrapper(req) {
56
+ const context = req?.[CONTEXT];
57
+ if (!context || context.credentialVerified) return req;
58
+ const authorization = req.headers?.authorization;
59
+ if (typeof authorization !== "string" || authorization === "") return req;
60
+ return Object.create(req, {
61
+ headers: {
62
+ value: { ...req.headers, authorization: UNVERIFIED_CREDENTIAL },
63
+ enumerable: true,
64
+ },
65
+ });
66
+ }
67
+
68
+ /// A callable wrapper that reads its request through [`requestForCallableWrapper`]. The result keeps
69
+ /// the wrapper's own properties, which the SDK reads and extends after the wrapper is built.
70
+ export function guardCallableWrapper(wrapper) {
71
+ if (typeof wrapper !== "function") return wrapper;
72
+ const guarded = function (req, ...rest) {
73
+ return wrapper.call(this, requestForCallableWrapper(req), ...rest);
74
+ };
75
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(wrapper))) {
76
+ Reflect.defineProperty(guarded, key, descriptor);
77
+ }
78
+ for (const symbol of Object.getOwnPropertySymbols(wrapper)) {
79
+ Reflect.defineProperty(guarded, symbol, Object.getOwnPropertyDescriptor(wrapper, symbol));
80
+ }
81
+ return guarded;
82
+ }
@@ -0,0 +1,53 @@
1
+ // The daemon sets this marker only for strict-profile dispatches and removes caller-supplied copies.
2
+ // The runner removes it before the function sees the request. Only the SDK's first read is hidden,
3
+ // so the handler and its timers continue to see "true".
4
+ import { AsyncLocalStorage } from "node:async_hooks";
5
+
6
+ export const TASK_IDENTITY_HEADER = "x-fireemu-task-identity";
7
+ const scope = new AsyncLocalStorage();
8
+ const installed = new WeakSet();
9
+
10
+ export function takeTaskIdentityMarker(req) {
11
+ const marker = req.headers?.[TASK_IDENTITY_HEADER];
12
+ if (req.headers) delete req.headers[TASK_IDENTITY_HEADER];
13
+ if (Array.isArray(req.rawHeaders)) {
14
+ const kept = [];
15
+ for (let i = 0; i + 1 < req.rawHeaders.length; i += 2) {
16
+ if (String(req.rawHeaders[i]).toLowerCase() !== TASK_IDENTITY_HEADER) {
17
+ kept.push(req.rawHeaders[i], req.rawHeaders[i + 1]);
18
+ }
19
+ }
20
+ req.rawHeaders = kept;
21
+ }
22
+ return marker === "1";
23
+ }
24
+
25
+ export function runWithTaskAuth(run) {
26
+ return scope.run({ hideNext: true }, run);
27
+ }
28
+
29
+ export function installTaskAuthEnvironment(target = process) {
30
+ if (installed.has(target)) return;
31
+ const real = target.env;
32
+ target.env = new Proxy(real, {
33
+ get: (env, prop) => {
34
+ const store = scope.getStore();
35
+ if (prop === "FUNCTIONS_EMULATOR" && store?.hideNext) {
36
+ store.hideNext = false;
37
+ return undefined;
38
+ }
39
+ return env[prop];
40
+ },
41
+ // Writes go to the real environment by plain assignment: the real `process.env` refuses a descriptor-based write.
42
+ set: (env, prop, value) => {
43
+ env[prop] = value;
44
+ return true;
45
+ },
46
+ deleteProperty: (env, prop) => delete env[prop],
47
+ defineProperty: (env, prop, descriptor) => {
48
+ if ("value" in descriptor) env[prop] = descriptor.value;
49
+ return true;
50
+ },
51
+ });
52
+ installed.add(target);
53
+ }
@@ -0,0 +1,110 @@
1
+ """Auth blocking tokens: run the SDK's production verification with the daemon's public keys.
2
+
3
+ SECURITY-SENSITIVE. The SDK skips signature and audience checks in the Auth emulator. When the daemon supplies
4
+ its public keys, this module confines production verification and certificate responses to the SDK verifier;
5
+ without the environment variable the SDK's emulator behavior is unchanged.
6
+ """
7
+
8
+ import contextvars
9
+ import importlib.metadata
10
+ import json
11
+
12
+ ENVIRONMENT_VARIABLE = "FIREEMU_AUTH_BLOCKING_JWKS"
13
+ NOTE_VERSION = "0.6.0"
14
+
15
+
16
+ class VerificationUnavailable(Exception):
17
+ pass
18
+
19
+
20
+ def parse_keys(text) -> dict[str, str] | None:
21
+ """Build the certificate mapping consumed by the SDK from the daemon's public JWKS."""
22
+ import jwt
23
+ from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
24
+
25
+ try:
26
+ document = json.loads(text)
27
+ except (ValueError, TypeError):
28
+ return None
29
+ entries = document.get("keys") if isinstance(document, dict) else None
30
+ if not isinstance(entries, list) or not entries:
31
+ return None
32
+ keys = {}
33
+ for entry in entries:
34
+ if not isinstance(entry, dict) or entry.get("kty") != "RSA" or not isinstance(entry.get("kid"), str) or not entry["kid"] or not isinstance(entry.get("n"), str) or not isinstance(entry.get("e"), str):
35
+ continue
36
+ try:
37
+ keys[entry["kid"]] = jwt.PyJWK(entry).key.public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo).decode("ascii")
38
+ except Exception:
39
+ continue
40
+ return keys or None
41
+
42
+
43
+ def install_from_environment(environ) -> bool:
44
+ """Install the SDK-only verification hook when the daemon provides usable public keys."""
45
+ if ENVIRONMENT_VARIABLE not in environ:
46
+ return False
47
+ value = environ.pop(ENVIRONMENT_VARIABLE)
48
+ try:
49
+ keys = parse_keys(value)
50
+ if not keys:
51
+ raise VerificationUnavailable("no usable public keys")
52
+ from firebase_admin import _auth_utils
53
+ from firebase_functions.private import token_verifier
54
+ from google.auth.exceptions import TransportError
55
+
56
+ stock = token_verifier._JWTVerifier
57
+ if not isinstance(stock, type) or not callable(token_verifier._auth_utils.is_emulated) or not token_verifier._token_gen.ID_TOKEN_CERT_URI:
58
+ raise VerificationUnavailable("unsupported SDK")
59
+ cert_url = token_verifier._token_gen.ID_TOKEN_CERT_URI
60
+ data = json.dumps(keys).encode()
61
+ active = contextvars.ContextVar("fireemu_auth_blocking_verification", default=False)
62
+
63
+ class AuthUtilsView:
64
+ def is_emulated(self):
65
+ return False if active.get() else _auth_utils.is_emulated()
66
+
67
+ def __getattr__(self, name):
68
+ return getattr(_auth_utils, name)
69
+
70
+ class Verifier(stock):
71
+ def verify(self, token, request):
72
+ def certificate_request(url, method="GET", body=None, headers=None, timeout=None, **kwargs):
73
+ if url != cert_url:
74
+ raise TransportError("unexpected certificate URL")
75
+ return type("CertificateResponse", (), {"status": 200, "headers": {}, "data": data})()
76
+
77
+ marker = active.set(True)
78
+ try:
79
+ if isinstance(token, (str, bytes)) and token:
80
+ _, payload = self._decode_unverified(token.encode() if isinstance(token, str) else token)
81
+ if not isinstance(payload.get("aud"), str):
82
+ raise self._invalid_token_error('Firebase Auth Blocking token has an invalid "aud" claim.')
83
+ return super().verify(token, certificate_request)
84
+ finally:
85
+ active.reset(marker)
86
+
87
+ auth_utils_view = AuthUtilsView()
88
+ token_verifier._JWTVerifier = Verifier
89
+ token_verifier._auth_utils = auth_utils_view
90
+ return True
91
+ except VerificationUnavailable:
92
+ raise
93
+ except Exception as error:
94
+ raise VerificationUnavailable("SDK hook installation failed") from error
95
+
96
+
97
+ def default_note(functions_version) -> str | None:
98
+ if functions_version != NOTE_VERSION:
99
+ return None
100
+ return '[functions] note: firebase-functions (Python) 0.6.0 accepts only a "run.app" audience in an Auth blocking token, while firebase-tools 15.28.2 registers the function\'s cloudfunctions.net address, so in production every Auth blocking function written with it fails with 503 "Error code: 47"; fireemu skips that check by default and runs it, so this function passes here (functions.authBlockingToken: "production", set by productionExact, reproduces the production failure)'
101
+
102
+
103
+ def announce_default_note(stderr):
104
+ try:
105
+ version = importlib.metadata.version("firebase-functions")
106
+ except Exception:
107
+ version = None
108
+ note = default_note(version)
109
+ if note is not None:
110
+ stderr.write(note + "\n")
@@ -6,7 +6,7 @@ import platform
6
6
  import sys
7
7
  import traceback
8
8
 
9
- from . import appcheck
9
+ from . import appcheck, blocking
10
10
  from .dispatch import Dispatcher
11
11
  from .environment import EnvironmentGate, load_local_secrets
12
12
  from .framing import FrameWriter, ProtocolError, read_frame
@@ -30,10 +30,12 @@ def load_codebase(source: str) -> dict:
30
30
 
31
31
 
32
32
  def serve(
33
- functions: dict, codebase: str, secret: str, stdin, writer: FrameWriter, gate: EnvironmentGate | None = None, app_check_verified: bool = False
33
+ functions: dict, codebase: str, secret: str, stdin, writer: FrameWriter, gate: EnvironmentGate | None = None, app_check_verified: bool = False, blocking_verified: bool = False
34
34
  ) -> int:
35
35
  """Says hello, then serves frames from `stdin` until `shutdown` or the end of the stream."""
36
36
  manifest = build_manifest(functions, app_check_verified)
37
+ if not blocking_verified and any(spec["trigger"]["type"] == "blockingAuth" for spec in manifest["functions"]):
38
+ blocking.announce_default_note(sys.stderr)
37
39
  server = None
38
40
  port = None
39
41
  if any(spec["trigger"]["type"] in HTTP_TRIGGERS for spec in manifest["functions"]):
@@ -84,9 +86,16 @@ def run(argv) -> int:
84
86
  return 1
85
87
  # Before any user code runs, so the Admin SDK's App Check service is built against the emulator's keys.
86
88
  app_check_verified = appcheck.install_from_environment(os.environ)
89
+ try:
90
+ blocking_verified = blocking.install_from_environment(os.environ)
91
+ except blocking.VerificationUnavailable as error:
92
+ sys.stderr.write(f"[functions] error: Auth blocking token verification was requested but is unavailable ({error}); not serving\n")
93
+ return 1
87
94
  try:
88
95
  functions = load_codebase(args.source)
89
96
  except BaseException: # a failing import in user code is reported with its traceback
90
97
  traceback.print_exc()
91
98
  return 1
99
+ if blocking_verified:
100
+ return serve(functions, args.codebase, secret, sys.stdin.buffer, writer, gate, app_check_verified, blocking_verified=True)
92
101
  return serve(functions, args.codebase, secret, sys.stdin.buffer, writer, gate, app_check_verified)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fireemu/darwin-arm64",
3
- "version": "0.48.0",
3
+ "version": "0.50.0",
4
4
  "description": "The fireemu daemon for darwin-arm64",
5
5
  "homepage": "https://fireemu.github.io/fireemu/",
6
6
  "repository": {