Skip to content
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

App crash on using secondary firebase app on iOS #5134

Closed
DarshitaGoMmt opened this issue Apr 8, 2021 · 8 comments · Fixed by #5154
Closed

App crash on using secondary firebase app on iOS #5134

DarshitaGoMmt opened this issue Apr 8, 2021 · 8 comments · Fixed by #5154
Labels
resolution: fixed A fix has been merged into main. type: bug New bug report

Comments

@DarshitaGoMmt
Copy link

package.json-

    "react": "16.13.1",
    "react-native": "0.63.4",
    "@react-native-firebase/analytics": "11.2.0",
    "@react-native-firebase/app": "11.2.0",
    "@react-native-firebase/auth": "11.2.0",
    "@react-native-firebase/firestore": "11.2.0",
    "@react-native-firebase/messaging": "11.2.0",
    "@react-native-firebase/remote-config": "11.2.0",
const initGuestChatConnection = async () => { 
  if (firebase.apps.length < 2) {
    await firebase.initializeApp(GUEST_CHAT_FIREBASE_CONFIG, {
      name: GUEST_CHAT_FIREBASE_CONFIG.app_name // 'GUEST_CHAT'
    });
  }
};

const getGuestChatFirebaseInstance = () => {
  return firebase.app(GUEST_CHAT_FIREBASE_CONFIG.app_name);
};

const signInGuestChatFirebaseInstance = token => {
  return getGuestChatFirebaseInstance()
    .auth()
    .signInWithCustomToken(token);
};

const getGuestChatAuthResponse = () => {
  initGuestChatConnection().then(async () => {
    try {
        await signInGuestChatFirebaseInstance('token');
    } catch (error) {
        console.error(error);
    }
 });
};

When using auth-

Exception '*** -[__NSDictionaryM setObject:forKeyedSubscript:]: key cannot be nil' was thrown while invoking addAuthStateListener on target RNFBAuthModule with params (
"GUEST_CHAT"
)
image

This is working fine on Android but failing on iOS.

@DarshitaGoMmt DarshitaGoMmt added help: needs-triage Issue needs additional investigation/triaging. type: bug New bug report labels Apr 8, 2021
@mikehardy mikehardy added the Workflow: Needs Review Pending feedback or review from a maintainer. label Apr 8, 2021
@mikehardy
Copy link
Collaborator

Interesting! Can you make a single App.js I could throw into a clean project to reproduce this quickly? That's the best chance for a crash fix - +1 that you're using current versions of react-native-firebase but you ignored the rest of the template unfortunately so I can't tell if you have some other versioning issue (perhaps overriding firebase-ios-sdk to an old version? I can't say: you ignored the template)

@DarshitaGoMmt
Copy link
Author

DarshitaGoMmt commented Apr 10, 2021

@mikehardy Please find the required files as follows:

package.json

{
  "name": "FirebaseProject",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "react": "17.0.1",
    "react-native": "0.64.0",
    "@react-native-firebase/analytics": "11.2.0",
    "@react-native-firebase/app": "11.2.0",
    "@react-native-firebase/auth": "11.2.0",
    "@react-native-firebase/firestore": "11.2.0",
    "@react-native-firebase/messaging": "11.2.0",
    "@react-native-firebase/remote-config": "11.2.0",
    "react-native-codegen": "^0.0.7"
  },
  "devDependencies": {
    "@babel/core": "^7.13.15",
    "@babel/runtime": "^7.13.10",
    "@react-native-community/eslint-config": "^2.0.0",
    "babel-jest": "^26.6.3",
    "eslint": "^7.23.0",
    "jest": "^26.6.3",
    "metro-react-native-babel-preset": "^0.65.2",
    "react-test-renderer": "17.0.1"
  },
  "jest": {
    "preset": "react-native"
  }
}

Podfile

require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

platform :ios, '10.0'

target 'FirebaseProject' do
  config = use_native_modules!

  use_react_native!(
    :path => config[:reactNativePath],
    # to enable hermes on iOS, change `false` to `true` and then install pods
    :hermes_enabled => false
  )

  target 'FirebaseProjectTests' do
    inherit! :complete
    # Pods for testing
  end

  # Enables Flipper.
  #
  # Note that if you have use_frameworks! enabled, Flipper will not work and
  # you should disable the next line.
  use_flipper!()

  post_install do |installer|
    react_native_post_install(installer)
  end
