@fireemu/darwin-arm64 0.71.2 → 0.72.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.71.2.
4
+ (Rust target `aarch64-apple-darwin`), version 0.72.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: 38999232 bytes
4
- sha256: f2511d38151e811180aabaddc2f80aa2a72590c12f54105e6adaecfb756fd7ab
3
+ size: 39065392 bytes
4
+ sha256: a3010199ec073eea4f9459176611d1126118c1b140084a65cc3448ff81817530
@@ -477,7 +477,13 @@ async function loadCodebase() {
477
477
  }
478
478
  }
479
479
  const entry = resolve(sourceDir, main);
480
- if (!existsSync(entry)) throw new Error(`functions entry point ${entry} does not exist`);
480
+ if (!existsSync(entry)) {
481
+ const hasTsConfig = existsSync(resolve(sourceDir, "tsconfig.json"));
482
+ const hint = hasTsConfig
483
+ ? ` (tsconfig.json found; build the codebase first, e.g. \`npm run build\` or \`tsc --watch\`)`
484
+ : "";
485
+ throw new Error(`functions entry point ${entry} does not exist${hint}`);
486
+ }
481
487
  startupTrace('user module import start');
482
488
  const mod = await import(pathToFileURL(entry).href);
483
489
  startupTrace('user module import end');
@@ -180,7 +180,16 @@ class LoopbackKeyClient:
180
180
  return self._keys[kid]
181
181
 
182
182
 
183
- def _emulator_service(stock, url: str):
183
+ _ACTIVE_RUNTIME_CLOCK = None
184
+
185
+
186
+ def set_runtime_clock(runtime_clock) -> None:
187
+ """Register the runner's emulator clock so App Check token lifetime matches session time."""
188
+ global _ACTIVE_RUNTIME_CLOCK
189
+ _ACTIVE_RUNTIME_CLOCK = runtime_clock
190
+
191
+
192
+ def _emulator_service(stock, url: str, runtime_clock=None):
184
193
  """The Admin SDK's App Check service, keyed to `url` and without credentials or a way to reach Google.
185
194
 
186
195
  The stock service builds an authorised HTTP client in its constructor (`app.credential.get_credential()`), which
@@ -189,10 +198,12 @@ def _emulator_service(stock, url: str):
189
198
  the keys fetched by `LoopbackKeyClient`, consumption refused, and two claim checks the emulator always satisfies.
190
199
  The audience rule stays the stock SDK's (`projects/<projectId>`).
191
200
  """
201
+ import jwt as _jwt
192
202
  from firebase_admin import exceptions
193
203
 
194
204
  class EmulatorAppCheckService(stock):
195
205
  _JWKS_URL = url
206
+ _RUNTIME_CLOCK = runtime_clock
196
207
 
197
208
  def __init__(self, app):
198
209
  project_id = app.project_id
@@ -207,10 +218,33 @@ def _emulator_service(stock, url: str):
207
218
  self._http_client = None
208
219
 
209
220
  def _decode_and_verify(self, token, signing_key):
210
- payload = super()._decode_and_verify(token, signing_key)
211
- exp = payload.get("exp")
212
- if isinstance(exp, bool) or not isinstance(exp, (int, float)):
213
- raise ValueError('The provided App Check token has no "exp" (expiration) claim.')
221
+ clock = self._RUNTIME_CLOCK if self._RUNTIME_CLOCK is not None else _ACTIVE_RUNTIME_CLOCK
222
+ if clock is not None:
223
+ # Verify signature and audience via PyJWT, then enforce iat/exp strictly against
224
+ # the emulator session clock (matches crates/fireemu-core-app-check/src/verify.rs).
225
+ payload = _jwt.decode(
226
+ token,
227
+ getattr(signing_key, "key", signing_key),
228
+ algorithms=["RS256"],
229
+ audience=self._scoped_project_id,
230
+ options={"verify_iat": False, "verify_exp": False, "verify_nbf": False},
231
+ )
232
+ emulator_now = clock.current_instant_nanos() / 1_000_000_000
233
+ iat = payload.get("iat")
234
+ exp = payload.get("exp")
235
+ if isinstance(iat, bool) or not isinstance(iat, (int, float)):
236
+ raise ValueError('The provided App Check token has no "iat" (issued at) claim.')
237
+ if iat > emulator_now:
238
+ raise _jwt.ImmatureSignatureError("The token is not yet valid (iat)")
239
+ if isinstance(exp, bool) or not isinstance(exp, (int, float)):
240
+ raise ValueError('The provided App Check token has no "exp" (expiration) claim.')
241
+ if exp <= emulator_now:
242
+ raise _jwt.ExpiredSignatureError("Signature has expired")
243
+ else:
244
+ payload = super()._decode_and_verify(token, signing_key)
245
+ exp = payload.get("exp")
246
+ if isinstance(exp, bool) or not isinstance(exp, (int, float)):
247
+ raise ValueError('The provided App Check token has no "exp" (expiration) claim.')
214
248
  issuer = payload.get("iss")
