Skip to content

Firebase Auth SDK rejects the Auth emulator over a tailnet address on a physical iOS device (GTMSessionFetcher localhost-only policy) #11730

Closed

Description

@formed2forge

Symptom

On a local dev harness reached over a tailnet address (Tailscale CGNAT range, 100.64.0.0/10), any Firebase Auth SDK call that talks to the Auth emulator directly (not via our own backend) fails immediately with:

FirebaseAuthException code=network-request-failed
message=Network error (such as timeout, interrupted connection or unreachable host) has occurred.

Confirmed via an in-app file probe bracketing _tokenGateway.forceRefresh() (FirebaseAuth.instance.currentUser?.getIdTokenResult(true)), on firebase_auth/FirebaseAuth pod 11.10.0. Reproduces on every attempt, ~3 fast retries (150-600ms apart, not a hang), zero requests ever reach the backend or the emulator's access log — the rejection happens before anything hits the wire.

Root cause — a Firebase SDK-internal restriction, not ATS

This is not an App Transport Security / Info.plist issue. Ruled out directly: added NSAllowsArbitraryLoads (in addition to the existing NSAllowsLocalNetworking, which only covers .local/RFC 1918 ranges — the actual gap for a CGNAT address) and the exact same failure reproduced identically afterward.

The real cause, confirmed by firebase-ios-sdk#7342 (same exact error, same class of setup — Auth Emulator reached over a local network IP from a physical device): Firebase Auth's iOS SDK uses GTMSessionFetcher for its own networking, which enforces its own insecure-scheme allowlist, independent of the app's ATS configuration:

"Insecure fetch request has a scheme (http) not found in fetcher allowedInsecureSchemes"

