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

[🐛][Android] Calling firebase.appCheck().activate() throws an exception #5981

Closed
5 of 9 tasks
rawatnaresh opened this issue Dec 31, 2021 · 3 comments · Fixed by #6056
Closed
5 of 9 tasks

[🐛][Android] Calling firebase.appCheck().activate() throws an exception #5981

rawatnaresh opened this issue Dec 31, 2021 · 3 comments · Fixed by #6056
Labels
help: needs-triage Issue needs additional investigation/triaging. plugin: app-check Firebase AppCheck type: bug New bug report

Comments

@rawatnaresh
Copy link
Contributor

Issue

Calling firebase.appCheck().activate() throws an exception : 👇 👇 👇

Click To Expand index.js

index.js:

import {AppRegistry} from 'react-native';
import {firebase} from '@react-native-firebase/app-check';

import App from './App';
import {name as appName} from './app.json';

const appCheck = firebase.appCheck();

appCheck
  .activate()
  .then(() => console.log('App Check:: Activated'))
  .catch(() => console.log('App Check:: Error'));

AppRegistry.registerComponent(appName, () => App);

Screenshot_20211231-102840_MyApp5

SafetyNet is enabled in firebase

Screen Shot 2021-12-31 at 10 47 55

To reproduce this issue 🧑‍💻

  • npx react-native init MyApp --template react-native-template-typescript
  • yarn add @react-native-firebase/app
  • yarn add @react-native-firebase/app-check
  • Setup firebase project
  • yarn start
  • yarn android

Project Files

Javascript

Click To Expand

package.json:

{
  "name": "myapp5",
  "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 . --ext .js,.jsx,.ts,.tsx"
  },
  "dependencies": {
    "@react-native-firebase/app": "^14.1.0",
    "@react-native-firebase/app-check": "^14.1.0",
    "react": "17.0.2",
    "react-native": "0.66.4"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "@babel/runtime": "^7.12.5",
    "@react-native-community/eslint-config": "^2.0.0",
    "@types/jest": "^26.0.23",
    "@types/react-native": "^0.66.4",
    "@types/react-test-renderer": "^17.0.1",
    "@typescript-eslint/eslint-plugin": "^5.7.0",
    "@typescript-eslint/parser": "^5.7.0",
    "babel-jest": "^26.6.3",
    "eslint": "^7.14.0",
    "jest": "^26.6.3",
    "metro-react-native-babel-preset": "^0.66.2",
    "react-test-renderer": "17.0.2",
    "typescript": "^4.4.4"
  },
  "resolutions": {
    "@types/react": "^17"
  },
  "jest": {
    "preset": "react-native",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ]
  }
}

firebase.json for react-native-firebase v6:

# N/A

iOS

Click To Expand

ios/Podfile:

  • I'm not using Pods
  • [] I'm using Pods and my Podfile looks like:
# N/A

AppDelegate.m:

// N/A


Android

Click To Expand

Have you converted to AndroidX?

  • my application is an AndroidX application?
  • I am using android/gradle.settings jetifier=true for Android compatibility?
  • I am using the NPM package jetifier for react-native compatibility?

android/build.gradle:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = "30.0.2"
        minSdkVersion = 21
        compileSdkVersion = 30
        targetSdkVersion = 30
        ndkVersion = "21.4.7075529"
    }
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:4.2.2")
        classpath 'com.google.gms:google-services:4.3.10'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenCentral()
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }

        google()
        maven { url 'https://www.jitpack.io' }
    }
}

android/app/build.gradle:

// N/A

android/settings.gradle:

apply plugin: "com.android.application"
apply plugin: 'com.google.gms.google-services' // <- Add this line

import com.android.build.OutputFile