215
249
  match = _ISSUER.fullmatch(issuer) if isinstance(issuer, str) else None
216
250
  if match is None:
@@ -234,7 +268,7 @@ def _emulator_service(stock, url: str):
234
268
  return EmulatorAppCheckService
235
269
 
236
270
 
237
- def install_jwks_hook(url: str) -> bool:
271
+ def install_jwks_hook(url: str, runtime_clock=None) -> bool:
238
272
  """Replaces the Admin SDK's App Check service with one keyed to `url`. False when this SDK is not the one that
239
273
  replacement was written for, or PyJWT is older than the tested floor (the runner then announces nothing, and the
240
274
  daemon keeps removing the header)."""
@@ -245,7 +279,7 @@ def install_jwks_hook(url: str) -> bool:
245
279
  return False
246
280
  if not all(hasattr(stock, name) for name in _REQUIRED_ATTRIBUTES) or not _pyjwt_supported():
247
281
  return False
248
- app_check._AppCheckService = _emulator_service(stock, url)
282
+ app_check._AppCheckService = _emulator_service(stock, url, runtime_clock=runtime_clock)
249
283
  return True
250
284
 
251
285
 
@@ -8,6 +8,7 @@ without the environment variable the SDK's emulator behavior is unchanged.
8
8
  import contextvars
9
9
  import importlib.metadata
10
10
  import json
11
+ import os
11
12
 
12
13
  ENVIRONMENT_VARIABLE = "FIREEMU_AUTH_BLOCKING_JWKS"
13
14
  NOTE_VERSION = "0.6.0"
@@ -101,6 +102,8 @@ def default_note(functions_version) -> str | None:
101
102
 
102
103
 
103
104
  def announce_default_note(stderr):
105
+ if os.environ.get("FIREEMU_SUPPRESS_BLOCKING_NOTE") == "1":
106
+ return
104
107
  try:
105
108
  version = importlib.metadata.version("firebase-functions")
106
109
  except Exception:
@@ -0,0 +1,77 @@
1
+ """Anonymous credential fallback for Firebase Admin / Google Cloud clients inside fireemu runners.
2
+
3
+ The daemon sets `GOOGLE_APPLICATION_CREDENTIALS` to a non-existent `no-credentials.json` inside
4
+ an empty sandbox directory so no function can pick up ambient host credentials or talk to real
5
+ Google APIs. Unlike the Node Admin SDK, Python's `firebase_admin.firestore.client()` calls
6
+ `google.auth.default()` even when `FIRESTORE_EMULATOR_HOST` is set, raising
7
+ `DefaultCredentialsError`.
8
+
9
+ When the sandbox sentinel is active and at least one emulator host environment variable is set,
10
+ this hook falls back to `google.auth.credentials.AnonymousCredentials()` on `DefaultCredentialsError`.
11
+ `AnonymousCredentials` never attaches an `Authorization` header and never contacts OAuth token
12
+ endpoints, preserving the no-ADC guarantee while letting emulator-targeted SDK clients initialize.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ from collections.abc import Mapping
19
+
20
+ _EMULATOR_HOST_VARS = (
21
+ "FIRESTORE_EMULATOR_HOST",
22
+ "FIREBASE_DATABASE_EMULATOR_HOST",
23
+ "FIREBASE_AUTH_EMULATOR_HOST",
24
+ "FIREBASE_STORAGE_EMULATOR_HOST",
25
+ "PUBSUB_EMULATOR_HOST",
26
+ "STORAGE_EMULATOR_HOST",
27
+ )
28
+
29
+
30
+ def _should_install(environ: Mapping[str, str]) -> bool:
31
+ creds = environ.get("GOOGLE_APPLICATION_CREDENTIALS", "")
32
+ if not creds:
33
+ return False
34
+ if os.path.basename(creds) != "no-credentials.json" or os.path.exists(creds):
35
+ return False
36
+ return any(bool(environ.get(var)) for var in _EMULATOR_HOST_VARS)
37
+
38
+
39
+ def _project_id(environ: Mapping[str, str]) -> str | None:
40
+ return (
41
+ environ.get("GOOGLE_CLOUD_PROJECT")
42
+ or environ.get("GCLOUD_PROJECT")
43
+ or environ.get("GOOGLE_CLOUD_QUOTA_PROJECT")
44
+ )
45
+
46
+
47
+ def install_from_environment(environ: Mapping[str, str]) -> bool:
48
+ """Install the anonymous credential fallback when running in the fireemu no-ADC sandbox."""
49
+ if not _should_install(environ):
50
+ return False
51
+ try:
52
+ import google.auth
53
+ from google.auth.credentials import AnonymousCredentials
54
+ from google.auth.exceptions import DefaultCredentialsError
55
+ except ImportError:
56
+ return False
57
+
58
+ if getattr(google.auth.default, "_fireemu_anonymous_fallback", False):
59
+ return True
60
+
61
+ original_default = google.auth.default
62
+
63
+ def _wrapped_default(*args, **kwargs):
64
+ try:
65
+ return original_default(*args, **kwargs)
66
+ except DefaultCredentialsError:
67
+ if _should_install(os.environ):
68
+ return AnonymousCredentials(), _project_id(os.environ)
69
+ raise
70
+
71
+ _wrapped_default._fireemu_anonymous_fallback = True # type: ignore[attr-defined]
72
+ google.auth.default = _wrapped_default
73
+
74
+ # firebase_admin.credentials imports google.auth at module level and calls google.auth.default()
75
+ # inside ApplicationDefault.get_credential(), so patching google.auth.default covers both
76
+ # firebase_admin and direct google-cloud-* clients.
77
+ return True
@@ -6,17 +6,27 @@ failing invocation still holds its place in the secret gate, and a failure to ma
6
6
  """
7
7
 
8
8
  import inspect
9
+ import os
9
10
  import traceback
10
11
 
11
12
 
13
+ def rewrite_snapshot_paths(text: str) -> str:
14
+ """Replace temporary snapshot directory paths with the original user source path when known."""
15
+ snapshot = os.environ.get("FIREEMU_SNAPSHOT_SOURCE")
16
+ original = os.environ.get("FIREEMU_ORIGINAL_SOURCE")
17
+ if snapshot and original and snapshot != original:
18
+ return text.replace(snapshot, original)
19
+ return text
20
+
21
+
12
22
  def describe(error: BaseException) -> tuple[str, str]:
13
23
  """`(traceback text, short text)` of `error`; never raises, whatever the error's methods do."""
14
24
  try:
15
- diagnostic = "".join(traceback.format_exception(error))
25
+ diagnostic = rewrite_snapshot_paths("".join(traceback.format_exception(error)))
16
26
  except BaseException:
17
27
  diagnostic = f"{type(error).__name__}: (the error could not be formatted)\n"
18
28
  try:
19
- text = str(error) or type(error).__name__
29
+ text = rewrite_snapshot_paths(str(error) or type(error).__name__)
20
30
  except BaseException:
21
31
  text = type(error).__name__
22
32
  return diagnostic, text
@@ -6,7 +6,7 @@ import platform
6
6
  import sys
7
7
  import traceback
8
8
 
9
- from . import appcheck, blocking
9
+ from . import appcheck, blocking, credentials, diagnostics
10
10
  from .clock import RuntimeClock, from_environment as clock_from_environment
11
11
  from .dispatch import Dispatcher
12
12
  from .environment import EnvironmentGate, load_local_secrets
@@ -161,6 +161,8 @@ def run(argv) -> int:
161
161
  sys.stderr.write(f"[functions] {error}\n")
162
162
  return 1
163
163
  inspector_port = _start_debugpy_from_environment(os.environ)
164
+ credentials.install_from_environment(os.environ)
165
+ appcheck.set_runtime_clock(runtime_clock)
164
166
  # Before any user code runs, so the Admin SDK's App Check service is built against the emulator's keys.
165
167
  app_check_verified = appcheck.install_from_environment(os.environ)
166
168
  try:
@@ -171,7 +173,7 @@ def run(argv) -> int:
171
173
  try:
172
174
  functions = load_codebase(args.source)
173
175
  except BaseException: # a failing import in user code is reported with its traceback
174
- traceback.print_exc()
176
+ sys.stderr.write(diagnostics.rewrite_snapshot_paths(traceback.format_exc()))
175
177
  return 1
176
178
  # A dedicated runner (`--function`) names its function; otherwise the call is the one the daemon has always seen.
177
179
  options: dict = {"runtime_clock": runtime_clock, "inspector_port": inspector_port}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fireemu/darwin-arm64",
3
- "version": "0.71.2",
3
+ "version": "0.72.0",
4
4
  "description": "The fireemu daemon for darwin-arm64",
5
5
  "homepage": "https://fireemu.github.io/fireemu/",
6
6
  "repository": {