Repository navigation
Expand file tree
/
Copy pathbuild.gradle.kts
More file actions
715 lines (650 loc) · 28.1 KB
/
Copy pathbuild.gradle.kts
File metadata and controls
715 lines (650 loc) · 28.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
import java.util.zip.ZipFile
import javax.imageio.ImageIO
data class AppReleaseVersion(
val name: String,
val code: Int,
)
fun parseAppReleaseVersion(buildFile: File): AppReleaseVersion {
val text = buildFile.readText()
val name =
Regex("""(?m)^\s*versionName\s*=\s*"([^"]+)"\s*$""")
.find(text)
?.groupValues
?.get(1)
?: error("app/build.gradle.kts must declare versionName")
val code =
Regex("""(?m)^\s*versionCode\s*=\s*(\d+)\s*$""")
.find(text)
?.groupValues
?.get(1)
?.toInt()
?: error("app/build.gradle.kts must declare versionCode")
return AppReleaseVersion(name, code)
}
data class SigningSecretFinding(
val path: String,
val line: Int,
val kind: String,
)
fun isExternalSecretReference(value: String): Boolean {
val normalized = value.trim()
val interpolation = Regex("""\$\{[^}]*}""")
val lookupPrefixes =
listOf(
"System.getenv(",
"signingProp(",
"findProperty(",
"project.findProperty(",
"rootProject.findProperty(",
"providers.",
"property(",
)
return normalized.isBlank() ||
normalized in setOf("...", "<redacted>", "<secret>", "<password>") ||
interpolation.containsMatchIn(normalized) ||
lookupPrefixes.any(normalized::startsWith)
}
fun findSigningSecretFindings(
path: String,
text: String,
): List<SigningSecretFinding> {
val privateKeyHeader =
Regex("""-----BEGIN\s+(?:RSA\s+|EC\s+|OPENSSH\s+)?PRIVATE KEY-----""", RegexOption.IGNORE_CASE)
val quotedPasswordAssignment =
Regex(
"""\b(?:storePassword|keyPassword|keystorePassword)\s*=\s*["']([^"']+)["']""",
RegexOption.IGNORE_CASE,
)
val namedPasswordAssignment =
Regex(
"""^\s*["']?(?:RELEASE_(?:STORE|KEY)_PASSWORD|STORE_PASSWORD|KEY_PASSWORD)["']?\s*[=:]\s*(.+?)\s*$""",
RegexOption.IGNORE_CASE,
)
return buildList {
text.lineSequence().forEachIndexed { index, line ->
if (privateKeyHeader.containsMatchIn(line)) {
add(SigningSecretFinding(path, index + 1, "private-key material"))
}
quotedPasswordAssignment.findAll(line).forEach { match ->
if (!isExternalSecretReference(match.groupValues[1])) {
add(SigningSecretFinding(path, index + 1, "literal signing password"))
}
}
namedPasswordAssignment.find(line)?.let { match ->
val value =
match.groupValues[1]
.trim()
.removeSuffix(",")
.trim()
.removeSurrounding("\"")
.removeSurrounding("'")
if (!isExternalSecretReference(value)) {
add(SigningSecretFinding(path, index + 1, "literal credential property"))
}
}
}
}.distinct()
}
fun requireNoTrackedSigningSecrets(findings: List<SigningSecretFinding>) {
check(findings.isEmpty()) {
"Tracked signing-secret preflight failed:\n" +
findings.joinToString("\n") { finding ->
"- ${finding.path}:${finding.line}: ${finding.kind}"
}
}
}
private val signingKeyContainerExtensions = setOf("jks", "keystore", "p12", "pfx")
/**
* Decode only files that look like UTF-8 text. Every tracked file reaches
* this content sniff; binary assets are skipped because password assignments
* and PEM headers cannot be meaningfully searched in arbitrary binary data.
*/
fun readTextForSigningSecretScan(file: File): String? {
val bytes = file.readBytes()
if (bytes.isEmpty()) return ""
val sample = bytes.take(8_192)
if (sample.any { byte -> byte == 0.toByte() }) return null
val decoder =
Charsets.UTF_8
.newDecoder()
.onMalformedInput(java.nio.charset.CodingErrorAction.REPORT)
.onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT)
return runCatching {
decoder.decode(java.nio.ByteBuffer.wrap(bytes)).toString()
}.getOrNull()
}
fun scanTrackedSigningFiles(
files: List<File>,
relativeTo: File,
): List<SigningSecretFinding> =
files.flatMap { file ->
if (!file.isFile) {
emptyList()
} else {
val path = file.relativeTo(relativeTo).invariantSeparatorsPath
if (file.extension.lowercase() in signingKeyContainerExtensions) {
listOf(SigningSecretFinding(path, 1, "signing key container"))
} else {
readTextForSigningSecretScan(file)
?.let { text -> findSigningSecretFindings(path, text) }
.orEmpty()
}
}
}
val appReleaseVersion = parseAppReleaseVersion(file("app/build.gradle.kts"))
val bundledRuntimeAssets =
setOf(
"assets/spam_numbers.manifest.json",
"assets/hot_numbers.json",
"assets/hot_ranges.json",
"assets/spam_domains.json",
"assets/community_watch.json",
"assets/spam_model_weights.json",
"assets/list_catalog.json",
)
fun verifyApkDataPrivacy(apkFile: File) {
val dataRoot = layout.projectDirectory.dir("data").asFile
val repositoryDataAssets =
dataRoot
.walkTopDown()
.filter { it.isFile }
.map { "assets/${it.relativeTo(dataRoot).invariantSeparatorsPath}" }
.toSet()
val bundledShardAssets = repositoryDataAssets.filter { it.startsWith("assets/spam_number_shards/") }.toSet()
val expectedRuntimeAssets = bundledRuntimeAssets + bundledShardAssets
ZipFile(apkFile).use { zip ->
val packagedAssets =
zip.entries().asSequence()
.map { it.name }
.filter { it.startsWith("assets/") && !it.endsWith("/") }
.toSet()
val missing = expectedRuntimeAssets - packagedAssets
val leaked = (packagedAssets intersect repositoryDataAssets) - expectedRuntimeAssets
check(missing.isEmpty()) {
"APK is missing required bundled feeds: ${missing.sorted().joinToString()}"
}
check(leaked.isEmpty()) {
"APK contains non-runtime repository data: ${leaked.sorted().joinToString()}"
}
}
}
plugins {
alias(libs.plugins.android.application) apply false
alias(libs.plugins.kotlin.android) apply false
alias(libs.plugins.kotlin.compose) apply false
alias(libs.plugins.ksp) apply false
alias(libs.plugins.kover) apply false
alias(libs.plugins.ktlint) apply false
alias(libs.plugins.detekt) apply false
alias(libs.plugins.hilt) apply false
alias(libs.plugins.room) apply false
}
allprojects {
dependencyLocking {
lockAllConfigurations()
}
}
tasks.register("verifyReproducibleBuildInputs") {
group = "verification"
description = "Fails when Gradle build scripts embed wall-clock build metadata."
val scanTargets = files(
"build.gradle.kts",
"settings.gradle.kts",
"app/build.gradle.kts",
"gradle/libs.versions.toml"
)
inputs.files(scanTargets)
doLast {
val forbiddenTokens = listOf(
"System.current" + "TimeMillis",
"Instant" + ".now",
"LocalDate" + ".now",
"LocalDateTime" + ".now",
"OffsetDateTime" + ".now",
"ZonedDateTime" + ".now",
"Date" + "()",
"BUILD" + "_TIME",
"BUILD" + "_TIMESTAMP",
"build" + "_time",
"build" + "_timestamp"
)
val hits = scanTargets.files
.filter { it.isFile }
.flatMap { file ->
val text = file.readText()
forbiddenTokens
.filter { token -> text.contains(token) }
.map { token -> "${file.relativeTo(rootDir).invariantSeparatorsPath}: $token" }
}
check(hits.isEmpty()) {
"Build scripts must not embed wall-clock metadata into the APK:\n${hits.joinToString("\n")}"
}
}
}
tasks.register<Exec>("verifyReleaseDrift") {
group = "verification"
description = "Reports release version, dependency-lock, advisory, and source-snapshot drift."
val script = layout.projectDirectory.file("scripts/verify_release_drift.py")
inputs.files(
script,
layout.projectDirectory.file("scripts/release_advisories.json"),
layout.projectDirectory.file("app/build.gradle.kts"),
layout.projectDirectory.file("gradle/libs.versions.toml"),
layout.projectDirectory.file("app/gradle.lockfile"),
layout.projectDirectory.file("gradle/wrapper/gradle-wrapper.properties"),
layout.projectDirectory.file("README.md"),
layout.projectDirectory.file("CHANGELOG.md"),
layout.projectDirectory.file("app/src/main/java/com/sysadmindoc/callshield/ui/screens/more/ChangelogScreen.kt"),
layout.projectDirectory.file("fastlane/metadata/android/en-US/changelogs/${appReleaseVersion.code}.txt"),
layout.projectDirectory.file("data/source-manifest.json"),
layout.projectDirectory.file("data/source-snapshot.json"),
)
workingDir(rootDir)
commandLine("python", script.asFile.absolutePath)
}
val releaseArtifactDirectory = layout.projectDirectory.dir("app/build/outputs/apk/release")
val releaseArtifactCandidates = listOf(
releaseArtifactDirectory.file("app-release.apk"),
releaseArtifactDirectory.file("app-release-unsigned.apk"),
)
val releaseSbomScript = layout.projectDirectory.file("scripts/release_sbom.py")
fun resolveReleaseArtifact(): java.io.File {
val metadataFile = releaseArtifactDirectory.file("output-metadata.json").asFile
val metadataName =
if (metadataFile.isFile) {
Regex(""""outputFile"\s*:\s*"([^"]+\.apk)"""")
.find(metadataFile.readText())
?.groupValues
?.getOrNull(1)
} else {
null
}
val artifact =
metadataName
?.let { releaseArtifactDirectory.file(it).asFile }
?.takeIf { it.isFile }
?: releaseArtifactCandidates
.map { it.asFile }
.firstOrNull { it.isFile }
return artifact ?: error(
"Release artifact does not exist in ${releaseArtifactDirectory.asFile}; " +
"expected the APK named by output-metadata.json.",
)
}
tasks.register<Exec>("generateReleaseSbom") {
group = "verification"
description = "Generates a CycloneDX SBOM and in-toto provenance for the release APK."
dependsOn(":app:assembleRelease")
inputs.files(
releaseSbomScript,
layout.projectDirectory.file("app/build.gradle.kts"),
layout.projectDirectory.file("app/gradle.lockfile"),
layout.projectDirectory.file("gradle/wrapper/gradle-wrapper.properties"),
releaseArtifactCandidates,
releaseArtifactDirectory.file("output-metadata.json"),
)
outputs.files(
releaseArtifactDirectory.asFileTree.matching {
include("*.cdx.json", "*.provenance.json", "*.sha256")
},
)
workingDir(rootDir)
doFirst {
commandLine(
"python",
releaseSbomScript.asFile.absolutePath,
"generate",
"--artifact",
resolveReleaseArtifact().absolutePath,
"--output-dir",
releaseArtifactDirectory.asFile.absolutePath,
)
}
}
tasks.register<Exec>("verifyReleaseSbom") {
group = "verification"
description = "Verifies the release APK, CycloneDX SBOM, provenance, and SHA-256 sidecar agree."
dependsOn("verifyReleaseMetadata", "generateReleaseSbom")
inputs.files(
releaseSbomScript,
releaseArtifactCandidates,
releaseArtifactDirectory.file("output-metadata.json"),
releaseArtifactDirectory.asFileTree.matching {
include("*.cdx.json", "*.provenance.json", "*.sha256")
},
)
workingDir(rootDir)
doFirst {
commandLine(
"python",
releaseSbomScript.asFile.absolutePath,
"verify",
"--artifact",
resolveReleaseArtifact().absolutePath,
"--output-dir",
releaseArtifactDirectory.asFile.absolutePath,
)
}
}
tasks.register<Exec>("verifyLiveCertificatePins") {
group = "verification"
description = "Fails when a pinned host serves a chain holding none of the app's pins. Needs network."
val script = layout.projectDirectory.file("scripts/check_live_pins.py")
inputs.files(
script,
layout.projectDirectory.file("app/src/main/java/com/sysadmindoc/callshield/data/remote/HttpClient.kt"),
)
// The answer depends on what the servers present today, not on any input file.
outputs.upToDateWhen { false }
workingDir(rootDir)
commandLine("python", script.asFile.absolutePath)
}
tasks.register("verifyReleaseApkReproducibleMetadata") {
group = "verification"
description = "Fails when the release APK contains AGP VCS metadata."
// A release whose pins no longer match the live chain downloads nothing on
// any device; three releases shipped that way from 2026-08-02.
dependsOn("verifyReleaseMetadata", ":app:assembleRelease", "verifyReleaseSbom", "verifyLiveCertificatePins")
val releaseOutput = layout.projectDirectory.dir("app/build/outputs/apk/release")
inputs.dir(releaseOutput)
doLast {
val apks =
releaseOutput.asFile
.listFiles { file -> file.isFile && file.extension.equals("apk", ignoreCase = true) }
.orEmpty()
.toList()
check(apks.size == 1) {
"Expected exactly one release APK, found ${apks.map { it.name }.sorted()}"
}
val apk = apks.single()
verifyApkDataPrivacy(apk)
ZipFile(apk).use { zip ->
check(zip.getEntry("META-INF/version-control-info.textproto") == null) {
"Release APK must not contain META-INF/version-control-info.textproto; " +
"disable android.vcsInfo.include for reproducible releases."
}
}
}
}
tasks.register("verifyReleaseMetadata") {
group = "verification"
description = "Fails when release, store listing, or README metadata drifts from the app."
dependsOn("verifyTrackedSigningSecrets", "verifyReleaseDrift")
val readme = layout.projectDirectory.file("README.md")
val storeDescription = layout.projectDirectory.file("fastlane/metadata/android/en-US/full_description.txt")
val storeShortDescription = layout.projectDirectory.file("fastlane/metadata/android/en-US/short_description.txt")
val storeChangelog =
layout.projectDirectory.file(
"fastlane/metadata/android/en-US/changelogs/${appReleaseVersion.code}.txt",
)
val storeImages = layout.projectDirectory.dir("fastlane/metadata/android/en-US/images")
val signingPreflight = layout.projectDirectory.file("scripts/verify-release-signing.ps1")
val changelog = layout.projectDirectory.file("CHANGELOG.md")
val changelogScreen =
layout.projectDirectory.file(
"app/src/main/java/com/sysadmindoc/callshield/ui/screens/more/ChangelogScreen.kt",
)
inputs.files(
"app/build.gradle.kts",
readme,
storeDescription,
storeShortDescription,
storeChangelog,
signingPreflight,
changelog,
changelogScreen,
)
inputs.dir(storeImages)
doLast {
val issues = mutableListOf<String>()
val readmeText = readme.asFile.readText()
val fullDescription = storeDescription.asFile.readText()
val shortDescription = storeShortDescription.asFile.readText()
val signingPreflightText = signingPreflight.asFile.readText()
val changelogText = changelog.asFile.readText()
val changelogScreenText = changelogScreen.asFile.readText()
if ("## v${appReleaseVersion.name}" !in changelogText) {
issues += "CHANGELOG.md has no section for v${appReleaseVersion.name}."
}
if (Regex("""## \[?Unreleased""").findAll(changelogText).count() > 1) {
issues += "CHANGELOG.md has more than one Unreleased section."
}
if ("\"${appReleaseVersion.name}\"" !in changelogScreenText) {
issues += "In-app ChangelogScreen has no entry for v${appReleaseVersion.name}."
}
if ("isLatest = true" !in changelogScreenText) {
issues += "In-app ChangelogScreen must flag a latest version entry."
}
if ("## v${appReleaseVersion.name} Highlights" !in readmeText) {
issues += "README highlights do not match app version ${appReleaseVersion.name}."
}
if ("## Detection Pipeline (v${appReleaseVersion.name})" !in readmeText) {
issues += "README detection-pipeline version does not match ${appReleaseVersion.name}."
}
if ("img.shields.io/github/v/release/SysAdminDoc/CallShield" !in readmeText) {
issues += "README release badge must follow the latest GitHub release."
}
val testCount =
Regex("""\*\*(\d+) total JVM unit tests\*\*""")
.find(readmeText)
?.groupValues
?.get(1)
if (testCount == null) {
issues += "README must declare the current JVM test count."
} else {
val testCountReferences =
listOf(
"img.shields.io/badge/JVM%20unit%20tests-$testCount-",
"alt=\"$testCount JVM unit tests\"",
"# $testCount tests",
"| Tests | $testCount JVM unit tests (JUnit) |",
)
if (testCountReferences.any { it !in readmeText }) {
issues += "README test badge, command, summary, and table must all use $testCount."
}
}
if (!storeChangelog.asFile.isFile || storeChangelog.asFile.readText().isBlank()) {
issues += "Fastlane changelog ${appReleaseVersion.code}.txt is missing or empty."
} else if (storeChangelog.asFile.readText().length > 500) {
issues += "Fastlane changelog ${appReleaseVersion.code}.txt exceeds 500 characters."
}
fun imageDimensions(file: File): Pair<Int, Int>? =
runCatching {
ImageIO.read(file)?.let { image -> image.width to image.height }
}.getOrNull()
val iconFile = storeImages.file("icon.png").asFile
if (imageDimensions(iconFile) != (512 to 512)) {
issues += "Fastlane icon.png must be a readable 512x512 PNG."
}
val featureGraphicFile = storeImages.file("featureGraphic.png").asFile
if (imageDimensions(featureGraphicFile) != (1024 to 500)) {
issues += "Fastlane featureGraphic.png must be a readable 1024x500 PNG."
}
val phoneScreenshots =
storeImages
.dir("phoneScreenshots")
.asFile
.listFiles { file -> file.isFile && file.extension.equals("png", ignoreCase = true) }
.orEmpty()
.sortedBy(File::getName)
if (phoneScreenshots.size !in 4..8) {
issues += "Fastlane metadata must include 4-8 phone screenshots; found ${phoneScreenshots.size}."
}
phoneScreenshots.forEach { screenshot ->
val dimensions = imageDimensions(screenshot)
if (dimensions == null) {
issues += "Fastlane screenshot ${screenshot.name} is not a readable PNG."
} else {
val (width, height) = dimensions
val shorter = minOf(width, height)
val longer = maxOf(width, height)
if (shorter < 320 || longer > 3_840 || longer > shorter * 2) {
issues +=
"Fastlane screenshot ${screenshot.name} has unsupported dimensions " +
"${width}x$height (expected 320-3840 px and at most 2:1)."
}
}
}
val currentStoreCopy = "$fullDescription\n$shortDescription".lowercase()
val retiredClaims =
listOf(
"abstractapi",
"optional api key",
"optional caller enrichment key",
"enrichment key stored",
)
retiredClaims.filter(currentStoreCopy::contains).forEach { claim ->
issues += "Current store metadata still contains retired claim: $claim."
}
if (Regex("""CallShield-v\d+\.\d+\.\d+\.apk""").containsMatchIn(signingPreflightText)) {
issues += "Signing preflight examples must use the stable AGP release output path."
}
check(issues.isEmpty()) {
"Release metadata verification failed:\n${issues.joinToString("\n") { "- $it" }}"
}
}
}
tasks.register("verifySigningSecretGuardTests") {
group = "verification"
description = "Proves literal signing secrets fail without appearing in diagnostics."
val accrescentScript = layout.projectDirectory.file("scripts/build-accrescent-apks.ps1")
inputs.file(accrescentScript)
doLast {
val sentinel = "synthetic-secret-must-not-print"
val syntheticSecrets =
listOf(
"fixture.gradle.kts" to ("store" + "Password = \"$sentinel\""),
"fixture.properties" to ("RELEASE_STORE_" + "PASSWORD=$sentinel"),
"fixture.pem" to ("-----BEGIN " + "PRIVATE KEY-----\n$sentinel"),
"extensionless" to ("RELEASE_KEY_" + "PASSWORD=p@${'$'}${'$'}word"),
)
val fixtureRoot = temporaryDir.resolve("tracked-secret-fixtures").apply { mkdirs() }
val fixtureFiles =
syntheticSecrets.map { (path, text) ->
fixtureRoot.resolve(path).apply { writeText(text) }
}
val binaryKeyContainer = fixtureRoot.resolve("fixture.p12").apply { writeBytes(byteArrayOf(0, 1, 2)) }
val findings = scanTrackedSigningFiles(fixtureFiles + binaryKeyContainer, fixtureRoot)
val failure = runCatching { requireNoTrackedSigningSecrets(findings) }.exceptionOrNull()
check(failure != null) { "Synthetic signing-secret fixture was not rejected." }
check(sentinel !in failure.message.orEmpty()) { "Signing-secret diagnostic exposed the matched value." }
check(findings.map(SigningSecretFinding::path).containsAll(syntheticSecrets.map { it.first } + "fixture.p12")) {
"Every tracked-file fixture must pass through the production scanner and be rejected."
}
val safeLookups =
"""
storePassword = releaseStorePassword
keyPassword = signingProp("RELEASE_KEY_PASSWORD")
RELEASE_STORE_PASSWORD: ${'$'}{{ secrets.RELEASE_STORE_PASSWORD }}
""".trimIndent()
check(findSigningSecretFindings("safe.yml", safeLookups).isEmpty()) {
"Environment and property lookups must remain valid."
}
val deceptiveLiterals =
listOf(
"RELEASE_STORE_" + "PASSWORD: p@${'$'}${'$'}word",
"RELEASE_KEY_" + "PASSWORD: prefixSystem.getenv(\"RELEASE_KEY_PASSWORD\")",
).joinToString("\n")
check(findSigningSecretFindings("unsafe.properties", deceptiveLiterals).size == 2) {
"Dollar signs and embedded lookup names must not bypass literal-secret detection."
}
val accrescentText = accrescentScript.asFile.readText()
check(Regex("""(?i)\[securestring]\s*\${'$'}KeystorePassword""").containsMatchIn(accrescentText))
check(Regex("""(?i)\[securestring]\s*\${'$'}KeyPassword""").containsMatchIn(accrescentText))
check("SetAccessRuleProtection(${ '$' }true, ${ '$' }false)" in accrescentText)
check("ZeroFreeBSTR" in accrescentText)
check("New-TemporaryFile" !in accrescentText && "Set-Content -Path ${ '$' }ksPassFile" !in accrescentText) {
"Accrescent signing passwords must not use ordinary temporary files."
}
}
}
tasks.register("verifyTrackedSigningSecrets") {
group = "verification"
description = "Rejects signing secrets embedded in tracked source and configuration files."
dependsOn("verifySigningSecretGuardTests")
val trackedSourceFiles =
providers
.exec {
commandLine("git", "ls-files", "-z")
}.standardOutput
.asText
.map { output ->
output
.split('\u0000')
.filter(String::isNotBlank)
.map(rootProject::file)
}
inputs.files(trackedSourceFiles)
doLast {
val findings = scanTrackedSigningFiles(trackedSourceFiles.get(), rootDir)
requireNoTrackedSigningSecrets(findings)
}
}
tasks.register("verifyDebugApkPrivacy") {
group = "verification"
description = "Fails when the debug APK leaks non-runtime repository data."
dependsOn(":app:assembleDebug")
val apk = layout.projectDirectory.file("app/build/outputs/apk/debug/app-debug.apk")
inputs.file(apk)
doLast {
verifyApkDataPrivacy(apk.asFile)
}
}
tasks.register("verifyBackupPrivacyRules") {
group = "verification"
description = "Fails when Android cloud backup includes the sensitive Room database."
val legacyRules = layout.projectDirectory.file("app/src/main/res/xml/backup_rules.xml")
val modernRules = layout.projectDirectory.file("app/src/main/res/xml/data_extraction_rules.xml")
inputs.files(legacyRules, modernRules)
doLast {
val legacy = legacyRules.asFile.readText()
val modern = modernRules.asFile.readText()
val cloudRules = modern.substringAfter("<cloud-backup>").substringBefore("</cloud-backup>")
val deviceTransferRules = modern.substringAfter("<device-transfer>").substringBefore("</device-transfer>")
check("domain=\"database\"" !in legacy) {
"API 23-30 cloud backup must not include the sensitive Room database."
}
check("domain=\"database\"" !in cloudRules) {
"API 31+ cloud backup must not include the sensitive Room database."
}
check("domain=\"database\"" in deviceTransferRules) {
"Direct device transfer should preserve the Room database."
}
}
}
tasks.register<Exec>("verifyPipelineTests") {
group = "verification"
description =
"Runs the Cloudflare Worker (node) and Python data-pipeline tests. " +
"The phone-number normalizer is implemented three times — Kotlin, JS, Python — " +
"and only the Kotlin side is covered by the Gradle suite."
val script = layout.projectDirectory.file("scripts/run-pipeline-tests.ps1")
inputs.file(script)
inputs.dir(layout.projectDirectory.dir("worker"))
inputs.dir(layout.projectDirectory.dir("scripts"))
// The liveness check reads the live report queue, but data/reports is NOT
// declared as an input. Two reasons. This task declares no outputs, so
// Gradle never marks it UP-TO-DATE and it re-runs every time regardless.
// And inputs.dir(...).optional() does not tolerate a missing directory --
// optional() only permits a null value, so a concrete path that does not
// exist still fails validation, and merge_community_reports.py removes
// data/reports once it is empty. Declaring it would break check the first
// time the queue drained past its .gitkeep.
// Skips (with a warning) when node/python are absent, so a machine without
// them can still run `check`.
commandLine(
"pwsh",
"-NoProfile",
"-NonInteractive",
"-File",
script.asFile.absolutePath,
)
}
tasks.register<Exec>("verifyReleaseSigningPolicyTests") {
group = "verification"
description = "Proves the release gate accepts only the pinned signer certificate."
val policy = layout.projectDirectory.file("scripts/release-signing-policy.ps1")
val test = layout.projectDirectory.file("scripts/test-release-signing-policy.ps1")
inputs.files(policy, test)
commandLine("pwsh", "-NoProfile", "-NonInteractive", "-File", test.asFile.absolutePath)
}