/**
 * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
 * and bundleReleaseJsAndAssets).
 * These basically call `react-native bundle` with the correct arguments during the Android build
 * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
 * bundle directly from the development server. Below you can see all the possible configurations
 * and their defaults. If you decide to add a configuration block, make sure to add it before the
 * `apply from: "../../node_modules/react-native/react.gradle"` line.
 *
 * project.ext.react = [
 *   // the name of the generated asset file containing your JS bundle
 *   bundleAssetName: "index.android.bundle",
 *
 *   // the entry file for bundle generation. If none specified and
 *   // "index.android.js" exists, it will be used. Otherwise "index.js" is
 *   // default. Can be overridden with ENTRY_FILE environment variable.
 *   entryFile: "index.android.js",
 *
 *   // https://reactnative.dev/docs/performance#enable-the-ram-format
 *   bundleCommand: "ram-bundle",
 *
 *   // whether to bundle JS and assets in debug mode
 *   bundleInDebug: false,
 *
 *   // whether to bundle JS and assets in release mode
 *   bundleInRelease: true,
 *
 *   // whether to bundle JS and assets in another build variant (if configured).
 *   // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
 *   // The configuration property can be in the following formats
 *   //         'bundleIn${productFlavor}${buildType}'
 *   //         'bundleIn${buildType}'
 *   // bundleInFreeDebug: true,
 *   // bundleInPaidRelease: true,
 *   // bundleInBeta: true,
 *
 *   // whether to disable dev mode in custom build variants (by default only disabled in release)
 *   // for example: to disable dev mode in the staging build type (if configured)
 *   devDisabledInStaging: true,
 *   // The configuration property can be in the following formats
 *   //         'devDisabledIn${productFlavor}${buildType}'
 *   //         'devDisabledIn${buildType}'
 *
 *   // the root of your project, i.e. where "package.json" lives
 *   root: "../../",
 *
 *   // where to put the JS bundle asset in debug mode
 *   jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
 *
 *   // where to put the JS bundle asset in release mode
 *   jsBundleDirRelease: "$buildDir/intermediates/assets/release",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in debug mode
 *   resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in release mode
 *   resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
 *
 *   // by default the gradle tasks are skipped if none of the JS files or assets change; this means
 *   // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
 *   // date; if you have any other folders that you want to ignore for performance reasons (gradle
 *   // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
 *   // for example, you might want to remove it from here.
 *   inputExcludes: ["android/**", "ios/**"],
 *
 *   // override which node gets called and with what additional arguments
 *   nodeExecutableAndArgs: ["node"],
 *
 *   // supply additional arguments to the packager
 *   extraPackagerArgs: []
 * ]
 */

project.ext.react = [
    enableHermes: false,  // clean and rebuild if changing
]

apply from: "../../node_modules/react-native/react.gradle"

/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = false

/**
 * The preferred build flavor of JavaScriptCore.
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US.  Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'org.webkit:android-jsc:+'

/**
 * Whether to enable the Hermes VM.
 *
 * This should be set on project.ext.react and mirrored here.  If it is not set
 * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
 * and the benefits of using Hermes will therefore be sharply reduced.
 */
def enableHermes = project.ext.react.get("enableHermes", false);

/**
 * Architectures to build native code for in debug.
 */
def nativeArchitectures = project.getProperties().get("reactNativeDebugArchitectures")

android {
    ndkVersion rootProject.ext.ndkVersion

    compileSdkVersion rootProject.ext.compileSdkVersion

    defaultConfig {
        applicationId "com.myapp5"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
            if (nativeArchitectures) {
                ndk {
                    abiFilters nativeArchitectures.split(',')
                }
            }
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://reactnative.dev/docs/signed-apk-android.
            signingConfig signingConfigs.debug
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }

    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // https://developer.android.com/studio/build/configure-apk-splits.html
            // Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc.
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        defaultConfig.versionCode * 1000 + versionCodes.get(abi)
            }

        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    //noinspection GradleDynamicVersion
    implementation "com.facebook.react:react-native:+"  // From node_modules

    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"

    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.fbjni'
    }

    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }

    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }

    if (enableHermes) {
        def hermesPath = "../../node_modules/hermes-engine/android/";
        debugImplementation files(hermesPath + "hermes-debug.aar")
        releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
        implementation jscFlavor
    }
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.implementation
    into 'libs'
}

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)

MainApplication.java:

// N/A

AndroidManifest.xml:

<!-- N/A -->


Environment

Click To Expand