By default this only permits plain HTTP to localhost/127.0.0.1. Any other host — including a Tailscale tailnet IP — is rejected at the SDK layer before ATS or the network stack are even reached. This explains the full pattern precisely:

  • Every other network call in the app (via Dart's http package, backend/http/shared.dart) works fine to the same tailnet host.
  • Only Firebase Auth SDK's own calls against the Auth emulator (useAuthEmulator(host, port)) fail — because those specifically route through GTMSessionFetcher's stricter policy.

Why this matters

Any local-dev workflow that runs the app on a physical iOS device (not the simulator) and reaches the harness over a network address rather than literal localhost — which is the only way to test against a real device at all, since the harness binds loopback only — cannot complete Firebase Auth token refreshes. This blocks anything that needs a fresh ID token: normal token expiry/refresh during a session, and in our case, blocked an onboarding step (PATCH /v1/users/language) that needed a freshly-refreshed token.

Possible directions (maintainer call — not proposing a specific one)

  • The standard workaround for this exact SDK limitation is a USB port-forward (e.g. iproxy) so the auth emulator appears as 127.0.0.1:<port> from the device's own perspective, satisfying GTMSessionFetcher's localhost-only check while the traffic still reaches the host machine. This would need to be wired into the local dev harness's device-testing docs/tooling.
  • Alternatively, serve the Auth emulator over HTTPS with a device-trusted certificate — more invasive, avoids the USB dependency.
  • Document this as a known limitation for anyone testing the mobile app on a physical device against the local harness, so the next person doesn't re-diagnose it from scratch.

Environment

macOS, local dev harness (make dev-up), physical iPhone over Tailscale (not simulator), firebase_auth/FirebaseAuth pod 11.10.0. Confirmed via file-based probes (profile builds have no console output for print()/debugPrint()) bracketing getAuthHeader(), makeApiCall(), and _refreshIdTokenOnce()'s catch blocks.

Activity

  1. formed2forge commented on Aug 17, 2026

    @formed2forge
    ContributorAuthor

    Correcting my own root-cause analysis above: the GTMSessionFetcher localhost-only explanation is wrong, and I'd rather retract it than leave it misleading anyone. The symptom is real and still unexplained; the diagnosis was not.

    I originally reasoned from firebase-ios-sdk#7342 (same error, same setup) plus having ruled out ATS. But #7342 is from 2021, and the SDK has since fixed exactly this. Reading the vendored Pods source instead of inferring:

    FirebaseAuth/Sources/Swift/Backend/AuthBackendRPCIssuer.swift — when an emulator is configured, both flags are set, not just the localhost one:

    let fetcher = fetcherService.fetcher(with: request)
    if let _ = requestConfiguration.emulatorHostAndPort {
      fetcher.allowLocalhostRequest = true
      fetcher.allowedInsecureSchemes = ["http"]     // permits http to ANY host
    }

    And GTMSessionFetcher checks the scheme allowlist first, short-circuiting before the host is ever examined (Sources/Core/GTMSessionFetcher.m, in the !isSecure branch):

    for (NSString *allowedScheme in _allowedInsecureSchemes) {
      if (requestScheme != nil &&
          [requestScheme caseInsensitiveCompare:allowedScheme] == NSOrderedSame) {
        allowRequest = YES;
        break;                    // host never inspected
      }
    }
    if (!allowRequest) {
      // only NOW does the IsLocalhost(host) check happen
    }

    So with "http" in allowedInsecureSchemes there is no host restriction at all — a tailnet IP is as acceptable as localhost.

    I also checked the token-refresh path specifically, since that is where this reproduced rather than at sign-in. SecureTokenService.requestAccessToken issues via backend.call(with: request) on a SecureTokenRequest carrying the same requestConfiguration, so it lands in the same AuthBackendRPCIssuer above and gets the same allowlist. There is no separate, less-permissive fetcher for refresh.

    Versions this was verified against, from app/ios/Podfile.lock: FirebaseAuth 11.10.0, GTMSessionFetcher/Core 3.5.0.

    This also means the workaround I suggested (an iproxy USB port-forward) should not be implemented — it targets a cause that does not exist. Worth noting for anyone who finds this later: iproxy forwards Mac→device over usbmuxd anyway, whereas this would have required the reverse direction (127.0.0.1 on the phone reaching the Mac), and iOS has no public adb reverse equivalent.

    What still stands from the original report:

    • The failure is real and reproducible: tapping Confirm on language selection does nothing for ~5 minutes (ApiClient.requestTimeoutWrite).
    • Every token refresh fails fast — ~150-600ms, not a hang — with FirebaseAuthException code=network-request-failed.
    • ATS is not the cause: adding NSAllowsArbitraryLoads to Info-Dev.plist reproduced the identical failure. (Still worth carrying, since NSAllowsLocalNetworking alone never covers the Tailscale CGNAT range 100.64.0.0/10.)

    Additionally eliminated since filing:

    • Not a missing --dart-define. Generated.xcconfig's DART_DEFINES decodes to OMI_FIREBASE_AUTH_EMULATOR_HOST=100.105.2.5, not env.dart's 127.0.0.1 fallback, and the built App.framework has every API URL baked as http://100.105.2.5:8000/..., confirming that define list was the one compiled in.
    • Not an asymmetry in how the emulator port is exposed. tailscale serve maps :9099 identically to :8000 (plain TCP → 127.0.0.1:<port>, no TLS termination), and curl http://<tailnet-ip>:9099/emulator/v1/projects/<project>/config from the host returns the emulator's real config JSON in ~60ms.

    Still open, and where I'd look next: whether useAuthEmulator() ran at all in that build (it sits behind a profile gate), and what URL the fetcher actually targeted — both were inferred, never observed. I'll update here once instrumented.

    Retitling suggestion for maintainers: the current title asserts the disproven cause, so something like "iOS device: Firebase Auth emulator token refresh fails with network-request-failed over a tailnet address" would describe the symptom without prejudging it.

  2. formed2forge commented on Aug 17, 2026

    @formed2forge
    ContributorAuthor

    Root cause found, and it is a real app bug — not an SDK bug and not environmental. It is App Transport Security, which both my original report and my correction above wrongly eliminated.

    The bug

    app/ios/Runner/Info-Dev.plist declares both ATS keys:

    <key>NSAppTransportSecurity</key>
    <dict>
      <key>NSAllowsLocalNetworking</key><true/>
      <key>NSAllowsArbitraryLoads</key><true/>
    </dict>

    Per Apple's documentation, when NSAllowsArbitraryLoads appears alongside NSAllowsLocalNetworking (or NSAllowsArbitraryLoadsInWebContent / NSAllowsArbitraryLoadsForMedia), the arbitrary-loads key is ignored on any OS version that understands the newer keys. So on iOS 26/27 only NSAllowsLocalNetworking is in force — and that covers .local, unqualified hostnames and link-local addresses, but not the Tailscale CGNAT range 100.64.0.0/10.

    Result: every plain-HTTP NSURLSession request to a tailnet-hosted dev backend is refused by ATS before it leaves the device.

    Why only Firebase Auth breaks

    This is what made it so confusing to diagnose — the app talks to the same host on :8000 all day without trouble:

    • Every other network call goes through the Dart http package, i.e. dart:io sockets, which bypass ATS entirely.
    • Firebase Auth alone uses GTMSessionFetcher on NSURLSession, which is subject to ATS.

    So a single asymmetry produced "only Firebase Auth fails, to a host everything else reaches fine" — which reads exactly like an SDK bug, and is why I filed it as one.

    The fix

    Delete the redundant key so NSAllowsArbitraryLoads actually takes effect:

    /usr/libexec/PlistBuddy -c "Delete :NSAppTransportSecurity:NSAllowsLocalNetworking" \
      app/ios/Runner/Info-Dev.plist

    Dev-only plist, so nothing changes for release builds.

    Evidence

    A native URLSession GET to the Auth emulator's own config endpoint, run from didFinishLaunchingWithOptions, logging error.domain / error.code. Identical build, identical URL, only the plist differing:

    BEFORE  NSURLSession shared          FAILED after 6ms  domain=NSURLErrorDomain code=-1022
                    desc=The resource could not be loaded because the App Transport Security
                         policy requires the use of a secure connection.
    BEFORE  NSURLSession fresh-ephemeral FAILED after 3ms  (identical)
    
    AFTER   NSURLSession shared          OK status=200 in 80ms bytes=99
    AFTER   NSURLSession fresh-ephemeral OK status=200 in 82ms bytes=99
    

    -1022 is NSURLErrorAppTransportSecurityRequiresSecureConnection. In the app's own logs, network-request-failed — the only failure mode observed across two debugging sessions — drops to zero occurrences after the change.

    (Both a shared and a fresh ephemeral session were tested because AuthBackendRPCIssuer sets reuseSession = false; they behave identically, so the per-request-session detail is not involved.)

    Why "ATS is ruled out" kept coming back wrong

    Worth recording, because the test that was supposed to settle it actively misled:

    1. Adding NSAllowsArbitraryLoads to disprove the ATS theory silently did nothing, because adding it next to NSAllowsLocalNetworking makes it a no-op. The negative result looked like evidence and was an artifact.
    2. Confirming the key is present in the built Runner.app/Info.plist is not the same as confirming it is in force.
    3. "Every other request to this host works" felt conclusive but was irrelevant — those requests never went through ATS at all.

    The reliable test is to issue an NSURLSession request from native code and log error.domain/error.code. A dart:io-based probe tells you nothing about ATS.

    Impact

    Any community developer running the backend somewhere that is not .local or RFC 1918 hits this — which includes every Tailscale user, the setup the local dev harness docs point people toward. The failure is silent: network-request-failed with no indication that a policy refused the connection locally.

    Suggested retitle: "iOS: ATS blocks Firebase Auth emulator over a tailnet address — NSAllowsArbitraryLoads nullified by NSAllowsLocalNetworking in Info-Dev.plist".

    Also worth a note for whoever picks this up: FirebaseAuthException code=network-request-failed is not evidence of a network problem. AuthBackend.swift maps any error returning no body data onto that code, so a locally-refused request is indistinguishable from a genuine network failure at the Dart layer — the real information is in NSUnderlyingErrorKey, which FlutterFire does not surface.

    Verified end to end

    With the plist change in place, the full flow now works on device against the local dev harness — sign-in via the local-dev button, then onboarding start to finish. From the same run:

    • Zero network-request-failed and zero internal-error after the fix.
    • A valid ID token for the first time in this investigation: hasAuthToken=true isExpirationDateValid=true.
    • PATCH /v1/users/onboarding 200 OK (×2) and PATCH /v1/users/geolocation 200 OK in the backend log, plus normal authenticated traffic afterwards (/v1/conversations, /v1/goals/all, /v1/folders, /v2/apps, …), all 200.
    • A /v4/listen websocket session ran and closed cleanly.

    Two unrelated things were also in the way once ATS was fixed, noted here in case anyone else hits them:

    1. A stale Firebase session in the shared App-Group Keychain kept being restored, and a full app uninstall does not clear it — keychain access groups outlive the app container. A one-shot FirebaseAuth.instance.signOut() at startup cleared it.
    2. network-request-failed had masked it, but the emulator was rejecting that stale refresh token; once ATS was fixed the error changed to internal-error, which is what pointed at the session rather than the network.
  3. formed2forge commented on Aug 18, 2026

    @formed2forge
    ContributorAuthor

    Correcting my own report: the root cause in the title and body of this issue is wrong. The symptom was real and is now fixed, but the explanation was not. Leaving it uncorrected would send the next person after a non-existent SDK restriction.

    What I claimed, and why it's wrong

    I claimed Firebase Auth's iOS SDK enforces a host allowlist permitting plain HTTP only to literal localhost/127.0.0.1, citing firebase-ios-sdk#7342, and therefore rejects a tailnet address before the network stack is reached. That is not true of the versions this app pins. Disproven by reading the vendored Pods source rather than inferring from the issue tracker.

    Pods/FirebaseAuth/FirebaseAuth/Sources/Swift/Backend/AuthBackendRPCIssuer.swift:62-65 — when an emulator is configured, both flags are set, not just the localhost one:

    if let _ = requestConfiguration.emulatorHostAndPort {
      fetcher.allowLocalhostRequest = true
      fetcher.allowedInsecureSchemes = ["http"]     // permits http to ANY host
    }

    And GTMSessionFetcher checks the scheme allowlist first, short-circuiting before the host is examined (Pods/GTMSessionFetcher/Sources/Core/GTMSessionFetcher.m:600-635):

    for (NSString *allowedScheme in _allowedInsecureSchemes) {
      if (... caseInsensitiveCompare:allowedScheme] == NSOrderedSame) {
        allowRequest = YES;
        break;                    // host never inspected
      }
    }
    if (!allowRequest) { /* only NOW does the IsLocalhost(host) check happen */ }

    With "http" in allowedInsecureSchemes there is no host restriction at all. Issue #7342 is from 2021; that allowedInsecureSchemes line in the emulator branch is the SDK's fix for it. Pinned versions from Podfile.lock: FirebaseAuth 11.10.0, GTMSessionFetcher/Core 3.5.0. The token-refresh path is covered by the same code — SecureTokenService.requestAccessToken issues through backend.call(with:) on a request carrying the same requestConfiguration, so it lands in the same issuer and gets the same allowlist. There is no separate, less-permissive fetcher for refresh.

    The actual cause: App Transport Security

    Info-Dev.plist declared NSAllowsArbitraryLoads alongside NSAllowsLocalNetworking. Per Apple's documentation, that combination makes NSAllowsArbitraryLoads a no-op — only the local-networking rules remain in force, and those do not cover the Tailscale CGNAT range 100.64.0.0/10. So every plain-HTTP NSURLSession request to the harness was refused before it left the device.

    Firebase Auth was the only visibly affected caller because it alone uses NSURLSession. The rest of the app talks to the harness over dart:io sockets, which bypass ATS entirely — which is exactly why ATS looked ruled out for two rounds of debugging: everything except auth kept working.

    Proof, rather than inference: a native NSURLSession probe against the harness went from code=-1022 (the ATS refusal) to status=200 after removing the redundant key, and network-request-failed dropped to zero. End-to-end verification followed — local-dev sign-in completed and PATCH /v1/users/onboarding returned 200 from the harness backend.

    Blast radius is narrower than this issue implies

    NSAllowsLocalNetworking does cover RFC 1918 addresses. The documented setup tells contributors to point a device at "your Mac's LAN address", which is RFC 1918 — so the documented path would never have hit this. It only bites when the harness is reached over a non-RFC-1918 address such as a Tailscale/CGNAT one, which is what I was doing.

    Two follow-on blockers cleared along the way, in case they save someone else the time: a stale Keychain session survives a full app uninstall (a one-shot signOut() clears it), and local-dev sign-in had been dropped from the branch under test and needed reapplying on both app and backend.

    Retitling or closing this in favour of a correctly-scoped issue is probably the right move — I did not want to do either unilaterally on a report that others may have already read.

  4. formed2forge commented on Aug 18, 2026

    @formed2forge
    ContributorAuthor

    Correction to my comment above, on one point of fact that matters if you go looking at the file.

    main's app/ios/Runner/Info-Dev.plist declares only NSAllowsLocalNetworking:

    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsLocalNetworking</key>
        <true/>
    </dict>

    It does not declare both keys, as I wrote. The fix is therefore to replace that key with NSAllowsArbitraryLoads in the dev-only plist, not to delete a redundant one.

    The "these two keys cannot coexist" point still stands and is still worth knowing — but it is the reason the obvious fix fails, not the original defect: adding NSAllowsArbitraryLoads alongside NSAllowsLocalNetworking makes the former a documented no-op on any OS that understands the newer key, so the CGNAT host stays blocked and the fix appears to do nothing. That was the state of my debugging tree, which I incorrectly described as the shipped state.

    The diagnosis is otherwise unchanged: NSAllowsLocalNetworking covers .local, unqualified hostnames and link-local addresses — never 100.64.0.0/10 — so NSURLSession requests to a tailnet-hosted harness are refused with NSURLErrorDomain code=-1022 before leaving the device, and only Firebase Auth is affected because everything else uses dart:io sockets, which bypass ATS.

  5. aryanorastar commented on Sep 20, 2026

    @aryanorastar
    Collaborator

    Closing as already fixed on current main.

    #11652 merged; current main Info-Dev.plist ATS dict is NSAllowsArbitraryLoads only (comment explains not combining with NSAllowsLocalNetworking). Tailscale CGNAT Auth-emulator path addressed.

  6. moved this from Someday to In review in omi TODO / bountieson Sep 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions