diff --git a/.bacon.yml b/.bacon.yml index a8f2903..8d519ed 100644 --- a/.bacon.yml +++ b/.bacon.yml @@ -49,12 +49,12 @@ test_suites: sort_order: '5' timeout: '10' criteria: MERGE - queue_name: small + queue_name: al2023 - name: snyk script_path: /root/okta/okta-client-javascript/scripts/bacon script_name: snyk sort_order: '7' timeout: '200' criteria: MAINLINE - queue_name: small + queue_name: al2023 trigger: AUTO diff --git a/.circleci/config.yml b/.circleci/config.yml index dd074b9..ba91e24 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -152,6 +152,53 @@ jobs: path: packages/react-native-platform/ios/.build destination: react-native-platform-ios-build-artifacts + # e2e-oauth-android-tests: + # executor: + # name: android/android_machine + # resource_class: large + # tag: default + # environment: + # GRADLE_OPTS: -Xmx4g + # steps: + # - checkout + # - eng-platform-helpers/step-load-dependencies + + # - run: + # name: Verify secrets loaded + # command: | + # if [ -z "${USERNAME}" ]; then echo "ERROR: USERNAME not loaded"; exit 1; fi + # echo "All secrets loaded successfully" + + # - restore_cache: + # keys: + # - gradle-e2e-oauth-{{ checksum "e2e/apps/react-native-oidc/android/app/build.gradle" }} + # - gradle-e2e-oauth- + + # - run: + # name: Setup Node and install dependencies + # command: | + # npm i -g yarn@1.22.22 + # yarn install --frozen-lockfile + + # - run: + # name: Run OIDC Test App E2E tests + # command: | + # cd e2e/apps/react-native-oidc/android + # ./gradlew connectedAndroidTest + + # - save_cache: + # key: gradle-e2e-oauth-{{ checksum "e2e/apps/react-native-oidc/android/app/build.gradle" }} + # paths: + # - ~/.gradle + # - .gradle + + # - store_test_results: + # path: e2e/apps/react-native-oidc/android/app/build/outputs/androidTest-results + + # - store_artifacts: + # path: e2e/apps/react-native-oidc/android/app/build/reports + # destination: e2e-oauth-android-test-reports + workflows: version: 2 build_and_test: @@ -159,4 +206,10 @@ workflows: - test-rn-webcrypto-android - test-rn-webcrypto-ios - test-rn-platform-android - # - test-rn-platform-ios + + # - eng-platform-helpers/job-secrets-obtain: + # name: cache-username + # secret_key: "USERNAME" + # - e2e-oauth-android-tests: + # requires: + # - cache-username diff --git a/e2e/apps/react-native-oidc/.gitignore b/e2e/apps/react-native-oidc/.gitignore index 9516583..4884c27 100644 --- a/e2e/apps/react-native-oidc/.gitignore +++ b/e2e/apps/react-native-oidc/.gitignore @@ -9,7 +9,6 @@ dist/ web-build/ expo-env.d.ts ios/ -android/ # Native .kotlin/ diff --git a/e2e/apps/react-native-oidc/android/.gitignore b/e2e/apps/react-native-oidc/android/.gitignore new file mode 100644 index 0000000..55ee0bf --- /dev/null +++ b/e2e/apps/react-native-oidc/android/.gitignore @@ -0,0 +1,17 @@ +# OSX +# +.DS_Store + +# Android/IntelliJ +# +build/ +.idea +.gradle +local.properties +*.iml +*.hprof +.cxx/ + +# Bundle artifacts +*.jsbundle +.claude/ \ No newline at end of file diff --git a/e2e/apps/react-native-oidc/android/app/build.gradle b/e2e/apps/react-native-oidc/android/app/build.gradle new file mode 100644 index 0000000..2e56b57 --- /dev/null +++ b/e2e/apps/react-native-oidc/android/app/build.gradle @@ -0,0 +1,246 @@ +apply plugin: "com.android.application" +apply plugin: "org.jetbrains.kotlin.android" +apply plugin: "com.facebook.react" + +def projectRoot = rootDir.getAbsoluteFile().getParentFile().getAbsolutePath() + +def envVars = [ + 'USERNAME': '', + 'PASSWORD': '', + 'NATIVE_SCHEME_URI': '' +] + +// Load test configuration from testenv file +def testenvFile = file('../../../../../testenv') +if (testenvFile.exists()) { + println("📋 Loading testenv from: ${testenvFile.absolutePath}") + testenvFile.eachLine { line -> + line = line.trim() + if (!line.startsWith('#') && line.contains('=')) { + def (key, value) = line.split('=', 2) + key = key.trim() + value = value.trim().replaceAll('^"|"$', '') + + println("$key is set") + if (envVars.containsKey(key)) { + println("$key is set in map") + envVars[key] = value + } + } + } +} + +// Load (and override existing) test configuration from environment variables +envVars.each { envVar, v -> + def value = System.getenv(envVar) + if (value) { + envVars[envVar] = value + } + + if (!envVars[envVar]) { + throw new GradleException(""" + ERROR: Required environment variable not set: $envVar + + Please set the following environment variables: + ${envVars.keySet().join('\n ')} + """.stripIndent()) + } +} + + +/** + * This is the configuration block to customize your React Native Android app. + * By default you don't need to apply any configuration, just uncomment the lines you need. + */ +react { + entryFile = file(["node", "-e", "require('expo/scripts/resolveAppEntry')", projectRoot, "android", "absolute"].execute(null, rootDir).text.trim()) + reactNativeDir = new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsoluteFile() + hermesCommand = new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/sdks/hermesc/%OS-BIN%/hermesc" + codegenDir = new File(["node", "--print", "require.resolve('@react-native/codegen/package.json', { paths: [require.resolve('react-native/package.json')] })"].execute(null, rootDir).text.trim()).getParentFile().getAbsoluteFile() + + enableBundleCompression = (findProperty('android.enableBundleCompression') ?: false).toBoolean() + // Use Expo CLI to bundle the app, this ensures the Metro config + // works correctly with Expo projects. + cliFile = new File(["node", "--print", "require.resolve('@expo/cli', { paths: [require.resolve('expo/package.json')] })"].execute(null, rootDir).text.trim()) + bundleCommand = "export:embed" + + /* Folders */ + // The root of your project, i.e. where "package.json" lives. Default is '../..' + // root = file("../../") + // The folder where the react-native NPM package is. Default is ../../node_modules/react-native + // reactNativeDir = file("../../node_modules/react-native") + // The folder where the react-native Codegen package is. Default is ../../node_modules/@react-native/codegen + // codegenDir = file("../../node_modules/@react-native/codegen") + + /* Variants */ + // The list of variants to that are debuggable. For those we're going to + // skip the bundling of the JS bundle and the assets. By default is just 'debug'. + // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants. + // debuggableVariants = ["liteDebug", "prodDebug"] + + /* Bundling */ + // A list containing the node command and its flags. Default is just 'node'. + // nodeExecutableAndArgs = ["node"] + + // + // The path to the CLI configuration file. Default is empty. + // bundleConfig = file(../rn-cli.config.js) + // + // The name of the generated asset file containing your JS bundle + // bundleAssetName = "MyApplication.android.bundle" + // + // The entry file for bundle generation. Default is 'index.android.js' or 'index.js' + // entryFile = file("../js/MyApplication.android.js") + // + // A list of extra flags to pass to the 'bundle' commands. + // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle + // extraPackagerArgs = [] + + /* Hermes Commands */ + // The hermes compiler command to run. By default it is 'hermesc' + // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc" + // + // The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map" + // hermesFlags = ["-O", "-output-source-map"] + + /* Autolinking */ + autolinkLibrariesWithApp() +} + +/** + * Set this to true in release builds to optimize the app using [R8](https://developer.android.com/topic/performance/app-optimization/enable-app-optimization). + */ +def enableMinifyInReleaseBuilds = (findProperty('android.enableMinifyInReleaseBuilds') ?: false).toBoolean() + +/** + * The preferred build flavor of JavaScriptCore (JSC) + * + * 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 = 'io.github.react-native-community:jsc-android:2026004.+' + +android { + ndkVersion rootProject.ext.ndkVersion + + buildToolsVersion rootProject.ext.buildToolsVersion + compileSdk rootProject.ext.compileSdkVersion + + namespace 'com.anonymous.reporeactnativeoidc' + defaultConfig { + applicationId 'com.anonymous.reporeactnativeoidc' + minSdkVersion rootProject.ext.minSdkVersion + targetSdkVersion rootProject.ext.targetSdkVersion + versionCode 1 + versionName "1.0.0" + + buildConfigField "String", "REACT_NATIVE_RELEASE_LEVEL", "\"${findProperty('reactNativeReleaseLevel') ?: 'stable'}\"" + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + + manifestPlaceholders = [OAUTH_SCHEME: envVars['NATIVE_SCHEME_URI']] + + testInstrumentationRunnerArguments( + 'USERNAME': envVars['USERNAME'], + 'PASSWORD': envVars['PASSWORD'] + ) + } + signingConfigs { + debug { + storeFile file('debug.keystore') + storePassword 'android' + keyAlias 'androiddebugkey' + keyPassword 'android' + } + } + buildTypes { + debug { + signingConfig signingConfigs.debug + } + release { + // Caution! In production, you need to generate your own keystore file. + // see https://reactnative.dev/docs/signed-apk-android. + signingConfig signingConfigs.debug + def enableShrinkResources = findProperty('android.enableShrinkResourcesInReleaseBuilds') ?: 'false' + shrinkResources enableShrinkResources.toBoolean() + minifyEnabled enableMinifyInReleaseBuilds + proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" + def enablePngCrunchInRelease = findProperty('android.enablePngCrunchInReleaseBuilds') ?: 'true' + crunchPngs enablePngCrunchInRelease.toBoolean() + } + } + // Use release build for instrumented tests instead of debug + testBuildType "release" + packagingOptions { + jniLibs { + def enableLegacyPackaging = findProperty('expo.useLegacyPackaging') ?: 'false' + useLegacyPackaging enableLegacyPackaging.toBoolean() + } + } + androidResources { + ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:!CVS:!thumbs.db:!picasa.ini:!*~' + } +} + +// Apply static values from `gradle.properties` to the `android.packagingOptions` +// Accepts values in comma delimited lists, example: +// android.packagingOptions.pickFirsts=/LICENSE,**/picasa.ini +["pickFirsts", "excludes", "merges", "doNotStrip"].each { prop -> + // Split option: 'foo,bar' -> ['foo', 'bar'] + def options = (findProperty("android.packagingOptions.$prop") ?: "").split(","); + // Trim all elements in place. + for (i in 0.. 0) { + println "android.packagingOptions.$prop += $options ($options.length)" + // Ex: android.packagingOptions.pickFirsts += '**/SCCS/**' + options.each { + android.packagingOptions[prop] += it + } + } +} + +dependencies { + // The version of react-native is set by the React Native Gradle Plugin + implementation("com.facebook.react:react-android") + + def isGifEnabled = (findProperty('expo.gif.enabled') ?: "") == "true"; + def isWebpEnabled = (findProperty('expo.webp.enabled') ?: "") == "true"; + def isWebpAnimatedEnabled = (findProperty('expo.webp.animated') ?: "") == "true"; + + if (isGifEnabled) { + // For animated gif support + implementation("com.facebook.fresco:animated-gif:${expoLibs.versions.fresco.get()}") + } + + if (isWebpEnabled) { + // For webp support + implementation("com.facebook.fresco:webpsupport:${expoLibs.versions.fresco.get()}") + if (isWebpAnimatedEnabled) { + // Animated webp support + implementation("com.facebook.fresco:animated-webp:${expoLibs.versions.fresco.get()}") + } + } + + if (hermesEnabled.toBoolean()) { + implementation("com.facebook.react:hermes-android") + } else { + implementation jscFlavor + } + + // Espresso and testing dependencies + androidTestImplementation("androidx.test.ext:junit:1.2.1") + androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0") + androidTestImplementation("androidx.test.espresso:espresso-intents:3.7.0") + androidTestImplementation("androidx.test:runner:1.7.0") + androidTestImplementation("androidx.test:rules:1.7.0") + androidTestImplementation("androidx.test.uiautomator:uiautomator:2.3.0") + androidTestImplementation("androidx.test:core:1.7.0") + androidTestImplementation("junit:junit:4.13.2") +} diff --git a/e2e/apps/react-native-oidc/android/app/debug.keystore b/e2e/apps/react-native-oidc/android/app/debug.keystore new file mode 100644 index 0000000..364e105 Binary files /dev/null and b/e2e/apps/react-native-oidc/android/app/debug.keystore differ diff --git a/e2e/apps/react-native-oidc/android/app/proguard-rules.pro b/e2e/apps/react-native-oidc/android/app/proguard-rules.pro new file mode 100644 index 0000000..551eb41 --- /dev/null +++ b/e2e/apps/react-native-oidc/android/app/proguard-rules.pro @@ -0,0 +1,14 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# react-native-reanimated +-keep class com.swmansion.reanimated.** { *; } +-keep class com.facebook.react.turbomodule.** { *; } + +# Add any project specific keep options here: diff --git a/e2e/apps/react-native-oidc/android/app/src/androidTest/java/com/anonymous/reporeactnativeoidc/ReactNativeOIDCAppTest.kt b/e2e/apps/react-native-oidc/android/app/src/androidTest/java/com/anonymous/reporeactnativeoidc/ReactNativeOIDCAppTest.kt new file mode 100644 index 0000000..34eaa16 --- /dev/null +++ b/e2e/apps/react-native-oidc/android/app/src/androidTest/java/com/anonymous/reporeactnativeoidc/ReactNativeOIDCAppTest.kt @@ -0,0 +1,454 @@ +package com.anonymous.reporeactnativeoidc + +import androidx.test.espresso.Espresso.onView +import androidx.test.espresso.action.ViewActions.click +import androidx.test.espresso.action.ViewActions.swipeUp +import androidx.test.espresso.action.ViewActions.swipeDown +import androidx.test.espresso.assertion.ViewAssertions.matches +import androidx.test.espresso.assertion.ViewAssertions.doesNotExist +import androidx.test.espresso.matcher.ViewMatchers.* +import androidx.test.ext.junit.rules.ActivityScenarioRule +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.uiautomator.By +import androidx.test.uiautomator.UiDevice +import androidx.test.uiautomator.UiSelector +import androidx.test.uiautomator.Until +import android.os.Bundle +import android.content.Intent +import android.view.KeyEvent +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import org.hamcrest.Matchers.allOf +import org.hamcrest.Matchers.containsString +import org.junit.Before +import org.junit.Ignore +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +/** + * Hybrid E2E tests for OAuth authentication flows. + * + * These tests use a combination of Espresso (for the React Native app) and UIAutomator + * (for the Chrome Custom Tab OAuth provider interaction). + * + */ +@RunWith(AndroidJUnit4::class) +class ReactNativeOIDCAppTest { + + @get:Rule + val activityRule = ActivityScenarioRule(MainActivity::class.java) + + private lateinit var device: UiDevice + private lateinit var oauthEmail: String + private lateinit var oauthPassword: String + + @Before + fun setUp() { + device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) + + // Read credentials from instrumentation arguments (set by build.gradle) + val args: Bundle = InstrumentationRegistry.getArguments() + + oauthEmail = args.getString("USERNAME") + ?: throw IllegalStateException(""" + OAuth email not found in instrumentation arguments. + Make sure USERNAME is set in your testenv file. + """.trimIndent()) + + oauthPassword = args.getString("PASSWORD") + ?: throw IllegalStateException(""" + OAuth password not found in instrumentation arguments. + Make sure PASSWORD is set in your testenv file. + """.trimIndent()) + + println("✓ OAuth credentials loaded: email=$oauthEmail") + } + + /** + * Helper: Wait for Okta login form to be available in Chrome Custom Tab. + * Ensures Chrome webview content has loaded. + */ + private fun waitForOktaLogin(timeoutMs: Long = 8000) { + val chromeLoaded = device.wait( + Until.hasObject(By.pkg("com.android.chrome").depth(0)), + timeoutMs + ) + + if (!chromeLoaded) { + throw AssertionError("Chrome Custom Tab webview failed to load after ${timeoutMs}ms - Chrome may not have opened") + } + } + + /** + * Helper: Input text into a focused field using shell commands + */ + private fun pasteText(text: String) { + try { + println(" Inputting text: $text") + + // Clear any existing content first by selecting all and deleting + device.pressKeyCode(KeyEvent.KEYCODE_A, KeyEvent.META_CTRL_ON) + Thread.sleep(100) + device.pressKeyCode(KeyEvent.KEYCODE_DEL) + Thread.sleep(200) + + // Use shell command to input text directly + // Input command handles most special characters natively + device.executeShellCommand("input text $text") + + Thread.sleep(500) + } catch (e: Exception) { + println("❌ Text input failed: ${e.message}") + throw Exception("Failed to input text: ${e.message}", e) + } + } + + private fun assertFreshAppState() { + // wait for app to fully launch + device.wait(Until.hasObject(By.pkg("com.anonymous.reporeactnativeoidc")), 10000) + Thread.sleep(3000) + + // confirm on Login tab + onView(withText(containsString("Authentication"))) + .check(matches(isDisplayed())) + + // clear existing tokens, etc + performClearFromLoginTab() + navigateToTab("Login") + + onView(withText(containsString("❌ Not Authenticated"))) + .check(matches(isDisplayed())) + + // click `Creds` tab + navigateToTab("Creds") + + // confirm fresh state + onView(withText(containsString("No credentials found."))) + .check(matches(isDisplayed())) + + // click `Token` tab + navigateToTab("Token") + + // confirm fresh state + onView(withText(containsString("No credential found"))) + .check(matches(isDisplayed())) + + // click `Login` tab + navigateToTab("Login") + } + + /** + * Helper: Determines the authentication status of the Test App + */ + private fun verifyAuthenticationStatus(expectAuthenticated: Boolean): Boolean { + return try { + val expectedStatus = if (expectAuthenticated) "✅ Authenticated" else "❌ Not Authenticated" + onView(withText(containsString(expectedStatus))) + .check(matches(isDisplayed())) + true // Element found + } catch (e: Exception) { + false // Element not found + } + } + + /** + * Helper: Navigates between tabs within the Test App + */ + private fun navigateToTab(tab: String) { + val tabConfig: Map> = mapOf( + "Login" to mapOf( + "contentDesc" to "loginTab", + "title" to "Authentication" + ), + "Creds" to mapOf( + "contentDesc" to "credentialsTab", + "title" to "Credentials" + ), + "Token" to mapOf( + "contentDesc" to "tokenTab", + "title" to "Token Details" + ) + ) + + // click `Token` tab + onView( + allOf( + withContentDescription(tabConfig[tab]?.get("contentDesc")), + isDisplayed() + ) + ).perform(click()) + + Thread.sleep(250) // wait for UI animations + + onView(withText(containsString(tabConfig[tab]?.get("title")))) + .check(matches(isDisplayed())) + } + + /** + * Complete OAuth login flow. + * + * Pre-req: Auth flow has already be started + * + * Flow: + * 1. UIAutomator: Wait for Chrome Custom Tab to open + * 2. UIAutomator: Enter OAuth provider credentials + * 3. UIAutomator: Submit login + * 4. UIAutomator: Wait for deep link redirect back to app + * 5. Espresso: Verify successful authentication state in the app + */ + fun performOktaLogin(username: String, password: String) { + // confirms Chrome opened succesfully + waitForOktaLogin() + + try { + Thread.sleep(500) + + // ### Identify Page + + // confirms Identify page loaded + device.wait( + Until.hasObject(By.text("Sign In")), + 5000 + ) + + // username field should be auto-focused, simply paste text and continue + pasteText(username) + device.pressKeyCode(KeyEvent.KEYCODE_ENTER) // submits form + Thread.sleep(2500) // wait for UI transition + + // ### Select Authenticator Page + + // check for and handle possible Select Authenticator Page + val onSelectAuthenticatorPage = device.findObject(UiSelector().text("Verify it's you with a security method")).exists() + if (onSelectAuthenticatorPage) { + // written for a user who has 2 authenticators (Email and Password) + // tab select to the 2nd button to select 'Password' + val selectPasswordButton = device.findObject( + By.desc("Select Password.") + ) + if (selectPasswordButton != null) { + selectPasswordButton.click() + } + + Thread.sleep(2500) // wait for UI transition + } + + // ### Challenge Password Page + + // confirms Challenge Password page loaded + val titleLoaded = device.wait( + Until.hasObject(By.text("Verify with your password")), + 5000 + ) + + // password field should be auto-focused, simply paste text and continue + pasteText(password) + device.pressKeyCode(KeyEvent.KEYCODE_ENTER) // submits form + } catch (e: Exception) { + println("❌ OAuth form interaction error: ${e.message}") + e.printStackTrace() + throw AssertionError("Failed to interact with OAuth provider form: ${e.message}") + } + + // wait for UI animations + Thread.sleep(3000) + + // wait for Chrome to close and app to return to foreground + val appInForeground = device.wait( + Until.hasObject(By.pkg("com.anonymous.reporeactnativeoidc").focused(true)), + 10000 + ) + assert(appInForeground) { "App should receive OAuth callback and return to foreground" } + + // verify Chrome is no longer visible + val chromeGone = !device.hasObject(By.pkg("com.android.chrome")) + if (!chromeGone) { + println("⚠️ Chrome still visible, but app is in foreground") + } + + // wait for OAuth callback exchange + Thread.sleep(3000) + } + + fun performLoginFromLoginTab() { + // click `Request Token` button + onView( + allOf( + withContentDescription("requestTokenButton"), + isDisplayed() + ) + ).perform(click()) + + // complete the OAuth login flow + performOktaLogin(oauthEmail, oauthPassword) + + Thread.sleep(1000) + + // confirm fresh state + onView(withText(containsString("✅ Authenticated"))) + .check(matches(isDisplayed())) + } + + fun performLogoutFromLoginTab() { + // click `Sign Out` button + onView( + allOf( + withContentDescription("signOutButton"), + isDisplayed() + ) + ).perform(click()) + + Thread.sleep(2000) + + // confirm fresh state + onView(withText(containsString("❌ Not Authenticated"))) + .check(matches(isDisplayed())) + } + + fun performClearFromLoginTab() { + // click `Clear` button + onView( + allOf( + withContentDescription("clearButton"), + isDisplayed() + ) + ).perform(click()) + + Thread.sleep(2000) + + // confirm fresh state + onView(withText(containsString("❌ Not Authenticated"))) + .check(matches(isDisplayed())) + } + + @Test + fun oauthFlow_CompleteLoginWithValidCredentials() { + assertFreshAppState() + + // confirm fresh state + onView(withText(containsString("❌ Not Authenticated"))) + .check(matches(isDisplayed())) + + performLoginFromLoginTab() + } + + @Test + fun oauthFlow_ChromeTabClosedBeforeCompletion() { + // wait for app to fully launch + device.wait(Until.hasObject(By.pkg("com.anonymous.reporeactnativeoidc")), 10000) + Thread.sleep(3000) + + // confirm fresh state + onView(withText(containsString("❌ Not Authenticated"))) + .check(matches(isDisplayed())) + + // click `Request Token` button + onView( + allOf( + withContentDescription("requestTokenButton"), + isDisplayed() + ) + ).perform(click()) + + waitForOktaLogin() + + // close Chrome Custom Tab by clicking the X button in the top left + val closeButtonAlt = device.findObject(By.res("com.android.chrome:id/close_button")) + if (closeButtonAlt != null) { + closeButtonAlt.click() + } else { + throw AssertionError("Could not find Chrome close button") + } + + // wait for Chrome to close and app to return to foreground + val appInForeground = device.wait( + Until.hasObject(By.pkg("com.anonymous.reporeactnativeoidc").focused(true)), + 10000 + ) + assert(appInForeground) { "App should return to foreground after Chrome closes" } + + // wait for app to process the dismissal + Thread.sleep(2000) + + // confir, app is still in "Not Authenticated" state (no OAuth callback received) + onView(withText(containsString("❌ Not Authenticated"))) + .check(matches(isDisplayed())) + } + + @Test + fun oauthFlow_TokenRevokeAfterLogin() { + if (verifyAuthenticationStatus(false)) { + performLoginFromLoginTab() + } + else { + println("⚠️ Skipping login, already authenticated") + } + + Thread.sleep(2000) + + performLogoutFromLoginTab() + } + + @Test + fun oauthFlow_RequestMultipleTokens() { + // wait for app to fully launch + assertFreshAppState() + + // perform 2 logins to acquire 2 tokens + // (this test assumes ephemeralSession and therefore no bound redirect will occur) + performLoginFromLoginTab() + Thread.sleep(2000) + performLoginFromLoginTab() + Thread.sleep(2000) + + // navigate to the Creds tabs to confirm multiple Credentials exist + // (this will help test the Credential/TokenStorage layers) + navigateToTab("Creds") + + onView(withText(containsString("2 credentials stored"))) + .check(matches(isDisplayed())) + + onView(withText(containsString("DEFAULT"))) + .check(matches(isDisplayed())) + + // navigate to the Token tab to revoke the default Credential + // (this will further help test the Credential/TokenStorage layers) + // NOTE: the Token tab will load the default Credential by default + navigateToTab("Token") + + Thread.sleep(250) + + // find 'Revoke Token' button and click (scroll to bottom to find it) + onView(isRoot()).perform( + swipeUp(), + swipeUp(), + swipeUp() + ) + Thread.sleep(250) + onView( + allOf( + withContentDescription("revokeTokenButton"), + isDisplayed() + ) + ).perform(click()) + + Thread.sleep(1500) + + onView(isRoot()).perform( + swipeDown(), + swipeDown(), + swipeDown() + ) + Thread.sleep(250) + + // assert a Credential was removed (there is now 1 less) + // and the 'DEFAULT' badge doesn't exist (the default Credential should have been removed) + onView(withText(containsString("1 credential stored"))) + .check(matches(isDisplayed())) + onView(withText(containsString("DEFAULT"))) + .check(doesNotExist()) + } +} diff --git a/e2e/apps/react-native-oidc/android/app/src/debug/AndroidManifest.xml b/e2e/apps/react-native-oidc/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..3ec2507 --- /dev/null +++ b/e2e/apps/react-native-oidc/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + + + diff --git a/e2e/apps/react-native-oidc/android/app/src/debugOptimized/AndroidManifest.xml b/e2e/apps/react-native-oidc/android/app/src/debugOptimized/AndroidManifest.xml new file mode 100644 index 0000000..3ec2507 --- /dev/null +++ b/e2e/apps/react-native-oidc/android/app/src/debugOptimized/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + + + diff --git a/e2e/apps/react-native-oidc/android/app/src/main/AndroidManifest.xml b/e2e/apps/react-native-oidc/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..6dc6750 --- /dev/null +++ b/e2e/apps/react-native-oidc/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/e2e/apps/react-native-oidc/android/app/src/main/java/com/anonymous/reporeactnativeoidc/MainActivity.kt b/e2e/apps/react-native-oidc/android/app/src/main/java/com/anonymous/reporeactnativeoidc/MainActivity.kt new file mode 100644 index 0000000..3b2bfd0 --- /dev/null +++ b/e2e/apps/react-native-oidc/android/app/src/main/java/com/anonymous/reporeactnativeoidc/MainActivity.kt @@ -0,0 +1,65 @@ +package com.anonymous.reporeactnativeoidc +import expo.modules.splashscreen.SplashScreenManager + +import android.os.Build +import android.os.Bundle + +import com.facebook.react.ReactActivity +import com.facebook.react.ReactActivityDelegate +import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled +import com.facebook.react.defaults.DefaultReactActivityDelegate + +import expo.modules.ReactActivityDelegateWrapper + +class MainActivity : ReactActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + // Set the theme to AppTheme BEFORE onCreate to support + // coloring the background, status bar, and navigation bar. + // This is required for expo-splash-screen. + // setTheme(R.style.AppTheme); + // @generated begin expo-splashscreen - expo prebuild (DO NOT MODIFY) sync-f3ff59a738c56c9a6119210cb55f0b613eb8b6af + SplashScreenManager.registerOnActivity(this) + // @generated end expo-splashscreen + super.onCreate(null) + } + + /** + * Returns the name of the main component registered from JavaScript. This is used to schedule + * rendering of the component. + */ + override fun getMainComponentName(): String = "main" + + /** + * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate] + * which allows you to enable New Architecture with a single boolean flags [fabricEnabled] + */ + override fun createReactActivityDelegate(): ReactActivityDelegate { + return ReactActivityDelegateWrapper( + this, + BuildConfig.IS_NEW_ARCHITECTURE_ENABLED, + object : DefaultReactActivityDelegate( + this, + mainComponentName, + fabricEnabled + ){}) + } + + /** + * Align the back button behavior with Android S + * where moving root activities to background instead of finishing activities. + * @see onBackPressed + */ + override fun invokeDefaultOnBackPressed() { + if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) { + if (!moveTaskToBack(false)) { + // For non-root activities, use the default implementation to finish them. + super.invokeDefaultOnBackPressed() + } + return + } + + // Use the default back button implementation on Android S + // because it's doing more than [Activity.moveTaskToBack] in fact. + super.invokeDefaultOnBackPressed() + } +} diff --git a/e2e/apps/react-native-oidc/android/app/src/main/java/com/anonymous/reporeactnativeoidc/MainApplication.kt b/e2e/apps/react-native-oidc/android/app/src/main/java/com/anonymous/reporeactnativeoidc/MainApplication.kt new file mode 100644 index 0000000..7747866 --- /dev/null +++ b/e2e/apps/react-native-oidc/android/app/src/main/java/com/anonymous/reporeactnativeoidc/MainApplication.kt @@ -0,0 +1,56 @@ +package com.anonymous.reporeactnativeoidc + +import android.app.Application +import android.content.res.Configuration + +import com.facebook.react.PackageList +import com.facebook.react.ReactApplication +import com.facebook.react.ReactNativeApplicationEntryPoint.loadReactNative +import com.facebook.react.ReactNativeHost +import com.facebook.react.ReactPackage +import com.facebook.react.ReactHost +import com.facebook.react.common.ReleaseLevel +import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint +import com.facebook.react.defaults.DefaultReactNativeHost + +import expo.modules.ApplicationLifecycleDispatcher +import expo.modules.ReactNativeHostWrapper + +class MainApplication : Application(), ReactApplication { + + override val reactNativeHost: ReactNativeHost = ReactNativeHostWrapper( + this, + object : DefaultReactNativeHost(this) { + override fun getPackages(): List = + PackageList(this).packages.apply { + // Packages that cannot be autolinked yet can be added manually here, for example: + // add(MyReactNativePackage()) + } + + override fun getJSMainModuleName(): String = ".expo/.virtual-metro-entry" + + override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG + + override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED + } + ) + + override val reactHost: ReactHost + get() = ReactNativeHostWrapper.createReactHost(applicationContext, reactNativeHost) + + override fun onCreate() { + super.onCreate() + DefaultNewArchitectureEntryPoint.releaseLevel = try { + ReleaseLevel.valueOf(BuildConfig.REACT_NATIVE_RELEASE_LEVEL.uppercase()) + } catch (e: IllegalArgumentException) { + ReleaseLevel.STABLE + } + loadReactNative(this) + ApplicationLifecycleDispatcher.onApplicationCreate(this) + } + + override fun onConfigurationChanged(newConfig: Configuration) { + super.onConfigurationChanged(newConfig) + ApplicationLifecycleDispatcher.onConfigurationChanged(this, newConfig) + } +} diff --git a/e2e/apps/react-native-oidc/android/app/src/main/res/drawable-hdpi/splashscreen_logo.png b/e2e/apps/react-native-oidc/android/app/src/main/res/drawable-hdpi/splashscreen_logo.png new file mode 100644 index 0000000..31df827 Binary files /dev/null and b/e2e/apps/react-native-oidc/android/app/src/main/res/drawable-hdpi/splashscreen_logo.png differ diff --git a/e2e/apps/react-native-oidc/android/app/src/main/res/drawable-mdpi/splashscreen_logo.png b/e2e/apps/react-native-oidc/android/app/src/main/res/drawable-mdpi/splashscreen_logo.png new file mode 100644 index 0000000..ef243aa Binary files /dev/null and b/e2e/apps/react-native-oidc/android/app/src/main/res/drawable-mdpi/splashscreen_logo.png differ diff --git a/e2e/apps/react-native-oidc/android/app/src/main/res/drawable-xhdpi/splashscreen_logo.png b/e2e/apps/react-native-oidc/android/app/src/main/res/drawable-xhdpi/splashscreen_logo.png new file mode 100644 index 0000000..e9d5474 Binary files /dev/null and b/e2e/apps/react-native-oidc/android/app/src/main/res/drawable-xhdpi/splashscreen_logo.png differ diff --git a/e2e/apps/react-native-oidc/android/app/src/main/res/drawable-xxhdpi/splashscreen_logo.png b/e2e/apps/react-native-oidc/android/app/src/main/res/drawable-xxhdpi/splashscreen_logo.png new file mode 100644 index 0000000..d61da15 Binary files /dev/null and b/e2e/apps/react-native-oidc/android/app/src/main/res/drawable-xxhdpi/splashscreen_logo.png differ diff --git a/e2e/apps/react-native-oidc/android/app/src/main/res/drawable-xxxhdpi/splashscreen_logo.png b/e2e/apps/react-native-oidc/android/app/src/main/res/drawable-xxxhdpi/splashscreen_logo.png new file mode 100644 index 0000000..4aeed11 Binary files /dev/null and b/e2e/apps/react-native-oidc/android/app/src/main/res/drawable-xxxhdpi/splashscreen_logo.png differ diff --git a/e2e/apps/react-native-oidc/android/app/src/main/res/drawable/ic_launcher_background.xml b/e2e/apps/react-native-oidc/android/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..883b2a0 --- /dev/null +++ b/e2e/apps/react-native-oidc/android/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/e2e/apps/react-native-oidc/android/app/src/main/res/drawable/rn_edit_text_material.xml b/e2e/apps/react-native-oidc/android/app/src/main/res/drawable/rn_edit_text_material.xml new file mode 100644 index 0000000..5c25e72 --- /dev/null +++ b/e2e/apps/react-native-oidc/android/app/src/main/res/drawable/rn_edit_text_material.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + diff --git a/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-hdpi/ic_launcher.webp new file mode 100644 index 0000000..a2f5908 Binary files /dev/null and b/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-hdpi/ic_launcher.webp differ diff --git a/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp new file mode 100644 index 0000000..1b52399 Binary files /dev/null and b/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp differ diff --git a/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp new file mode 100644 index 0000000..ff10afd Binary files /dev/null and b/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp differ diff --git a/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp new file mode 100644 index 0000000..115a4c7 Binary files /dev/null and b/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp differ diff --git a/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp new file mode 100644 index 0000000..dcd3cd8 Binary files /dev/null and b/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp differ diff --git a/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..459ca60 Binary files /dev/null and b/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp differ diff --git a/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp new file mode 100644 index 0000000..8ca12fe Binary files /dev/null and b/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp differ diff --git a/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..8e19b41 Binary files /dev/null and b/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp differ diff --git a/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp new file mode 100644 index 0000000..b824ebd Binary files /dev/null and b/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differ diff --git a/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..4c19a13 Binary files /dev/null and b/e2e/apps/react-native-oidc/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp differ diff --git a/e2e/apps/react-native-oidc/android/app/src/main/res/values-night/colors.xml b/e2e/apps/react-native-oidc/android/app/src/main/res/values-night/colors.xml new file mode 100644 index 0000000..3c05de5 --- /dev/null +++ b/e2e/apps/react-native-oidc/android/app/src/main/res/values-night/colors.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/e2e/apps/react-native-oidc/android/app/src/main/res/values/colors.xml b/e2e/apps/react-native-oidc/android/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..a890727 --- /dev/null +++ b/e2e/apps/react-native-oidc/android/app/src/main/res/values/colors.xml @@ -0,0 +1,5 @@ + + #FFFFFF + #023c69 + #ffffff + \ No newline at end of file diff --git a/e2e/apps/react-native-oidc/android/app/src/main/res/values/strings.xml b/e2e/apps/react-native-oidc/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..49c2cc5 --- /dev/null +++ b/e2e/apps/react-native-oidc/android/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + \@repo/react-native-oidc + \ No newline at end of file diff --git a/e2e/apps/react-native-oidc/android/app/src/main/res/values/styles.xml b/e2e/apps/react-native-oidc/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..45a97e6 --- /dev/null +++ b/e2e/apps/react-native-oidc/android/app/src/main/res/values/styles.xml @@ -0,0 +1,14 @@ + + + + \ No newline at end of file diff --git a/e2e/apps/react-native-oidc/android/build.gradle b/e2e/apps/react-native-oidc/android/build.gradle new file mode 100644 index 0000000..2c548b6 --- /dev/null +++ b/e2e/apps/react-native-oidc/android/build.gradle @@ -0,0 +1,38 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + repositories { + google() + mavenCentral() + } + dependencies { + classpath('com.android.tools.build:gradle') + classpath('com.facebook.react:react-native-gradle-plugin') + classpath('org.jetbrains.kotlin:kotlin-gradle-plugin') + } +} + +allprojects { + repositories { + google() + mavenCentral() + maven { url 'https://www.jitpack.io' } + } + + // Configure all library modules to handle fbjni conflict + afterEvaluate { project -> + if (project.plugins.hasPlugin('android-library')) { + project.android { + packagingOptions { + pickFirst 'lib/arm64-v8a/libfbjni.so' + pickFirst 'lib/armeabi-v7a/libfbjni.so' + pickFirst 'lib/x86/libfbjni.so' + pickFirst 'lib/x86_64/libfbjni.so' + } + } + } + } +} + +apply plugin: "expo-root-project" +apply plugin: "com.facebook.react.rootproject" diff --git a/e2e/apps/react-native-oidc/android/gradle.properties b/e2e/apps/react-native-oidc/android/gradle.properties new file mode 100644 index 0000000..dca4160 --- /dev/null +++ b/e2e/apps/react-native-oidc/android/gradle.properties @@ -0,0 +1,72 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +# Default value: -Xmx512m -XX:MaxMetaspaceSize=256m +# Increased for instrumentation tests with multiple Expo modules +# org.gradle.jvmargs=-Xmx4096m -XX:MaxMetaspaceSize=1024m +org.gradle.jvmargs=-Xmx6144m -XX:MaxMetaspaceSize=2048m +org.gradle.workers.max=1 + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +org.gradle.parallel=true + +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app's APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true + +# Enable AAPT2 PNG crunching +android.enablePngCrunchInReleaseBuilds=true + +# Use this property to specify which architecture you want to build. +# You can also override it from the CLI using +# ./gradlew -PreactNativeArchitectures=x86_64 +reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64 + +# Use this property to enable support to the new architecture. +# This will allow you to use TurboModules and the Fabric render in +# your application. You should enable this flag either if you want +# to write custom TurboModules/Fabric components OR use libraries that +# are providing them. +newArchEnabled=true + +# Use this property to enable or disable the Hermes JS engine. +# If set to false, you will be using JSC instead. +hermesEnabled=true + +# Use this property to enable edge-to-edge display support. +# This allows your app to draw behind system bars for an immersive UI. +# Note: Only works with ReactActivity and should not be used with custom Activity. +edgeToEdgeEnabled=true + +# Enable GIF support in React Native images (~200 B increase) +expo.gif.enabled=true +# Enable webp support in React Native images (~85 KB increase) +expo.webp.enabled=true +# Enable animated webp support (~3.4 MB increase) +# Disabled by default because iOS doesn't support animated webp +expo.webp.animated=false + +# Enable network inspector +EX_DEV_CLIENT_NETWORK_INSPECTOR=true + +# Use legacy packaging to compress native libraries in the resulting APK. +expo.useLegacyPackaging=false + +# Specifies whether the app is configured to use edge-to-edge via the app config or plugin +# WARNING: This property has been deprecated and will be removed in Expo SDK 55. Use `edgeToEdgeEnabled` or `react.edgeToEdgeEnabled` to determine whether the project is using edge-to-edge. +expo.edgeToEdgeEnabled=true + + +android.compileSdkVersion=36 +android.targetSdkVersion=35 diff --git a/e2e/apps/react-native-oidc/android/gradle/wrapper/gradle-wrapper.jar b/e2e/apps/react-native-oidc/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 Binary files /dev/null and b/e2e/apps/react-native-oidc/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/e2e/apps/react-native-oidc/android/gradle/wrapper/gradle-wrapper.properties b/e2e/apps/react-native-oidc/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..d4081da --- /dev/null +++ b/e2e/apps/react-native-oidc/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/e2e/apps/react-native-oidc/android/gradlew b/e2e/apps/react-native-oidc/android/gradlew new file mode 100755 index 0000000..7f94d3d --- /dev/null +++ b/e2e/apps/react-native-oidc/android/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/e2e/apps/react-native-oidc/android/gradlew.bat b/e2e/apps/react-native-oidc/android/gradlew.bat new file mode 100644 index 0000000..db3a6ac --- /dev/null +++ b/e2e/apps/react-native-oidc/android/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/e2e/apps/react-native-oidc/android/settings.gradle b/e2e/apps/react-native-oidc/android/settings.gradle new file mode 100644 index 0000000..288349d --- /dev/null +++ b/e2e/apps/react-native-oidc/android/settings.gradle @@ -0,0 +1,39 @@ +pluginManagement { + def reactNativeGradlePlugin = new File( + providers.exec { + workingDir(rootDir) + commandLine("node", "--print", "require.resolve('@react-native/gradle-plugin/package.json', { paths: [require.resolve('react-native/package.json')] })") + }.standardOutput.asText.get().trim() + ).getParentFile().absolutePath + includeBuild(reactNativeGradlePlugin) + + def expoPluginsPath = new File( + providers.exec { + workingDir(rootDir) + commandLine("node", "--print", "require.resolve('expo-modules-autolinking/package.json', { paths: [require.resolve('expo/package.json')] })") + }.standardOutput.asText.get().trim(), + "../android/expo-gradle-plugin" + ).absolutePath + includeBuild(expoPluginsPath) +} + +plugins { + id("com.facebook.react.settings") + id("expo-autolinking-settings") +} + +extensions.configure(com.facebook.react.ReactSettingsExtension) { ex -> + if (System.getenv('EXPO_USE_COMMUNITY_AUTOLINKING') == '1') { + ex.autolinkLibrariesFromCommand() + } else { + ex.autolinkLibrariesFromCommand(expoAutolinking.rnConfigCommand) + } +} +expoAutolinking.useExpoModules() + +rootProject.name = '@reporeact-native-oidc' + +expoAutolinking.useExpoVersionCatalog() + +include ':app' +includeBuild(expoAutolinking.reactNativeGradlePlugin) diff --git a/e2e/apps/react-native-oidc/app.config.ts b/e2e/apps/react-native-oidc/app.config.ts index 97e47af..92c7c4e 100644 --- a/e2e/apps/react-native-oidc/app.config.ts +++ b/e2e/apps/react-native-oidc/app.config.ts @@ -5,7 +5,13 @@ import envModule from '@repo/env'; envModule.setEnvironmentVarsFromTestEnv(__dirname); const env: any = {}; // List of environment variables made available to the app -['ISSUER', 'NATIVE_CLIENT_ID', 'NATIVE_REDIRECT_URI', 'USE_DPOP'].forEach((key) => { +[ + 'ISSUER', + 'NATIVE_CLIENT_ID', + 'NATIVE_REDIRECT_URI', + 'NATIVE_LOGOUT_REDIRECT_URI', + 'USE_DPOP' +].forEach((key) => { if (!process.env[key]) { console.warn(`Environment variable ${key} should be set for development. See README.md`); } @@ -25,7 +31,7 @@ export default ({ config }: ConfigContext) => ({ "ios": { "bundleIdentifier": "com.anonymous.reporeactnativeoidc" }, - scheme: "com.oktapreview.jperreault-test", + scheme: process.env.NATIVE_SCHEME_URI, autolinking: { searchPaths: [ "../../node_modules", @@ -38,7 +44,7 @@ export default ({ config }: ConfigContext) => ({ autoVerify: true, data: [ { - scheme: "com.oktapreview.jperreault-test" + scheme: process.env.NATIVE_SCHEME_URI } ], category: ["BROWSABLE", "DEFAULT"] diff --git a/e2e/apps/react-native-oidc/app/(tabs)/_layout.tsx b/e2e/apps/react-native-oidc/app/(tabs)/_layout.tsx index 7a27432..64ce522 100644 --- a/e2e/apps/react-native-oidc/app/(tabs)/_layout.tsx +++ b/e2e/apps/react-native-oidc/app/(tabs)/_layout.tsx @@ -30,6 +30,7 @@ export default function TabLayout() { name="index" options={{ title: 'Login', + tabBarAccessibilityLabel: 'loginTab', tabBarIcon: ({ color }) => , }} /> @@ -37,6 +38,7 @@ export default function TabLayout() { name="credentials" options={{ title: 'Creds', + tabBarAccessibilityLabel: 'credentialsTab', tabBarIcon: ({ color }) => , }} /> @@ -44,6 +46,7 @@ export default function TabLayout() { name="token" options={{ title: 'Token', + tabBarAccessibilityLabel: 'tokenTab', tabBarIcon: ({ color }) => , }} /> diff --git a/e2e/apps/react-native-oidc/app/(tabs)/credentials.tsx b/e2e/apps/react-native-oidc/app/(tabs)/credentials.tsx index 5579ebd..1913599 100644 --- a/e2e/apps/react-native-oidc/app/(tabs)/credentials.tsx +++ b/e2e/apps/react-native-oidc/app/(tabs)/credentials.tsx @@ -117,6 +117,7 @@ export default function CredentialsScreen() { {credentials.map((cred) => ( handleCredentialPress(cred.id)}> diff --git a/e2e/apps/react-native-oidc/app/(tabs)/index.tsx b/e2e/apps/react-native-oidc/app/(tabs)/index.tsx index bf06240..39134a2 100644 --- a/e2e/apps/react-native-oidc/app/(tabs)/index.tsx +++ b/e2e/apps/react-native-oidc/app/(tabs)/index.tsx @@ -41,7 +41,7 @@ export default function AuthScreen() { setLoading(true); setError(null); await signIn(); - setIsAuthenticated(true); + await checkAuth(); } catch (err) { console.error('Sign in failed:', err); setError(err instanceof Error ? err.message : 'Sign in failed'); @@ -64,6 +64,17 @@ export default function AuthScreen() { } }; + const handleClearStorage = async () => { + try { + setLoading(true); + setError(null); + await Credential.clear(); + } + finally { + setLoading(false); + } + } + return ( -