Deep links and intent security

Learn Android deep link security: verified App Links with assetlinks.json, exported components, PendingIntent FLAG_IMMUTABLE and preventing intent redirection. About 25 minutes.

Why it matters

  • An exported Activity that handles a deep link is a public API. Any app on the device, or any web page, can send it data. Trusting that data leads to bugs such as opening internal screens, leaking files or intent redirection.
  • A mutable PendingIntent wrapping an implicit Intent lets whoever receives it fill in the target. Google Play has published remediation guidance for both intent redirection and implicit PendingIntent vulnerabilities.
  • Verified Android App Links (assetlinks.json plus android:autoVerify="true") make your https links open your app and no one else's. Interviewers often ask how they differ from plain deep links and what changed in Android 12.
  • Obfuscation (R8) renames classes but does not stop anyone from sending a crafted Intent. Validation in code is the control.

The simple explanation

  • A deep link is a doorbell on your front door: anyone on the street can ring it.
  • A verified App Link is a doorbell registered to your address: the city confirmed you own the house, so the delivery comes only to you.
  • Data in the link or in intent extras is a note slipped under the door. Read only the lines you expect and check each one.
  • A mutable PendingIntent is a signed, pre-paid envelope with a blank address line. FLAG_IMMUTABLE and an explicit target fill in the address before you hand it over.

What is the difference between a deep link and an Android App Link? A deep link is any intent filter that opens your Activity from a URI, such as myapp://item/42 or https://example.com/item/42. Other apps can declare the same filter, so the user may get a chooser or the wrong app. An App Link is an https deep link whose domain you have verified: the filter has android:autoVerify="true" and your site serves https://example.com/.well-known/assetlinks.json listing your package name and signing certificate SHA-256 fingerprint. Android checks the file and then opens matching links directly in your app. Custom schemes cannot be verified.

Android 12 (API 31) changes. A generic web link (http/https, VIEW, BROWSABLE) opens your app only if your app is approved for that domain, through verification or because the user enabled it in settings; otherwise it opens in the browser. Verification is also tracked per domain, so one failing host no longer blocks the others.

Every incoming Intent is a message from an untrusted caller:

SurfaceRiskMitigation
Exported componentsAny app can start your Activity, Service or Receiverandroid:exported="false" unless it must be public; protect public ones with a signature permission when only your apps call them
Link data and extrasCaller controls every valueParse only the values you need from the URI; validate type, length and format
Nested Intent extrasIntent redirection: your app launches what the attacker choseNever launch an Intent taken from extras; build a new explicit one
PendingIntentReceiver fills in an implicit target or adds URI grantsFLAG_IMMUTABLE plus an explicit component; FLAG_MUTABLE only when required

Intent redirection happens when an exported component reads an Intent (or a URI it turns into one) from the incoming data and passes it to startActivity. Because the launch comes from your app, it can reach your non-exported components and your FileProvider grants. The fix is to never forward a caller-supplied intent.

PendingIntent rules. Apps targeting API 31+ must pass FLAG_IMMUTABLE or FLAG_MUTABLE, or creation throws IllegalArgumentException. Apps targeting API 34+ cannot create a mutable PendingIntent around an implicit Intent without an explicit opt-out flag.

Notes

  • Set android:exported="false" on every component that other apps do not need. Apps targeting Android 12+ must declare android:exported explicitly on components with intent filters, or the app cannot be installed.
  • An intent filter makes a component reachable from outside. Do not add one to an internal screen just to navigate to it; use an explicit Intent instead.
  • For App Links, put android:autoVerify="true" on an intent filter with VIEW, DEFAULT, BROWSABLE and https data, and serve assetlinks.json over HTTPS without redirects, with Content-Type: application/json.
  • The fingerprint in assetlinks.json must match the key that signs the installed app. With Play App Signing that is the app signing key from Play Console, not your upload key.
  • Check App Link state on Android 12+ with adb shell pm get-app-links com.example.app and re-run verification with adb shell pm verify-app-links --re-verify com.example.app.
  • Read only the parameters you expect, from intent.data (path segments, query parameters). Validate each one: an ID should match a strict pattern and length, never be passed into SQL or file paths unchecked.
  • Never call startActivity with an Intent from getParcelableExtra. If a link must say "go here next", accept a short route name and map it to an explicit destination you control.
  • getCallingPackage() returns null unless the Activity was started for a result, so it is not a reliable way to authorise callers. Use a signature-level permission for components only your own apps should call.
  • Use FLAG_IMMUTABLE for every PendingIntent unless the receiver must fill in data, such as inline reply in notifications. A mutable one should wrap an explicit Intent (setPackage or a component).
  • In debug builds, StrictMode.VmPolicy.Builder().detectUnsafeIntentLaunch() (API 31+) flags launches of intents that came from another app, which helps find redirection bugs.