end

App.js

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow strict-local
 */

import React, {useEffect} from 'react';
import {
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  useColorScheme,
  View,
} from 'react-native';

import {
  Colors,
  DebugInstructions,
  Header,
  LearnMoreLinks,
  ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
import firebase from './firebase';

const Section = ({children, title}) => {
  const isDarkMode = useColorScheme() === 'dark';
  return (
    <View style={styles.sectionContainer}>
      <Text
        style={[
          styles.sectionTitle,
          {
            color: isDarkMode ? Colors.white : Colors.black,
          },
        ]}>
        {title}
      </Text>
      <Text
        style={[
          styles.sectionDescription,
          {
            color: isDarkMode ? Colors.light : Colors.dark,
          },
        ]}>
        {children}
      </Text>
    </View>
  );
};

const firebaseConfig = {
  apiKey: 'XXXXXXXXXXXXXXXXXXXXXXX',
  authDomain: 'test-XXXXX.firebaseapp.com',
  databaseURL: 'https://test-XXXXXX.firebaseio.com',
  projectId: 'test-XXXXX',
  storageBucket: 'tes-XXXXX.appspot.com',
  messagingSenderId: 'XXXXXXXXXXXXX',
  appId: '1:XXXXXXXXX',
  app_name: 'TEST',
};

const initGuestChatConnection = async () => {
  // DEFAULT app will always be there
  console.log('Length', firebase.apps.length);
  if (firebase.apps.length < 2) {
    await firebase.initializeApp(firebaseConfig, {
      name: firebaseConfig.app_name,
    });
  }
};

const getGuestChatFirebaseInstance = () => {
  return firebase.app(firebaseConfig.app_name);
};

const signInGuestChatFirebaseInstance = token => {
  return getGuestChatFirebaseInstance().auth().signInWithCustomToken(token);
};

const App = () => {
  const isDarkMode = useColorScheme() === 'dark';

  const backgroundStyle = {
    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
  };
  useEffect(() => {
    initGuestChatConnection().then(async () => {
      console.log('Length', firebase.apps.length);
      // await signInGuestChatFirebaseInstance('token');
      getGuestChatFirebaseInstance()
        .firestore()
        .collection('Test')
        .doc()
        .get()
        .then(snapshot => {
          snapshot.forEach(x => {
            console.log('Data: ', x.data());
          });
        });
    });
  }, []);

  return (
    <SafeAreaView style={backgroundStyle}>
      <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
      <ScrollView
        contentInsetAdjustmentBehavior="automatic"
        style={backgroundStyle}>
        <Header />
        <View
          style={{
            backgroundColor: isDarkMode ? Colors.black : Colors.white,
          }}>
          <Section title="Step One">
            Edit <Text style={styles.highlight}>App.js</Text> to change this
            screen and then come back to see your edits.
          </Section>
          <Section title="See Your Changes">
            <ReloadInstructions />
          </Section>
          <Section title="Debug">
            <DebugInstructions />
          </Section>
          <Section title="Learn More">
            Read the docs to discover what to do next:
          </Section>
          <LearnMoreLinks />
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
  },
  highlight: {
    fontWeight: '700',
  },
});
export default App;

Screenshot of crashes:

While authorising it throwing error:
image

While accessing firestore collection:
image

@mikehardy
Copy link
Collaborator

This is not a complete self-contained App.js - you import firebase from './firebase' yet you have not included it

There is a lack of try/catch everywhere, meaning that when I correct the import above to import firebase from '@react-native-firebase/app'; I get unhandled promise rejections etc

Nevertheless, after hacking around on your App.js I can reproduce this, not sure what the problem is yet, but I can get the same redbox

Note that you can do:

  1. firebase.app('<secondary app name>').firestore() or
  2. firebase.app().firestore('<secondary app name>')

...according to the docs but if I try 2 it appears to attempt connection to the default app still, not the secondary one. So there may be more than one thing happening here.

Also note that I since you have publicly shared the API keys here you should consider that firebase project compromised - do not use it for anything important, make sure there is not a billing account connected to it and make sure to delete as soon as we are done troubleshooting.