react-native info output:

 System:
    OS: macOS 11.4
    CPU: (4) x64 Intel(R) Core(TM) i7-5650U CPU @ 2.20GHz
    Memory: 59.61 MB / 8.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 16.13.1 - ~/.nodenv/versions/16.13.1/bin/node
    Yarn: 1.22.17 - ~/.nodenv/versions/16.13.1/bin/yarn
    npm: 8.1.2 - ~/.nodenv/versions/16.13.1/bin/npm
    Watchman: 2021.11.01.00 - /usr/local/bin/watchman
  Managers:
    CocoaPods: 1.11.2 - /usr/local/bin/pod
  SDKs:
    iOS SDK:
      Platforms: iOS 14.4, DriverKit 20.2, macOS 11.1, tvOS 14.3, watchOS 7.2
    Android SDK:
      API Levels: 28, 29, 30
      Build Tools: 28.0.3, 29.0.2, 29.0.3, 30.0.2, 30.0.3
      System Images: android-28 | Google APIs Intel x86 Atom, android-28 | Google Play Intel x86 Atom, android-29 | Google APIs Intel x86 Atom, android-30 | Google APIs Intel x86 Atom
      Android NDK: 22.1.7171670
  IDEs:
    Android Studio: 2020.3 AI-203.7717.56.2031.7678000
    Xcode: 12.4/12D4e - /usr/bin/xcodebuild
  Languages:
    Java: 1.8.0_282 - /usr/bin/javac
  npmPackages:
    @react-native-community/cli: Not Found
    react: 17.0.2 => 17.0.2 
    react-native: 0.66.4 => 0.66.4 
    react-native-macos: Not Found
  npmGlobalPackages:
    *react-native*: Not Found
  • Platform that you're experiencing the issue on:
    • iOS
    • Android
    • iOS but have not tested behavior on Android
    • Android but have not tested behavior on iOS
    • Both
  • *react-native-firebase version you're using that has this issue: *
    • 14.1.0
  • Firebase module(s) you're using that has the issue:
    • @react-native-firebase/app-check
  • *Are you using TypeScript? *
    • Y & 4.4.4


@rawatnaresh rawatnaresh added help: needs-triage Issue needs additional investigation/triaging. type: bug New bug report labels Dec 31, 2021
@mikehardy
Copy link
Collaborator

Hi there!
The module should not crash, that is an error, I will investigate it and fix it.
However, you should not be blocked by this - you're using the API incorrectly vs stated parameter requirements, the first one is non-null:

activate(
siteKeyOrProvider: string | AppCheckProvider,
isTokenAutoRefreshEnabled?: boolean,
): Promise<void>;

You may always consult our e2e tests in order to see how we expect usage to go:

await firebase.appCheck().activate('ignored', false);

Also the documentation shows whether a parameter is required or not and should be examined: https://rnfirebase.io/reference/app-check#activate

I'm going to leave this open because we should be more tolerant in what we expect and how we message expectation violations in the API usage but I'll assume you can move forward with this information?

@mikehardy mikehardy added Workflow: Needs Review Pending feedback or review from a maintainer. plugin: app-check Firebase AppCheck labels Dec 31, 2021
@rawatnaresh
Copy link
Contributor Author

I'm sorry that I missed it.

Calling activate('Provider', false) works as expected. However, calling activate('Provider') without the second parameter still throws the same error even though it's marked as optional.

isTokenAutoRefreshEnabled?: boolean,

Also there are no examples in App check Usage Documentation and also no link to the API reference page like rest of the usage pages.

Allow me update the usage page when I get it working on both iOS and android.

Thank you!

@mikehardy
Copy link
Collaborator

Very strange with regard to the usage docs etc, clearly something is not right. Thanks for mentioning that the second supposed-to-be-optional parameter also has problems, I'll clean that as well as I sweep through this. Glad you are unblocked at least, there is one happy path blazed through the module that I'm certain really does work :-), glad you are on it now

mikehardy added a commit that referenced this issue Feb 6, 2022
previously, the required string argument was not validated, and
the optional boolean argument was not supplied to native, causing
an android native crash if not supplied

omitting the string now correctly throws an error, and omitting the
token refresh boolean will default correctly to app check token refresh
as configured in firebase.json, app-wide data collection if app check
does not have a config, and the default true if there is no config

Fixes #5981 - thanks to @rawatnaresh for catching this!
mikehardy added a commit that referenced this issue Feb 6, 2022
previously, the required string argument was not validated, and
the optional boolean argument was not supplied to native, causing
an android native crash if not supplied

omitting the string now correctly throws an error, and omitting the
token refresh boolean will default correctly to app check token refresh
as configured in firebase.json, app-wide data collection if app check
does not have a config, and the default true if there is no config

Fixes #5981 - thanks to @rawatnaresh for catching this!
@mikehardy mikehardy removed the Workflow: Needs Review Pending feedback or review from a maintainer. label Feb 6, 2022
mikehardy added a commit that referenced this issue Feb 7, 2022
previously, the required string argument was not validated, and
the optional boolean argument was not supplied to native, causing
an android native crash if not supplied

omitting the string now correctly throws an error, and omitting the
token refresh boolean will default correctly to app check token refresh
as configured in firebase.json, app-wide data collection if app check
does not have a config, and the default true if there is no config

Fixes #5981 - thanks to @rawatnaresh for catching this!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help: needs-triage Issue needs additional investigation/triaging. plugin: app-check Firebase AppCheck type: bug New bug report
Projects
None yet
2 participants