Code example

The manifest declares a verified App Link for one path; the matching assetlinks.json sits on the website.

<activity
    android:name=".DeepLinkActivity"
    android:exported="true">
    <intent-filter android:autoVerify="true">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="https" />
        <data android:host="app.example.com" />
        <data android:pathPrefix="/profile/" />
    </intent-filter>
</activity>
[
  {
    "relation": ["delegate_permission/common.handle_all_urls"],
    "target": {
      "namespace": "android_app",
      "package_name": "com.example.secure",
      "sha256_cert_fingerprints": ["AB:CD:...:EF"]
    }
  }
]

This Activity validates the link, reads only the user ID from the path, and starts an explicit internal screen. A helper builds an immutable PendingIntent for a notification that opens the same screen.

package com.example.secure
 
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
 
class DeepLinkActivity : AppCompatActivity() {
 
    private val allowedHosts = setOf("app.example.com")
    private val userIdPattern = Regex("[A-Za-z0-9_-]{1,64}")
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        handle(intent)
        finish() // trampoline: route, then get out of the back stack
    }
 
    private fun handle(intent: Intent) {
        val uri: Uri = intent.data ?: return
        if (uri.scheme != "https" || uri.host !in allowedHosts) return
 
        // Expect exactly /profile/{userId}; ignore all extras.
        val segments = uri.pathSegments
        if (segments.size != 2 || segments[0] != "profile") return
        val userId = segments[1]
        if (!userIdPattern.matches(userId)) return
 
        // New explicit Intent with only the validated value.
        startActivity(ProfileActivity.intent(this, userId))
    }
}
 
class ProfileActivity : AppCompatActivity() {
    companion object {
        private const val EXTRA_USER_ID = "user_id"
 
        fun intent(context: Context, userId: String): Intent =
            Intent(context, ProfileActivity::class.java).putExtra(EXTRA_USER_ID, userId)
 
        fun pendingIntent(context: Context, userId: String): PendingIntent =
            PendingIntent.getActivity(
                context,
                userId.hashCode(), // distinct request code per user
                intent(context, userId),
                PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
            )
    }
}
  • The scheme, host and path shape are checked first, then the one value the screen needs is validated with a strict pattern.
  • Extras are ignored entirely. Browsers and other apps can add their own extras to a VIEW intent, so the link data in intent.data is the contract.
  • ProfileActivity is not exported (no intent filter, exported="false"), and it is reached only through a new explicit Intent. Nothing from the caller is forwarded.
  • FLAG_IMMUTABLE stops a notification receiver from changing the intent; FLAG_UPDATE_CURRENT updates the extras if the same request code is reused.
  • If the Activity used launchMode="singleTop", it would also need to handle onNewIntent. As a trampoline that finishes immediately, it does not.

Run the idea in plain Kotlin

data class IncomingLink(
  val scheme: String,
  val host: String?,
  val path: String,
  val extras: Map<String, String> = emptyMap()
)

val allowedHosts = setOf("app.example.com")
val userIdPattern = Regex("[A-Za-z0-9_-]{1,64}")

fun route(link: IncomingLink): String {
  if (link.scheme != "https") return "REJECTED: scheme " + link.scheme
  if (link.host !in allowedHosts) return "REJECTED: host " + link.host
  val segments = link.path.trim('/').split('/')
  if (segments.size != 2 || segments[0] != "profile") return "REJECTED: unknown path " + link.path
  val userId = segments[1]
  if (!userIdPattern.matches(userId)) return "REJECTED: invalid user id"
  // Extras are never read, so a smuggled "next_intent" has no effect
  return "OPEN ProfileActivity(userId=" + userId + ")"
}

fun main() {
  val links = listOf(
      IncomingLink("https", "app.example.com", "/profile/user_42"),
      IncomingLink("http", "app.example.com", "/profile/user_42"),
      IncomingLink("https", "evil.example.net", "/profile/user_42"),
      IncomingLink("https", "app.example.com", "/admin/settings"),
      IncomingLink("https", "app.example.com", "/profile/" + "a".repeat(65)),
      IncomingLink("https", "app.example.com", "/profile/abc", mapOf("next_intent" to "intent:#Intent;component=com.example.secure/.AdminActivity;end"))
  )
  for (link in links) println(route(link))
}