mikehardy added a commit that referenced this issue Apr 10, 2021
Previously the exceptions were swallowed, meaning that initialization failures
were very difficult to diagnose, leading to developer confusion

Fixes #5134
@mikehardy
Copy link
Collaborator

@DarshitaGoMmt your secondary configuration is invalid, as a proximal cause - you need to use a valid app id for iOS I think

That is a project-specific problem, so I am going to close this issue, as a valid config will work.

The crash is also a derivative item, the root cause is that initializeApp on iOS was swallowing configuration errors, so you had no way of knowing your configuration was invalid, so you continued ahead and were actually using a null native secondary app

#5154 will fix that issue so that errors will be easy to see going forward. Until that fix is released you should incorporate the patches (via patch-package) from the PR artifact here: https://github.com/invertase/react-native-firebase/actions/runs/736591451

It does contain a few patches at this point as we have a queue of unreleased changes since v11.2.0, if you want to just reach in to node_modules/@react-native-firebase/app directly and make the 2-line change from the PR, then persist that with patch-package that would also work. But the whole patch-package will be what goes out in v11.3.0 so it should be fine also

@mikehardy mikehardy added resolution: fixed A fix has been merged into main. Resolution: Solution Provided and removed help: needs-triage Issue needs additional investigation/triaging. Resolution: No Template Workflow: Needs Review Pending feedback or review from a maintainer. Workflow: Waiting for User Response Blocked waiting for user response. labels Apr 10, 2021
@DarshitaGoMmt
Copy link
Author

DarshitaGoMmt commented Apr 11, 2021

@mikehardy The configuration has been copied from firestore project setting for a web app (which is working fine on Android). How can I ensure whether the config is valid or invalid?
Sorry for the inconvenience caused in identifying the import as I created firebase folder with index file for the same.
image

The config shared is created specifically for sharing the issue will delete the project once issue is resolved.

@varunon9
Copy link

@mikehardy As @DarshitaGoMmt mentioned, we are using same firebase config for our Android (via react-native-firebase @react-native-firebase/app) & web (via official firebase JS SDK - firebase/app) platform as well. It's working fine on both the platforms but not on ios. This config is generated by adding a web-app in our Firebase project which I think is okay for a secondary app.

@mikehardy
Copy link
Collaborator

mikehardy commented Apr 11, 2021

It's an invalid app Id, I saw the exception personally while reproducing it myself. Using an ios config worked.

mikehardy added a commit that referenced this issue Apr 11, 2021
Previously the exceptions were swallowed, meaning that initialization failures
were very difficult to diagnose, leading to developer confusion

Fixes #5134
@DarshitaGoMmt
Copy link
Author

DarshitaGoMmt commented Apr 11, 2021

@mikehardy Auth worked on trying with iOS based app config while on Android it worked with web app config also. Since on adding iOS app it provides GoogleService-info.plist so it created confusion as we don't add more than one GoogleService-info.plist. So what we did now is, extracted all config related info from GoogleService-info.plist and used it. This made secondary app worked on iOS!
Thanks for helping!

mikehardy added a commit that referenced this issue Apr 12, 2021
Previously the exceptions were swallowed, meaning that initialization failures
were very difficult to diagnose, leading to developer confusion

Fixes #5134
mikehardy added a commit that referenced this issue Apr 12, 2021
Previously the exceptions were swallowed, meaning that initialization failures
were very difficult to diagnose, leading to developer confusion

Fixes #5134
mikehardy added a commit that referenced this issue Apr 12, 2021
Previously the exceptions were swallowed, meaning that initialization failures
were very difficult to diagnose, leading to developer confusion

Fixes #5134
mikehardy added a commit that referenced this issue Apr 12, 2021
Previously the exceptions were swallowed, meaning that initialization failures
were very difficult to diagnose, leading to developer confusion

Fixes #5134
androidIsForVivek pushed a commit to androidIsForVivek/react-native-firebase that referenced this issue Aug 9, 2021
Previously the exceptions were swallowed, meaning that initialization failures
were very difficult to diagnose, leading to developer confusion

Fixes invertase#5134
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
resolution: fixed A fix has been merged into main. type: bug New bug report
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants