From 209ea4299893d10ec1d7976ddff55f2756cc17c3 Mon Sep 17 00:00:00 2001 From: shakibuzzaman Date: Tue, 25 Aug 2026 14:44:48 +0600 Subject: [PATCH] fix: never let verification block a release build - Split the packaged scan per format: verifyDevConsolePackagedArtifact (APK/AAR, assemble path) and verifyDevConsolePackagedBundle (AAB, bundle path). One task naming both built an AAB during every release APK build, which broke Studio's signing wizard: -Pandroid.injected.apk.location puts the final AAB inside package's output dir, so Gradle rejects produceBundleIdeListingFile for an undeclared dependency. - Treat scan-limit-exceeded as a warning, not a violation. R8's mapping file overran the 64 MiB read cap and failed real release builds. - Skip BUNDLE-METADATA/ entries: Play strips them, and proguard.map names every class the build ever saw. - Warn instead of throwing FileNotFoundException on a missing or unreadable package. - Match forbidden paths at any segment, so assets/devconsole-web/ is also found at base/assets/devconsole-web/ inside an AAB. - Add devConsole.verificationEnabled / -Pdevconsole.verification.enabled=false to take verification off assemble/bundle, warning loudly and leaving verifyDevConsoleProtectedArtifacts runnable by name. Tests: 11 new functional tests, 42/42 pass. Verified against a real app on both assembleLiveRelease and bundleLiveRelease with the wizard's injected location. --- CHANGELOG.md | 44 +++ .../gradle/DevConsoleVariantPolicyPlugin.kt | 275 ++++++++++++++---- ...onsoleVariantPolicyPluginFunctionalTest.kt | 273 +++++++++++++++++ 3 files changed, 541 insertions(+), 51 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c1bd20a..2a9e716 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,50 @@ before it can reach a release. (There was briefly a separate `sdk:plugin-api` mo third-party plugin framework; it was removed before ever shipping — see Removed, below — so it never joined this list.) +## Unreleased + +Nothing this plugin does should ever be the reason a release cannot be built. Everything below comes +from one release APK build that the plugin stopped for reasons that had nothing to do with whether +the DevConsole runtime leaked. + +### Fixed + +- **A release APK build no longer builds an app bundle nobody asked for — or fails trying.** The + packaged-artifact scan named `SingleArtifact.APK` and `SingleArtifact.BUNDLE` on one task and hung + it off `assemble`, so every release APK build also ran `packageBundle`, + `signBundle` and `produceBundleIdeListingFile`. From Android Studio's "Generate + Signed APK" wizard that was fatal: the wizard passes `-Pandroid.injected.apk.location`, which puts + AGP's final AAB path *inside* `package`'s output directory, and Gradle then rejects + `produceBundleIdeListingFile` for consuming that directory without declaring a dependency + on `package`. The scan is now one task per packaging format — + `verifyDevConsolePackagedArtifact` for the APK/AAR on the assemble path, and a new + `verifyDevConsolePackagedBundle` for the AAB on the bundle path — so the plugin only ever + asks for artifacts the build was already going to produce. +- **A truncated read is no longer reported as a leak.** An entry too large to read to the end was + recorded as a `scan-limit-exceeded` violation, which failed release builds over the size of R8's + mapping file. Not finishing a read says nothing about what shipped: it is now a warning and an + `unscannable` list in the JSON report, and never fails a build on its own. +- **App-bundle build metadata is left out of the scan.** `BUNDLE-METADATA/` holds R8's `proguard.map` + and the dependency manifest; Play strips it, so nothing under it can carry DevConsole onto a + device. Reading it was the trigger for the false positive above, and the mapping file names every + class the build ever saw. +- **A missing or unreadable package is a warning, not a failed build.** Scanning an artifact the + build never produced threw `FileNotFoundException` out of the task. Whatever leaves an expected + artifact missing is a task-graph or environment problem, and must not stop a release. +- **Path-based detection now works inside app bundles.** An APK carries the dashboard at + `assets/devconsole-web/`, but a bundle nests every module under its own directory and carries it at + `base/assets/devconsole-web/`. Prefix matching was anchored at the start of the entry name, so it + matched in APKs and silently never matched in AABs — a gap that stayed hidden only while one task + scanned both formats and the APK caught the leak first. + +### Added + +- **`devConsole.verificationEnabled`**, also settable as `-Pdevconsole.verification.enabled=false`. + Takes verification off `assemble`/`bundle` so a build can always get out the door, warning loudly + every time and leaving `verifyDevConsoleProtectedArtifacts` runnable by name. A plugin that can + block a release needs a way past it that does not involve editing build files — the signing wizard + has no command line. Turning it off does not make a release safe to ship; it makes it unverified. + ## 1.3.1 — 2026-08-24 ### Changed diff --git a/gradle-plugin/src/main/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPlugin.kt b/gradle-plugin/src/main/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPlugin.kt index c47dfe1..0646401 100644 --- a/gradle-plugin/src/main/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPlugin.kt +++ b/gradle-plugin/src/main/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPlugin.kt @@ -42,6 +42,18 @@ import java.util.zip.ZipInputStream enum class DevConsoleVariantPolicy { ENABLED, DISABLED, PROTECTED } +/** + * One protected variant's packaged-artifact scans, split by the lifecycle task that produces each + * format so neither ever drags the other's packaging pipeline into the build. + * + * @property assembled scans what `assemble` produces -- the APK, or the AAR on a library. + * @property bundled scans what `bundle` produces. Null on a library, which has no bundle. + */ +internal data class VariantPackagedScans( + val assembled: TaskProvider, + val bundled: TaskProvider?, +) + abstract class DevConsoleExtension { /** * Variants that are allowed to carry the real DevConsole runtime. Defaults to `["debug"]`, which @@ -86,6 +98,22 @@ abstract class DevConsoleExtension { abstract val defaultPolicy: Property abstract val failBuildOnUnsafeVariant: Property + /** + * Whether verification runs as part of `assemble` / `bundle`. Defaults to true, + * and to the `devconsole.verification.enabled` Gradle property when a host sets one. + * + * The kill switch exists because this plugin sits directly on the release path, and a plugin that + * can stop a release from being built is a worse problem than the one it was written to prevent. + * If it ever misbehaves, `-Pdevconsole.verification.enabled=false` gets a build out the door + * without editing build files -- which matters when the build is being run from Android Studio's + * signing wizard rather than a command line. It logs a warning every time, and the verification + * tasks stay registered so `verifyDevConsoleProtectedArtifacts` still runs them on demand. + * + * Turning it off does not make a release safe to ship: it makes it unverified. Use it to unblock, + * then put it back. + */ + abstract val verificationEnabled: Property + /** * Adds the right DevConsole artifact per variant so hosts do not hand-write the debug/release * split -- writing `implementation` instead of `debugImplementation` is the mistake the variant @@ -159,6 +187,18 @@ abstract class VerifyDevConsoleProtectedArtifactsTask : DefaultTask() { } } +/** + * Scans the packages a single variant produced for DevConsole runtime content. + * + * One instance per variant *per packaging format*, never one covering both. A task's + * [packagedArtifacts] naming an artifact its own lifecycle task does not build pulls that artifact's + * whole production pipeline into the graph, and the plugin has no business deciding that + * `assembleRelease` should also build an AAB. See `registerPackagedArtifactScans`. + * + * This task only ever fails a build over an actual policy violation. A missing or unreadable + * artifact is reported as a warning: the point of the plugin is to keep the debugging runtime out of + * release packages, and it fails at that job just as badly if it stops a release from being built. + */ @DisableCachingByDefault( because = "its report embeds absolute file paths from packagedArtifacts, which are not reproducible " + "across machines/checkouts and would make a cached result misleading", @@ -179,10 +219,20 @@ abstract class VerifyDevConsolePackagedArtifactTask : DefaultTask() { val artifacts = packagedArtifacts.files .flatMap { artifact -> - if (artifact.isDirectory) { - artifact.walkTopDown().filter(File::isFile).toList() - } else { - listOf(artifact) + when { + artifact.isDirectory -> artifact.walkTopDown().filter(File::isFile).toList() + // An artifact this task was pointed at but that the build never produced is a + // task-graph problem, not a policy violation, and must never take a release + // build down with it -- see the class KDoc. Skipping it here keeps the scan + // reporting on what actually got packaged. + artifact.isFile -> listOf(artifact) + else -> { + logger.warn( + "DevConsole: skipping ${artifact.absolutePath} while verifying " + + "${variantName.get()} -- it was not produced by this build.", + ) + emptyList() + } } }.distinctBy(File::getAbsolutePath) .sortedBy(File::getAbsolutePath) @@ -194,10 +244,22 @@ abstract class VerifyDevConsolePackagedArtifactTask : DefaultTask() { sha256 = artifact.sha256(), ) } - val violations = artifacts.flatMap(::scanArtifact).distinct().sorted() + val findings = artifacts.flatMap(::scanArtifactSafely).distinct().sorted() + // An entry too big to read to the end is a hole in the scan's coverage, not evidence that + // anything leaked. Reporting it as a violation failed release builds over the size of R8's + // mapping file -- a build artifact that is not even delivered to a device. It stays in the + // report and in the log so the gap is visible, but it never fails a build on its own. + val (unscannable, violations) = findings.partition { it.contains(SCAN_LIMIT_MARKER) } val report = jsonReport.get() report.parentFile.mkdirs() - report.writeText(reportJson(inspected, violations)) + report.writeText(reportJson(inspected, violations, unscannable)) + if (unscannable.isNotEmpty()) { + logger.warn( + "DevConsole: could not scan ${unscannable.size} oversized entr" + + "${if (unscannable.size == 1) "y" else "ies"} in ${variantName.get()} " + + "-- ${unscannable.joinToString()}", + ) + } if (violations.isNotEmpty()) { val message = "Protected variant ${variantName.get()} contains forbidden DevConsole packaged content: " + @@ -206,14 +268,51 @@ abstract class VerifyDevConsolePackagedArtifactTask : DefaultTask() { } } + /** + * Reads one artifact, downgrading an I/O failure to a warning. A truncated, locked or otherwise + * unreadable package is an environment problem; failing the build over it would block a release + * for a reason that has nothing to do with whether DevConsole leaked into it. + */ + private fun scanArtifactSafely(artifact: File): List = + runCatching { scanArtifact(artifact) }.getOrElse { failure -> + logger.warn( + "DevConsole: could not read ${artifact.absolutePath} while verifying " + + "${variantName.get()} -- ${failure.message}. Skipping it.", + ) + emptyList() + } + + /** + * Forbidden path prefixes matching [entryName], anchored at any path segment rather than only at + * the start. + * + * An APK carries the dashboard at `assets/devconsole-web/`, but an app bundle nests every module + * under its own directory and carries the same files at `base/assets/devconsole-web/`. A plain + * `startsWith` therefore matched inside APKs and silently never matched inside AABs -- a gap that + * stayed hidden only while one task scanned both formats and the APK caught the leak first. + */ + private fun forbiddenPathsIn(entryName: String): List = + FORBIDDEN_ENTRY_PREFIXES.filter { prefix -> + entryName.startsWith(prefix) || entryName.contains("/$prefix") + } + + /** + * Whether an entry is app-bundle build metadata rather than shipped content. + * + * `BUNDLE-METADATA/` holds R8's `proguard.map` and the dependency manifest. Play strips it, so + * nothing under it can carry DevConsole onto a device -- and reading it is actively harmful: the + * mapping file for a large app runs past this scanner's read limit, and it names every class the + * build ever saw, so scanning it invites failures that say nothing about what shipped. + */ + private fun isBuildMetadata(entryName: String): Boolean = entryName.startsWith("BUNDLE-METADATA/") + private fun scanArtifact(artifact: File): List = when (artifact.extension.lowercase()) { "apk", "aab", "aar", "jar", "zip" -> ZipFile(artifact).use { zip -> - zip.entries().asSequence().flatMap { entry -> + zip.entries().asSequence().filterNot { isBuildMetadata(it.name) }.flatMap { entry -> val pathMatches = - FORBIDDEN_ENTRY_PREFIXES - .filter { entry.name.startsWith(it) } + forbiddenPathsIn(entry.name) .map { signature -> "${artifact.name}!/${entry.name} [$signature]" } if (entry.isDirectory) { pathMatches.asSequence() @@ -247,9 +346,7 @@ abstract class VerifyDevConsolePackagedArtifactTask : DefaultTask() { val entry = nested.nextEntry ?: break if (!entry.isDirectory) { val nestedLocation = "$location!/${entry.name}" - FORBIDDEN_ENTRY_PREFIXES - .filter { entry.name.startsWith(it) } - .forEach { add("$nestedLocation [$it]") } + forbiddenPathsIn(entry.name).forEach { add("$nestedLocation [$it]") } addAll(scanBounded(nested, MAX_NESTED_ENTRY_BYTES, nestedLocation)) } nested.closeEntry() @@ -268,7 +365,7 @@ abstract class VerifyDevConsolePackagedArtifactTask : DefaultTask() { ): List { val bounded = input.readBytesBounded(limit) return scanBytes(bounded.bytes, location) + - if (bounded.limitExceeded) listOf("$location [scan-limit-exceeded:$limit]") else emptyList() + if (bounded.limitExceeded) listOf("$location [$SCAN_LIMIT_MARKER$limit]") else emptyList() } private fun scanBytes( @@ -323,6 +420,7 @@ abstract class VerifyDevConsolePackagedArtifactTask : DefaultTask() { private fun reportJson( inspected: List, violations: List, + unscannable: List, ): String = buildString { append("{\n \"variant\":\"").append(variantName.get().jsonEscape()).append("\",\n") @@ -344,6 +442,12 @@ abstract class VerifyDevConsolePackagedArtifactTask : DefaultTask() { append("\n \"").append(violation.jsonEscape()).append('"') } if (violations.isNotEmpty()) append('\n').append(" ") + append("],\n \"unscannable\":[") + unscannable.forEachIndexed { index, entry -> + if (index > 0) append(',') + append("\n \"").append(entry.jsonEscape()).append('"') + } + if (unscannable.isNotEmpty()) append('\n').append(" ") append("]\n}\n") } @@ -373,6 +477,9 @@ abstract class VerifyDevConsolePackagedArtifactTask : DefaultTask() { ) private companion object { + /** Tags an entry the scanner could not read to the end. Never a violation -- see `verify`. */ + const val SCAN_LIMIT_MARKER = "scan-limit-exceeded:" + const val MAX_SCANNED_ENTRY_BYTES = 64 * 1024 * 1024 const val MAX_NESTED_ENTRY_BYTES = 16 * 1024 * 1024 @@ -403,6 +510,9 @@ abstract class VerifyDevConsolePackagedArtifactTask : DefaultTask() { // Bump in step with SDK_VERSION in convention-publishing; the tag must exist before this resolves. private const val DEFAULT_SDK_VERSION = "1.3.1" +/** Gradle property backing [DevConsoleExtension.verificationEnabled]. */ +private const val VERIFICATION_ENABLED_PROPERTY = "devconsole.verification.enabled" + /** JitPack's group for this repo — what auto-wiring declares. */ private const val DEVCONSOLE_GROUP = "com.github.devconsole-android.DevConsole" @@ -418,7 +528,7 @@ private val CORE_RUNTIME_COORDINATE_NAMES = setOf("devconsole", "devconsole-noop class DevConsoleVariantPolicyPlugin : Plugin { override fun apply(target: Project) = with(target) { - val packagedVerificationTasks = linkedMapOf>() + val packagedVerificationTasks = linkedMapOf() // variant name -> AGP build type name (e.g. "productionDebug" -> "debug"). Populated by the // AndroidComponentsExtension#onVariants callbacks in registerPackagedArtifactScans below. The // build type is what lets a flavored variant like "productionDebug" resolve against @@ -451,6 +561,9 @@ class DevConsoleVariantPolicyPlugin : Plugin { // restore the old release-pattern-only behavior. defaultPolicy.convention(DevConsoleVariantPolicy.PROTECTED) failBuildOnUnsafeVariant.convention(true) + verificationEnabled.convention( + providers.gradleProperty(VERIFICATION_ENABLED_PROPERTY).map(String::toBoolean).orElse(true), + ) autoWireDependencies.convention(true) sdkVersion.convention(DEFAULT_SDK_VERSION) } @@ -512,9 +625,25 @@ class DevConsoleVariantPolicyPlugin : Plugin { } } + /** + * Registers the packaged-artifact scans for every protected variant, **one task per packaging + * format**, and records them in [scans] so `registerProtectedVerifier` can hang each one off the + * lifecycle task that actually produces its format. + * + * A task's inputs decide what Gradle builds. When a single task named both `SingleArtifact.APK` + * and `SingleArtifact.BUNDLE` and hung off `assemble`, asking for a release APK also + * built the AAB -- `packageReleaseBundle`, `signReleaseBundle` and + * `produceBundleIdeListingFile` all joined an APK-only graph. Besides the wasted build + * time, it broke Android Studio's "Generate Signed APK" wizard outright: the wizard passes + * `-Pandroid.injected.apk.location`, which puts AGP's final AAB path *inside* + * `package`'s output directory, and Gradle then rejects + * `produceBundleIdeListingFile` for consuming that directory without declaring a + * dependency on `package`. Keeping each format on its own task means the plugin only + * ever asks for artifacts the build was already going to produce. + */ private fun Project.registerPackagedArtifactScans( extension: DevConsoleExtension, - scans: MutableMap>, + scans: MutableMap, actualVariantBuildTypes: MutableMap, ) { plugins.withId("com.android.application") { @@ -525,22 +654,27 @@ class DevConsoleVariantPolicyPlugin : Plugin { if (variantPolicy(variant.name, variant.buildType, extension) != DevConsoleVariantPolicy.PROTECTED) { return@onVariants } - scans[variant.name] = - tasks.register( - "verify${variant.name.capitalized()}DevConsolePackagedArtifact", + scans[variant.name] = VariantPackagedScans( + // Keeps the historical task name: this is the scan on the assemble path, the + // one hosts and CI already invoke. + assembled = registerPackagedScan( + extension = extension, + taskName = "verify${variant.name.capitalized()}DevConsolePackagedArtifact", + variantName = variant.name, + reportName = "${variant.name}-artifacts", ) { - group = "verification" - variantName.set(variant.name) - failOnUnsafeVariant.set(extension.failBuildOnUnsafeVariant) - packagedArtifacts.from(variant.artifacts.get(SingleArtifact.APK)) - packagedArtifacts.from(variant.artifacts.get(SingleArtifact.BUNDLE)) - packagedArtifacts.from(variant.artifacts.get(SingleArtifact.MERGED_MANIFEST)) - jsonReport.set( - layout.buildDirectory.file( - "reports/devconsole/${variant.name}-artifacts.json", - ).map { it.asFile }, - ) - } + it.from(variant.artifacts.get(SingleArtifact.APK)) + it.from(variant.artifacts.get(SingleArtifact.MERGED_MANIFEST)) + }, + bundled = registerPackagedScan( + extension = extension, + taskName = "verify${variant.name.capitalized()}DevConsolePackagedBundle", + variantName = variant.name, + reportName = "${variant.name}-bundle", + ) { + it.from(variant.artifacts.get(SingleArtifact.BUNDLE)) + }, + ) } } plugins.withId("com.android.library") { @@ -551,25 +685,40 @@ class DevConsoleVariantPolicyPlugin : Plugin { if (variantPolicy(variant.name, variant.buildType, extension) != DevConsoleVariantPolicy.PROTECTED) { return@onVariants } - scans[variant.name] = - tasks.register( - "verify${variant.name.capitalized()}DevConsolePackagedArtifact", + // A library has no bundle task, so there is no second format to scan. + scans[variant.name] = VariantPackagedScans( + assembled = registerPackagedScan( + extension = extension, + taskName = "verify${variant.name.capitalized()}DevConsolePackagedArtifact", + variantName = variant.name, + reportName = "${variant.name}-artifacts", ) { - group = "verification" - variantName.set(variant.name) - failOnUnsafeVariant.set(extension.failBuildOnUnsafeVariant) - packagedArtifacts.from(variant.artifacts.get(SingleArtifact.AAR)) - packagedArtifacts.from(variant.artifacts.get(SingleArtifact.MERGED_MANIFEST)) - jsonReport.set( - layout.buildDirectory.file( - "reports/devconsole/${variant.name}-artifacts.json", - ).map { it.asFile }, - ) - } + it.from(variant.artifacts.get(SingleArtifact.AAR)) + it.from(variant.artifacts.get(SingleArtifact.MERGED_MANIFEST)) + }, + bundled = null, + ) } } } + private fun Project.registerPackagedScan( + extension: DevConsoleExtension, + taskName: String, + variantName: String, + reportName: String, + artifacts: (ConfigurableFileCollection) -> Unit, + ): TaskProvider = + tasks.register(taskName) { + group = "verification" + this.variantName.set(variantName) + failOnUnsafeVariant.set(extension.failBuildOnUnsafeVariant) + artifacts(packagedArtifacts) + jsonReport.set( + layout.buildDirectory.file("reports/devconsole/$reportName.json").map { it.asFile }, + ) + } + /** * Resolves a variant's policy. [buildType] is the AGP build-type name backing this variant (e.g. * "debug" for the flavored variant "productionDebug") -- read from AGP's own variant model rather @@ -677,23 +826,33 @@ class DevConsoleVariantPolicyPlugin : Plugin { policies: Map, report: TaskProvider, extension: DevConsoleExtension, - packagedVerificationTasks: Map>, + packagedScans: Map, ) { val protectedPaths = extension.protectedDependencyPaths.get() val protectedVariants = policies.filterValues { it == DevConsoleVariantPolicy.PROTECTED }.keys + val wireOntoLifecycleTasks = extension.verificationEnabled.get() + if (!wireOntoLifecycleTasks) { + logger.warn( + "DevConsole: verification is switched off for project '$path' via " + + "$VERIFICATION_ENABLED_PROPERTY, so assemble/bundle will not check that the " + + "DevConsole runtime stayed out of ${protectedVariants.joinToString()}. Anything " + + "built this way is unverified -- switch it back on before shipping.", + ) + } // One verifier task per protected variant, never a single shared one. A shared task carries // every protected variant's runtime classpath and packaged artifact as its own inputs, so // wiring it onto assemble made building one variant resolve -- and on a flavored // project fully build -- every other protected variant too: `assembleProductionRelease` // dragged `dexBuilderStagingRelease`, `bundleStagingRelease` and every other flavor's // dependency download into the graph. Per-variant tasks keep each variant's inputs to itself. - val verifiers = protectedVariants.map { variant -> + val verifiers = protectedVariants.flatMap { variant -> + // Dependency-graph checks only: no packaged artifact among its inputs, so it is safe to + // hang off both lifecycle tasks without deciding anything about what gets packaged. val verifier = tasks.register( "verify${variant.capitalized()}DevConsoleProtectedArtifacts", ) { group = "verification" dependsOn(report) - packagedVerificationTasks[variant]?.let { packaged -> dependsOn(packaged) } violations.set(declaredViolations(variant, protectedPaths)) resolvedRuntimeComponents.put(variant, resolvedRuntimeComponents(variant)) protectedProjectPaths.set(protectedPaths) @@ -706,14 +865,28 @@ class DevConsoleVariantPolicyPlugin : Plugin { // lazy and safe even when a task name does not exist for this project type (e.g. // bundle on a library module, which has no bundle task) -- it never forces the task // to be created, it just configures it if and when it is. + // + // Each packaged scan goes on the lifecycle task that produces its format, and nowhere else. + // Hanging the AAB scan off assemble is what made a release APK build an AAB it was + // never asked for -- see registerPackagedArtifactScans for what that broke. + val scans = packagedScans[variant] val capitalized = variant.capitalized() - tasks.matching { it.name == "assemble$capitalized" }.configureEach { it.dependsOn(verifier) } - tasks.matching { it.name == "bundle$capitalized" }.configureEach { it.dependsOn(verifier) } - verifier + if (wireOntoLifecycleTasks) { + tasks.matching { it.name == "assemble$capitalized" }.configureEach { assemble -> + assemble.dependsOn(verifier) + scans?.assembled?.let { scan -> assemble.dependsOn(scan) } + } + tasks.matching { it.name == "bundle$capitalized" }.configureEach { bundle -> + bundle.dependsOn(verifier) + scans?.bundled?.let { scan -> bundle.dependsOn(scan) } + } + } + listOfNotNull(verifier, scans?.assembled, scans?.bundled) } // Aggregate lifecycle task: the name hosts and CI already invoke, and what `check` hangs off. // Asking for it explicitly still verifies every protected variant -- it just is no longer on - // any single variant's build path. + // any single variant's build path. This one deliberately covers every format, so `check` on a + // flavored app does build the AABs; that is the price of asking for full verification by name. val aggregate = tasks.register("verifyDevConsoleProtectedArtifacts") { task -> task.group = "verification" task.description = "Verifies every protected variant excludes the full DevConsole runtime." diff --git a/gradle-plugin/src/test/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPluginFunctionalTest.kt b/gradle-plugin/src/test/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPluginFunctionalTest.kt index e94898a..51d4bbd 100644 --- a/gradle-plugin/src/test/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPluginFunctionalTest.kt +++ b/gradle-plugin/src/test/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPluginFunctionalTest.kt @@ -10,6 +10,8 @@ import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import java.io.File +import java.util.zip.ZipEntry +import java.util.zip.ZipOutputStream class DevConsoleVariantPolicyPluginFunctionalTest { @get:Rule @@ -117,6 +119,25 @@ class DevConsoleVariantPolicyPluginFunctionalTest { ) } + /** + * Writes a zip into the fixture's project directory. Built here rather than in the fixture's + * build script because Kotlin DSL resolves `java` to Gradle's `java` extension, so a script + * cannot name `java.util.zip` at all. + */ + private fun writeZip( + relativePath: String, + vararg entries: Pair, + ) { + val target = File(projectDir.root, relativePath).apply { parentFile.mkdirs() } + ZipOutputStream(target.outputStream().buffered()).use { zip -> + entries.forEach { (name, bytes) -> + zip.putNextEntry(ZipEntry(name)) + zip.write(bytes) + zip.closeEntry() + } + } + } + private fun runner(vararg args: String): GradleRunner = GradleRunner.create() // AGP 8.13.0 requires Gradle 8.13+ and is not compatible with Gradle 9.x, so pin the TestKit // daemon to 8.14.3 (the repo's own wrapper version) rather than inheriting any 9.x Gradle. @@ -1005,10 +1026,262 @@ class DevConsoleVariantPolicyPluginFunctionalTest { assertTrue(result.output, !result.output.contains("PartnerRelease")) } + @Test + fun `assembleRelease builds a clean protected variant to completion without building an app bundle`() { + writeFixture( + devConsoleBlock = "", + androidPlugin = "com.android.application", + applicationIdLine = + """ + applicationId = "io.devconsole.fixture" + versionCode = 1 + """.trimIndent(), + ) + + val result = runner("assembleRelease").build() + + assertTrue(result.output, result.output.contains("BUILD SUCCESSFUL")) + assertTrue(result.output, result.output.contains(":verifyReleaseDevConsolePackagedArtifact")) + // The packaged scan naming SingleArtifact.BUNDLE alongside SingleArtifact.APK dragged the whole + // bundle pipeline into every release APK build -- wasted work, and the direct cause of the + // wizard failure the next test covers. + BUNDLE_PIPELINE_TASKS.forEach { task -> + assertTrue(result.output, !result.output.contains(task)) + } + } + + @Test + fun `assembleRelease builds to completion from the Studio signed-APK wizard's injected output location`() { + writeFixture( + devConsoleBlock = "", + androidPlugin = "com.android.application", + applicationIdLine = + """ + applicationId = "io.devconsole.fixture" + versionCode = 1 + """.trimIndent(), + ) + val destination = File(projectDir.root, "wizard-out").apply { mkdirs() } + + // What Android Studio's "Generate Signed Bundle / APK" wizard passes. It puts AGP's final AAB + // path inside package's output directory, so any graph holding both package + // and produceBundleIdeListingFile is rejected by Gradle for an undeclared dependency. + // An APK build has no business containing the latter; it only did because of the packaged scan. + val result = runner( + "assembleRelease", + "-Pandroid.injected.apk.location=${destination.absolutePath}", + ).build() + + assertTrue(result.output, result.output.contains("BUILD SUCCESSFUL")) + } + + @Test + fun `bundleRelease builds to completion from the Studio signed-bundle wizard's injected output location`() { + writeFixture( + devConsoleBlock = "", + androidPlugin = "com.android.application", + applicationIdLine = + """ + applicationId = "io.devconsole.fixture" + versionCode = 1 + """.trimIndent(), + ) + val destination = File(projectDir.root, "wizard-out").apply { mkdirs() } + + val result = runner( + "bundleRelease", + "-Pandroid.injected.apk.location=${destination.absolutePath}", + ).build() + + assertTrue(result.output, result.output.contains("BUILD SUCCESSFUL")) + assertTrue(result.output, result.output.contains(":verifyReleaseDevConsolePackagedBundle")) + } + + @Test + fun `bundleRelease still opens the app bundle and rejects content only the package reveals`() { + writeFixture( + devConsoleBlock = "autoWireDependencies.set(false)", + androidPlugin = "com.android.application", + applicationIdLine = + """ + applicationId = "io.devconsole.fixture" + versionCode = 1 + """.trimIndent(), + ) + // Nothing in the dependency graph gives this away -- only reading the packaged bytes does. So + // a failure here proves the AAB itself was opened, which is the coverage the split must keep. + File(projectDir.root, "src/main/assets/devconsole-web/index.html").apply { parentFile.mkdirs() } + .writeText("forbidden dashboard") + + val result = runner("bundleRelease").buildAndFail() + + assertTrue(result.output, result.output.contains("assets/devconsole-web/")) + assertTrue(result.output, result.output.contains(".aab!/")) + } + + @Test + fun `a packaged artifact the build never produced is a warning, not a failed release`() { + writeFixture( + devConsoleBlock = "", + androidPlugin = "com.android.application", + applicationIdLine = + """ + applicationId = "io.devconsole.fixture" + versionCode = 1 + """.trimIndent(), + // Points a scan at a path nothing writes. Whatever leaves an expected artifact missing -- + // a task-graph mistake here, an AGP change, a host's own output redirection -- must never + // be the reason a release build fails. This used to throw FileNotFoundException. + extraBuildScript = + """ + tasks.register("verifyMissingArtifact") { + variantName.set("release") + failOnUnsafeVariant.set(true) + packagedArtifacts.from(layout.buildDirectory.file("nowhere/absent.aab")) + jsonReport.set(layout.buildDirectory.file("reports/devconsole/absent.json").map { it.asFile }) + } + """.trimIndent(), + ) + + val result = runner("verifyMissingArtifact").build() + + assertTrue(result.output, result.output.contains("BUILD SUCCESSFUL")) + assertTrue(result.output, result.output.contains("it was not produced by this build")) + } + + @Test + fun `an entry too large to read through is reported but does not fail the build`() { + writeFixture( + devConsoleBlock = "autoWireDependencies.set(false)", + androidPlugin = "com.android.application", + applicationIdLine = + """ + applicationId = "io.devconsole.fixture" + versionCode = 1 + """.trimIndent(), + // A real liveRelease AAB failed on exactly this: R8's mapping file ran past the scanner's + // 64 MiB read limit, and the resulting "scan-limit-exceeded" note was counted as a + // violation. Not finishing a read says nothing about what leaked, and must never stop a + // release. Hence the deliberately oversized entry below. + extraBuildScript = + """ + tasks.register("verifyOversized") { + variantName.set("release") + failOnUnsafeVariant.set(true) + packagedArtifacts.from(file("oversized.zip")) + jsonReport.set(layout.buildDirectory.file("reports/devconsole/oversized.json").map { it.asFile }) + } + """.trimIndent(), + ) + // One entry past the scanner's 64 MiB read limit. Harmless content: the point is that the read + // cannot finish, not what is in it. + writeZip("oversized.zip", "huge.txt" to ByteArray(65 * 1024 * 1024) { 'a'.code.toByte() }) + + val result = runner("verifyOversized").build() + + assertTrue(result.output, result.output.contains("BUILD SUCCESSFUL")) + assertTrue(result.output, result.output.contains("could not scan")) + val report = File(projectDir.root, "build/reports/devconsole/oversized.json").readText() + assertTrue(report, report.contains("scan-limit-exceeded")) + assertTrue(report, report.contains("\"violations\":[]")) + } + + @Test + fun `app bundle build metadata is left out of the scan`() { + writeFixture( + devConsoleBlock = "autoWireDependencies.set(false)", + androidPlugin = "com.android.application", + applicationIdLine = + """ + applicationId = "io.devconsole.fixture" + versionCode = 1 + """.trimIndent(), + // BUNDLE-METADATA is Play-stripped build output, so a DevConsole name appearing there says + // nothing about what reaches a device -- R8's mapping file names every class the build saw. + extraBuildScript = + """ + tasks.register("verifyFakeBundle") { + variantName.set("release") + failOnUnsafeVariant.set(true) + packagedArtifacts.from(file("fake.aab")) + jsonReport.set(layout.buildDirectory.file("reports/devconsole/fake-bundle.json").map { it.asFile }) + } + """.trimIndent(), + ) + writeZip( + "fake.aab", + "BUNDLE-METADATA/com.android.tools.build.obfuscation/proguard.map" to + "DEVCONSOLE_ENABLED_FULL_V1".toByteArray(), + ) + + val result = runner("verifyFakeBundle").build() + + assertTrue(result.output, result.output.contains("BUILD SUCCESSFUL")) + } + + @Test + fun `the verification kill switch lets a violating release build ship anyway, loudly`() { + writeFixture( + devConsoleBlock = "autoWireDependencies.set(false)", + androidPlugin = "com.android.application", + applicationIdLine = + """ + applicationId = "io.devconsole.fixture" + versionCode = 1 + """.trimIndent(), + ) + File( + projectDir.root, + "src/main/java/io/devconsole/internal/enabled/FullRuntimeMarker.java", + ).apply { parentFile.mkdirs() } + .writeText( + """ + package io.devconsole.internal.enabled; + public final class FullRuntimeMarker { + public static final String SIGNATURE = "DEVCONSOLE_ENABLED_FULL_V1"; + } + """.trimIndent(), + ) + + // Same project that `assembleRelease fails a violating project, not just check` proves is + // rejected. Nothing this plugin does should ever be the reason a release cannot be built at + // all, so there has to be a way past it that does not involve editing build files. + val result = runner("assembleRelease", "-Pdevconsole.verification.enabled=false").build() + + assertTrue(result.output, result.output.contains("BUILD SUCCESSFUL")) + assertTrue(result.output, result.output.contains("verification is switched off")) + assertTrue(result.output, !result.output.contains(":verifyReleaseDevConsolePackagedArtifact")) + } + + @Test + fun `the kill switch leaves the verification tasks runnable by name`() { + writeFixture( + devConsoleBlock = "autoWireDependencies.set(false)", + androidPlugin = "com.android.application", + applicationIdLine = + """ + applicationId = "io.devconsole.fixture" + versionCode = 1 + """.trimIndent(), + ) + File(projectDir.root, "src/main/assets/devconsole-web/index.html").apply { parentFile.mkdirs() } + .writeText("forbidden dashboard") + + // Off the release path, not gone: a host that switched the wiring off can still audit. + val result = runner("verifyDevConsoleProtectedArtifacts", "-Pdevconsole.verification.enabled=false") + .buildAndFail() + + assertTrue(result.output, result.output.contains("assets/devconsole-web/")) + } + private companion object { /** A valid, empty zip -- enough for Gradle to accept the stub as a jar artifact. */ val EMPTY_JAR_BYTES = byteArrayOf(0x50, 0x4B, 0x05, 0x06) + ByteArray(18) + + /** Tasks that only ever run when the build was actually asked for an app bundle. */ + val BUNDLE_PIPELINE_TASKS = + listOf(":packageReleaseBundle", ":signReleaseBundle", ":produceReleaseBundleIdeListingFile") } }