Expected output:

OPEN ProfileActivity(userId=user_42)
REJECTED: scheme http
REJECTED: host evil.example.net
REJECTED: unknown path /admin/settings
REJECTED: invalid user id
OPEN ProfileActivity(userId=abc)

In production

Exported Activity forwarded a caller-supplied Intent
  • A "router" Activity was exported so marketing links could open it. If the incoming intent had an extra named next, it called startActivity on that nested Intent.
  • A security researcher showed that another app could put an Intent targeting a non-exported settings screen inside next. Because the launch came from the app itself, the internal screen opened.
  • The same path could target the app's FileProvider with read grants, exposing private files.
The fix
  • Removed the nested-intent extra. The router now accepts a route name from the link path and maps it to a fixed set of explicit destinations.
  • Marked every internal Activity exported="false" and removed intent filters that were only used for in-app navigation.
  • Enabled detectUnsafeIntentLaunch() in debug builds and added a test that sends the router an intent with a nested Intent extra and asserts nothing is launched.
Mutable PendingIntent with an implicit Intent
  • A notification action used a PendingIntent created with FLAG_MUTABLE around an implicit Intent (an action string, no package or component).
  • The app passed that PendingIntent to a third-party SDK. Any code holding it could fill in the missing component, or add a content:// URI with a read-grant flag, and send it with the app's identity.
  • An internal security review found it; the action did not need mutability at all.
The fix
  • Switched to FLAG_IMMUTABLE and made the base Intent explicit with the app's own component.
  • For the one notification that needed inline reply (which requires a mutable PendingIntent), kept FLAG_MUTABLE but set an explicit component so nothing can redirect it.
  • Raised the target SDK to 34, where creating a mutable PendingIntent around an implicit Intent throws, so the mistake cannot come back unnoticed.

Common mistakes

  • exported="true" on internal screens. Any app can start them. Export only entry points, and protect them with a signature permission when only your apps should call them.
  • Launching an Intent taken from extras. This is intent redirection: the attacker chooses the target and your app's identity opens it. Build a new explicit Intent from validated values.
  • Missing FLAG_IMMUTABLE. Targeting API 31+ without a mutability flag throws IllegalArgumentException. Use FLAG_IMMUTABLE unless the receiver must fill in data.
  • Mutable PendingIntent around an implicit Intent. Whoever receives it can choose the component. Make the base intent explicit.
  • Skipping scheme and host checks. A deep link handler that only reads the path accepts http, other hosts and custom schemes. Check scheme, host and path shape before reading values.
  • Wrong fingerprint in assetlinks.json. Using the upload key instead of the Play app signing key means verification fails and links open in the browser on Android 12+.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is the difference between a deep link and a verified App Link?”

“How do you prevent intent redirection?”

“What changed for PendingIntent in recent Android versions?”

“How do you validate an intent received by an exported Activity?”

Quiz

What does android:autoVerify="true" on an https intent filter require?

An app targeting API 31+ creates a PendingIntent without FLAG_IMMUTABLE or FLAG_MUTABLE. What happens?

Which approach prevents intent redirection in an exported Activity?

A verified App Link arrives with extra keys your handler does not use. What should the handler do?

0 of 4 answered

Mini task

  1. Declare the link. Add DeepLinkActivity with android:exported="true" and an autoVerify intent filter for https://yourdomain.com/item/. Make every other Activity exported="false".

  2. Publish assetlinks.json. Get the SHA-256 fingerprint of your signing key (Play Console's app signing page for Play builds, or ./gradlew signingReport for local builds) and serve the file at https://yourdomain.com/.well-known/assetlinks.json.

  3. Write a pure parser. Create fun parseItemLink(uri: Uri): String? that returns the item ID only for https, your host, and a path of exactly /item/{id} where the ID matches [A-Za-z0-9_-]{1,64}. Unit test it with good and bad inputs.

  4. Route explicitly. In DeepLinkActivity, call the parser, start DetailActivity with a new explicit Intent carrying only the ID, then finish().

  5. Test. Run adb shell am start -a android.intent.action.VIEW -c android.intent.category.BROWSABLE -d "https://yourdomain.com/item/42" and confirm the detail screen opens. Then run adb shell am start -n com.example.app/.DetailActivity and confirm it fails because the Activity is not exported.

  6. Check verification. On an Android 12+ device, run adb shell pm get-app-links com.example.app and confirm your domain shows verified.

Done condition: valid links open the detail screen, malformed links do nothing, internal screens cannot be started from adb, and the domain shows as verified.

Next: CI/CD pipelines