-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathbuild.gradle
More file actions
3519 lines (3132 loc) · 155 KB
/
Copy pathbuild.gradle
File metadata and controls
3519 lines (3132 loc) · 155 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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
buildscript {
repositories {
mavenCentral()
maven { url "https://jitpack.io" }
maven { url "https://plugins.gradle.org/m2/" }
}
}
import org.gradle.jvm.tasks.Jar
import org.gradle.api.tasks.bundling.Zip
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import java.util.zip.ZipFile
plugins {
id 'bisq.gradle.regtest_plugin.RegtestPlugin'
}
def dependencyVerificationMetadata = layout.projectDirectory.file('gradle/verification-metadata.xml')
def dependencyVerificationKeyring = layout.projectDirectory.file('gradle/verification-keyring.keys')
def dependencyVerificationBinaryKeyring = layout.projectDirectory.file('gradle/verification-keyring.gpg')
def dependencyChecksumFallbackAllowlist = layout.projectDirectory.file('gradle/dependency-checksum-fallback-allowlist.tsv')
def dependencySignatureReport = layout.projectDirectory.file('docs/dependency-signature-report.md')
def gradleWrapperChecksums = layout.projectDirectory.file('gradle/wrapper/gradle-wrapper.sha256')
def linuxReleaseBuilderDockerfile = layout.projectDirectory.file('docker/release-builder/linux/Dockerfile')
def linuxReleaseBuilderWorkflow = layout.projectDirectory.file('.github/workflows/release-builder.yml')
def installerEvidenceWorkflow = layout.projectDirectory.file('.github/workflows/installer-evidence.yml')
def gradleWrapperCommand = System.getProperty('os.name').toLowerCase(Locale.ROOT).contains('windows') ? 'gradlew.bat' : './gradlew'
def htmlEscape = { value ->
value == null
? ''
: value.toString()
.replace('&', '&')
.replace('<', '<')
.replace('>', '>')
.replace('|', '|')
}
def keyIdSuffix = { String keyId ->
def normalized = keyId.toUpperCase(Locale.ROOT).replaceAll(/\s/, '')
normalized.length() > 16 ? normalized.substring(normalized.length() - 16) : normalized
}
def decodeArmoredPublicKey = { String armoredPublicKey ->
def base64Lines = []
def inBody = false
armoredPublicKey.eachLine { line ->
if (line.startsWith('-----BEGIN')) {
return
}
if (!inBody) {
if (line.trim().empty) {
inBody = true
}
return
}
if (line.startsWith('=') || line.startsWith('-----END')) {
return
}
if (!line.trim().empty) {
base64Lines << line.trim()
}
}
if (base64Lines.empty) {
return new byte[0]
}
try {
Base64.decoder.decode(base64Lines.join(''))
} catch (Exception ignored) {
new byte[0]
}
}
def parseOpenPgpPackets = { String armoredPublicKey ->
def packets = []
try {
byte[] bytes = decodeArmoredPublicKey(armoredPublicKey)
int offset = 0
while (offset < bytes.length) {
int ctb = bytes[offset++] & 0xff
if ((ctb & 0x80) == 0) {
return packets
}
int tag
long length
if ((ctb & 0x40) != 0) {
tag = ctb & 0x3f
int firstLengthOctet = bytes[offset++] & 0xff
if (firstLengthOctet < 192) {
length = firstLengthOctet
} else if (firstLengthOctet <= 223) {
length = ((firstLengthOctet - 192) << 8) + (bytes[offset++] & 0xff) + 192
} else if (firstLengthOctet == 255) {
length = ((bytes[offset++] & 0xffL) << 24) |
((bytes[offset++] & 0xffL) << 16) |
((bytes[offset++] & 0xffL) << 8) |
(bytes[offset++] & 0xffL)
} else {
return packets
}
} else {
tag = (ctb >> 2) & 0x0f
int lengthType = ctb & 0x03
if (lengthType == 0) {
length = bytes[offset++] & 0xff
} else if (lengthType == 1) {
length = ((bytes[offset++] & 0xff) << 8) | (bytes[offset++] & 0xff)
} else if (lengthType == 2) {
length = ((bytes[offset++] & 0xffL) << 24) |
((bytes[offset++] & 0xffL) << 16) |
((bytes[offset++] & 0xffL) << 8) |
(bytes[offset++] & 0xffL)
} else {
length = bytes.length - offset
}
}
if (length > Integer.MAX_VALUE || offset + (int) length > bytes.length) {
return packets
}
packets << [
tag : tag,
body: Arrays.copyOfRange(bytes, offset, offset + (int) length)
]
offset += (int) length
}
} catch (Exception ignored) {
return packets
}
packets
}
def normalizeOpenPgpUserId = { String userId ->
userId
.replace('\uFFFDamonn McManus <eamonn@mcmanus.net>', '\u00C9amonn McManus <eamonn@mcmanus.net>')
.replace('\u003Famonn McManus <eamonn@mcmanus.net>', '\u00C9amonn McManus <eamonn@mcmanus.net>')
}
def parsePublicKeyUserIds = { String armoredPublicKey ->
parseOpenPgpPackets(armoredPublicKey)
.findAll { it.tag == 13 }
.collect { packet -> normalizeOpenPgpUserId(new String(packet.body, StandardCharsets.UTF_8).trim()) }
.findAll { it }
}
def parsePublicKeyCreatedDate = { String armoredPublicKey ->
def publicKeyPacket = parseOpenPgpPackets(armoredPublicKey).find { it.tag == 6 }
if (publicKeyPacket?.body == null || publicKeyPacket.body.length < 5) {
return null
}
byte[] body = publicKeyPacket.body
long created = ((body[1] & 0xffL) << 24) |
((body[2] & 0xffL) << 16) |
((body[3] & 0xffL) << 8) |
(body[4] & 0xffL)
java.time.Instant.ofEpochSecond(created)
.atZone(java.time.ZoneOffset.UTC)
.toLocalDate()
.toString()
}
def parseSignerUserId = { String userId ->
def matcher = userId =~ /^(.*?)\s*<([^>]+)>$/
matcher.matches()
? [name: matcher[0][1].trim(), email: matcher[0][2].trim(), userId: userId]
: [name: userId, email: '', userId: userId]
}
def loadSignerMetadata = { File keyringFile ->
def signers = [:]
if (!keyringFile.exists()) {
return signers
}
def current = null
def saveCurrent = {
if (current?.keyId) {
def userIds = parsePublicKeyUserIds(current.armor.toString()) ?: current.userIds
def user = userIds ? parseSignerUserId(userIds[0]) : [name: '', email: '', userId: '']
def signer = user + [
keyId : current.keyId,
created: parsePublicKeyCreatedDate(current.armor.toString()) ?: ''
]
([current.keyId] + current.subKeyIds).each { keyId ->
signers[keyId] = signer
}
}
}
keyringFile.eachLine(StandardCharsets.UTF_8.name()) { line ->
def pubMatcher = line =~ /^pub\s+([0-9A-Fa-f]+)\s*$/
if (pubMatcher.matches()) {
saveCurrent()
current = [
keyId : keyIdSuffix(pubMatcher[0][1]),
subKeyIds: [],
userIds : [],
armor : new StringBuilder(),
inArmor : false
]
return
}
if (current == null) {
return
}
def uidMatcher = line =~ /^uid\s+(.*)$/
if (uidMatcher.matches()) {
current.userIds << uidMatcher[0][1].trim()
return
}
def subMatcher = line =~ /^sub\s+([0-9A-Fa-f]+)\s*$/
if (subMatcher.matches()) {
current.subKeyIds << keyIdSuffix(subMatcher[0][1])
return
}
if (line.startsWith('-----BEGIN PGP PUBLIC KEY BLOCK-----')) {
current.inArmor = true
}
if (current.inArmor) {
current.armor << line << '\n'
}
if (line.startsWith('-----END PGP PUBLIC KEY BLOCK-----')) {
current.inArmor = false
}
}
saveCurrent()
signers
}
def resolvableConfigurations = {
allprojects.collectMany { project ->
(project.configurations + project.buildscript.configurations).findAll { it.canBeResolved }.collect { configuration ->
[project: project, configuration: configuration]
}
}.sort { left, right ->
def leftPath = "${left.project.path}:${left.configuration.name}"
def rightPath = "${right.project.path}:${right.configuration.name}"
leftPath <=> rightPath
}
}
def resolveConfigurations = { boolean collectComponents ->
def resolvedComponents = new TreeSet<String>()
def directComponents = new TreeSet<String>()
def failures = []
resolvableConfigurations().each { entry ->
def configuration = entry.configuration
try {
if (collectComponents) {
def result = configuration.incoming.resolutionResult
result.root.dependencies.each { dependency ->
def selected = dependency.hasProperty('selected') ? dependency.selected?.id : null
if (selected instanceof org.gradle.api.artifacts.component.ModuleComponentIdentifier) {
directComponents.add("${selected.group}:${selected.module}:${selected.version}".toString())
}
}
result.allComponents.each { component ->
def id = component.id
if (id instanceof org.gradle.api.artifacts.component.ModuleComponentIdentifier) {
resolvedComponents.add("${id.group}:${id.module}:${id.version}".toString())
}
}
}
configuration.resolve()
} catch (Exception exception) {
failures << "${entry.project.path}:${configuration.name} - ${exception.message}"
}
}
if (!failures.empty) {
throw new GradleException("Failed to resolve ${failures.size()} configuration(s):\n - ${failures.join('\n - ')}")
}
[resolvedComponents: resolvedComponents, directComponents: directComponents]
}
def readChecksumFallbackAllowlist = { File allowlistFile ->
if (!allowlistFile.exists()) {
throw new GradleException("Missing ${allowlistFile}. Review checksum-only dependencies and add the approved entries.")
}
def sortKey = { String entry ->
def columns = entry.split(/\t/, -1)
def module = columns[0].split(':', -1)
"${module[0]}\t${module[1]}\t${module[2]}\t${columns[1]}".toString()
}
def allowedEntries = new TreeSet<String>()
def rationaleByEntry = new TreeMap<String, String>()
def entryOrder = []
def duplicateEntries = []
allowlistFile.eachLine(StandardCharsets.UTF_8.name()) { line, number ->
def trimmed = line.trim()
if (!trimmed || trimmed.startsWith('#')) {
return
}
def columns = line.split(/\t/, -1)
if (columns.size() != 3 || columns.any { !it.trim() }) {
throw new GradleException("Invalid checksum fallback allowlist entry at ${allowlistFile}:${number}. Expected '<group:name:version>\\t<artifact-file-name>\\t<review-rationale>'.")
}
def entry = "${columns[0].trim()}\t${columns[1].trim()}".toString()
entryOrder << entry
if (!allowedEntries.add(entry)) {
duplicateEntries << entry
}
rationaleByEntry[entry] = columns[2].trim()
}
if (!duplicateEntries.empty) {
throw new GradleException("Duplicate checksum fallback allowlist entries:\n - ${duplicateEntries.unique().sort().join('\n - ')}")
}
if (entryOrder != entryOrder.sort(false) { left, right -> sortKey(left) <=> sortKey(right) }) {
throw new GradleException(
"Checksum fallback allowlist entries must be sorted by module and artifact:\n" +
allowlistFile
)
}
[entries: allowedEntries, rationales: rationaleByEntry]
}
tasks.register('resolveAndVerifyDependencies') {
group = 'verification'
description = 'Resolves every resolvable configuration so Gradle dependency verification checks all dependency artifacts.'
doLast {
resolveConfigurations(false)
logger.lifecycle("Resolved and verified ${resolvableConfigurations().size()} configurations.")
}
}
tasks.register('verifyDependencySignaturePolicy') {
group = 'verification'
description = 'Verifies all dependency artifacts and fails if checksum-only artifacts are not explicitly allowed.'
inputs.file(dependencyVerificationMetadata)
inputs.file(dependencyChecksumFallbackAllowlist)
doLast {
resolveConfigurations(false)
def metadataFile = dependencyVerificationMetadata.asFile
def allowlistFile = dependencyChecksumFallbackAllowlist.asFile
if (!metadataFile.exists()) {
throw new GradleException("Missing ${metadataFile}. Run './gradlew resolveAndVerifyDependencies --write-verification-metadata pgp,sha256' first.")
}
def allowlist = readChecksumFallbackAllowlist(allowlistFile)
def allowedEntries = allowlist.entries
def metadata = new XmlSlurper(false, false).parse(metadataFile)
def checksumFallbackEntries = new TreeSet<String>()
metadata.components.component.each { component ->
def id = "${component.@group}:${component.@name}:${component.@version}".toString()
component.artifact.each { artifact ->
def checksumOnly = artifact.sha256.any { checksum ->
checksum.@reason.text() == 'Artifact is not signed'
}
if (checksumOnly) {
checksumFallbackEntries.add("${id}\t${artifact.@name}".toString())
}
}
}
def unapprovedEntries = checksumFallbackEntries.findAll { !allowedEntries.contains(it) }
def staleEntries = allowedEntries.findAll { !checksumFallbackEntries.contains(it) }
if (!unapprovedEntries.empty || !staleEntries.empty) {
def message = new StringBuilder()
message << 'Dependency signature policy failed.'
if (!unapprovedEntries.empty) {
message << "\n\nUnapproved checksum-only dependency artifacts:\n - ${unapprovedEntries.join('\n - ')}"
}
if (!staleEntries.empty) {
message << "\n\nAllowlist entries that are no longer checksum-only artifacts:\n - ${staleEntries.join('\n - ')}"
}
message << "\n\nReview each checksum-only artifact, update ${allowlistFile}, and regenerate ${dependencySignatureReport.asFile}."
throw new GradleException(message.toString())
}
logger.lifecycle("Verified ${checksumFallbackEntries.size()} approved checksum-only dependency artifact(s).")
}
}
tasks.register('refreshDependencyVerificationKeyring') {
group = 'verification'
description = 'Refreshes dependency verification PGP public keys from key servers and exports the armored keyring.'
inputs.file(dependencyVerificationMetadata)
outputs.file(dependencyVerificationKeyring)
outputs.upToDateWhen { false }
doLast {
def keyringFile = dependencyVerificationKeyring.asFile
def previousModified = keyringFile.exists() ? keyringFile.lastModified() : 0L
def result = exec {
commandLine gradleWrapperCommand, '--no-daemon', 'help', '--refresh-keys', '--export-keys'
ignoreExitValue = true
}
if (!keyringFile.exists()) {
throw new GradleException("Failed to write ${keyringFile}. Check network access to the configured Gradle verification key servers.")
}
if (result.exitValue != 0) {
if (keyringFile.lastModified() <= previousModified) {
throw new GradleException("Gradle --refresh-keys --export-keys failed with exit code ${result.exitValue} and did not update ${keyringFile}.")
}
logger.warn("Gradle --refresh-keys --export-keys exited with ${result.exitValue} after updating ${keyringFile}. This can happen in some Gradle/Bouncy Castle combinations.")
}
if (dependencyVerificationBinaryKeyring.asFile.exists()) {
logger.warn("Ignoring ${dependencyVerificationBinaryKeyring.asFile}; dependency verification is configured to use the armored keyring.")
}
logger.lifecycle("Refreshed ${keyringFile}.")
}
}
tasks.register('dependencySignatureReport') {
group = 'verification'
description = 'Writes a report of signed and checksum-only dependencies from Gradle verification metadata.'
inputs.file(dependencyVerificationMetadata)
inputs.file(dependencyVerificationKeyring).optional()
inputs.file(dependencyChecksumFallbackAllowlist)
outputs.file(dependencySignatureReport)
outputs.upToDateWhen { false }
doLast {
def resolved = resolveConfigurations(true)
def metadataFile = dependencyVerificationMetadata.asFile
def keyringFile = dependencyVerificationKeyring.asFile
if (!metadataFile.exists()) {
throw new GradleException("Missing ${metadataFile}. Run './gradlew resolveAndVerifyDependencies --write-verification-metadata pgp,sha256' first.")
}
def allowlist = readChecksumFallbackAllowlist(dependencyChecksumFallbackAllowlist.asFile)
def signerMetadata = loadSignerMetadata(keyringFile)
def metadata = new XmlSlurper(false, false).parse(metadataFile)
def componentsById = new TreeMap<String, Object>()
metadata.components.component.each { component ->
def id = "${component.@group}:${component.@name}:${component.@version}".toString()
componentsById[id] = component
}
def trustedKeys = []
metadata.configuration.'trusted-keys'.'trusted-key'.each { trustedKey ->
def entries = []
if (trustedKey.@group.text() || trustedKey.@name.text() || trustedKey.@version.text()) {
entries << [
group : trustedKey.@group.text(),
name : trustedKey.@name.text(),
version: trustedKey.@version.text(),
regex : trustedKey.@regex.text()
]
}
trustedKey.trusting.each { trusting ->
entries << [
group : trusting.@group.text(),
name : trusting.@name.text(),
version: trusting.@version.text(),
regex : trusting.@regex.text()
]
}
trustedKeys << [id: trustedKey.@id.text(), entries: entries]
}
def matches = { String pattern, String value, boolean regex ->
if (!pattern) {
return true
}
regex ? (value ==~ pattern) : pattern == value
}
def rows = []
resolved.resolvedComponents.each { id ->
def component = componentsById[id]
if (component == null) {
rows << [
id : id,
scope : resolved.directComponents.contains(id) ? 'direct' : 'transitive',
status : 'missing from metadata',
signedCount : 0,
checksumOnlyCount: 0,
keyIds : [],
checksumArtifacts: ['metadata entry missing']
]
return
}
def group = component.@group.text()
def name = component.@name.text()
def version = component.@version.text()
def artifacts = component.artifact.collect { artifact ->
def checksumOnly = artifact.sha256.any { checksum ->
checksum.@reason.text() == 'Artifact is not signed'
}
[
name : artifact.@name.text(),
checksumOnly: checksumOnly,
keyIds : artifact.pgp.collect { it.@value.text() }.findAll { it }
]
}
def matchingTrustedKeys = trustedKeys.findAll { trustedKey ->
trustedKey.entries.any { entry ->
def regex = entry.regex == 'true'
matches(entry.group, group, regex) &&
matches(entry.name, name, regex) &&
matches(entry.version, version, regex)
}
}.collect { it.id }
def signedCount = artifacts.count { !it.checksumOnly }
def checksumOnlyCount = artifacts.count { it.checksumOnly }
def status = checksumOnlyCount == 0
? 'PGP signed'
: signedCount == 0 ? 'checksum fallback' : 'mixed'
def keyIds = signedCount == 0
? []
: (artifacts.collectMany { it.keyIds } + matchingTrustedKeys).unique().sort()
rows << [
id : id,
scope : resolved.directComponents.contains(id) ? 'direct' : 'transitive',
status : status,
signedCount : signedCount,
checksumOnlyCount: checksumOnlyCount,
keyIds : keyIds,
checksumArtifacts: artifacts.findAll { it.checksumOnly }.collect { artifact ->
[
name : artifact.name,
rationale: allowlist.rationales["${id}\t${artifact.name}".toString()] ?: 'Missing allowlist rationale'
]
}.sort { it.name }
]
}
def reportFile = dependencySignatureReport.asFile
reportFile.parentFile.mkdirs()
def signedRows = rows.findAll { it.status == 'PGP signed' }
def checksumRows = rows.findAll { it.status == 'checksum fallback' }
def mixedRows = rows.findAll { it.status == 'mixed' }
def missingRows = rows.findAll { it.status == 'missing from metadata' }
def totalArtifacts = rows.sum { it.signedCount + it.checksumOnlyCount } ?: 0
def signedArtifacts = rows.sum { it.signedCount } ?: 0
def checksumOnlyArtifacts = rows.sum { it.checksumOnlyCount } ?: 0
def reportedKeyIds = rows.collectMany { it.keyIds }.unique().sort()
def reportedKeyIdsInKeyring = reportedKeyIds.count { signerMetadata[keyIdSuffix(it)] != null }
def reportedKeyIdsWithUserId = reportedKeyIds.count {
def signer = signerMetadata[keyIdSuffix(it)]
signer?.name || signer?.email
}
def reportedKeyIdsWithCreatedDate = reportedKeyIds.count {
signerMetadata[keyIdSuffix(it)]?.created
}
def signerDetails = { List<String> keyIds ->
if (!keyIds) {
return '-'
}
keyIds.collect { keyId ->
def signer = signerMetadata[keyIdSuffix(keyId)]
if (signer == null) {
return "`$keyId`"
}
def lines = ["`$keyId`"]
if (signer.name) {
lines << htmlEscape(signer.name)
}
if (signer.email) {
lines << "`$signer.email`"
}
if (signer.created) {
lines << "created ${signer.created}"
}
lines.join('<br>')
}.join('<br><br>')
}
def markdown = new StringBuilder()
markdown << '# Dependency Signature Report\n\n'
markdown << "Generated from `gradle/verification-metadata.xml` after resolving ${resolvableConfigurations().size()} configurations.\n\n"
if (keyringFile.exists()) {
markdown << 'Signer metadata is loaded from `gradle/verification-keyring.keys`; names and emails come from the first OpenPGP user ID, and creation dates come from the public key packet.\n\n'
} else {
markdown << 'Signer metadata is unavailable because `gradle/verification-keyring.keys` is missing.\n\n'
}
markdown << 'Checksum fallback review rationales are loaded from `gradle/dependency-checksum-fallback-allowlist.tsv`.\n\n'
markdown << 'Refresh the metadata before regenerating this report:\n\n'
markdown << '```bash\n'
markdown << './gradlew refreshDependencyVerificationKeyring\n'
markdown << './gradlew resolveAndVerifyDependencies --write-verification-metadata pgp,sha256\n'
markdown << './gradlew dependencySignatureReport\n'
markdown << '```\n\n'
markdown << '## Summary\n\n'
markdown << "| Metric | Count |\n"
markdown << "| --- | ---: |\n"
markdown << "| Resolved external modules | ${rows.size()} |\n"
markdown << "| Modules with PGP-signed artifacts only | ${signedRows.size()} |\n"
markdown << "| Modules using checksum fallback only | ${checksumRows.size()} |\n"
markdown << "| Modules with mixed signed/checksum-only artifacts | ${mixedRows.size()} |\n"
markdown << "| Modules missing verification metadata | ${missingRows.size()} |\n"
markdown << "| Verified artifacts | ${totalArtifacts} |\n"
markdown << "| PGP-signed artifacts | ${signedArtifacts} |\n"
markdown << "| Checksum-fallback artifacts | ${checksumOnlyArtifacts} |\n"
markdown << "| Signer keys found in exported keyring | ${reportedKeyIdsInKeyring} / ${reportedKeyIds.size()} |\n"
markdown << "| Signer keys with name or email | ${reportedKeyIdsWithUserId} / ${reportedKeyIds.size()} |\n"
markdown << "| Signer keys with creation date | ${reportedKeyIdsWithCreatedDate} / ${reportedKeyIds.size()} |\n\n"
markdown << '## Handling Transitive Dependencies\n\n'
markdown << 'Treat transitive dependencies the same as direct dependencies. Gradle verifies the resolved artifact graph, so a transitive artifact with a published signature should be PGP-verified, and an unsigned transitive artifact should keep an explicit SHA-256 checksum fallback. Review metadata changes separately when dependency versions change, especially new trusted keys and new checksum-only artifacts.\n\n'
markdown << '## Checksum Fallback Dependencies\n\n'
if (checksumRows.empty && mixedRows.empty) {
markdown << 'All resolved modules have PGP-signed artifacts in the current metadata.\n\n'
} else {
markdown << "| Dependency | Scope | Checksum-only artifacts and review rationale |\n"
markdown << "| --- | --- | --- |\n"
(checksumRows + mixedRows).sort { it.id }.each { row ->
def checksumArtifacts = row.checksumArtifacts.collect { artifact ->
"`$artifact.name`<br>${htmlEscape(artifact.rationale)}"
}.join('<br><br>')
markdown << "| `${row.id}` | ${row.scope} | ${checksumArtifacts} |\n"
}
markdown << '\n'
}
if (!missingRows.empty) {
markdown << '## Missing Metadata\n\n'
markdown << "| Dependency | Scope |\n"
markdown << "| --- | --- |\n"
missingRows.sort { it.id }.each { row ->
markdown << "| `${row.id}` | ${row.scope} |\n"
}
markdown << '\n'
}
markdown << '## Full Resolved Dependency Inventory\n\n'
markdown << "| Dependency | Scope | Status | Artifacts | Signer key and metadata |\n"
markdown << "| --- | --- | --- | ---: | --- |\n"
rows.sort { it.id }.each { row ->
def artifactSummary = "${row.signedCount} signed / ${row.checksumOnlyCount} checksum"
markdown << "| `${row.id}` | ${row.scope} | ${row.status} | ${artifactSummary} | ${signerDetails(row.keyIds)} |\n"
}
reportFile.setText(markdown.toString(), StandardCharsets.UTF_8.name())
logger.lifecycle("Wrote ${reportFile}.")
}
}
if (hasProperty('buildScan')) {
buildScan {
termsOfServiceUrl = 'https://gradle.com/terms-of-service'
termsOfServiceAgree = 'yes'
}
}
def sha256 = { File file ->
MessageDigest digest = MessageDigest.getInstance('SHA-256')
file.withInputStream { input ->
byte[] buffer = new byte[8192]
int read
while ((read = input.read(buffer)) != -1) {
digest.update(buffer, 0, read)
}
}
digest.digest().collect { String.format('%02x', it) }.join()
}
def sha256Bytes = { byte[] bytes ->
MessageDigest.getInstance('SHA-256')
.digest(bytes)
.collect { String.format('%02x', it & 0xff) }
.join()
}
def canonicalPath = { File file ->
rootProject.relativePath(file).replace(File.separatorChar, '/' as char)
}
def normalizeReleaseVersion = { String rawReleaseVersion ->
if (rawReleaseVersion == null || rawReleaseVersion.trim().empty) {
throw new GradleException('Missing required -PreleaseVersion=<version>, for example -PreleaseVersion=1.10.0')
}
def releaseVersion = rawReleaseVersion.trim()
if (releaseVersion.startsWith('v')) {
releaseVersion = releaseVersion.substring(1)
}
if (!(releaseVersion ==~ /\d+\.\d+\.\d+([.-][A-Za-z0-9_.-]+)?/)) {
throw new GradleException("Invalid release version '${rawReleaseVersion}'. Expected a version such as 1.10.0 or v1.10.0.")
}
releaseVersion
}
def resolveGpgExecutable = {
def configuredGpgExecutable = providers.gradleProperty('gpgExecutable').orNull ?:
providers.environmentVariable('GPG_EXECUTABLE').orNull
configuredGpgExecutable ?: [
'/opt/homebrew/bin/gpg',
'/usr/local/bin/gpg',
'/usr/bin/gpg'
].find { new File(it).canExecute() } ?: 'gpg'
}
def enabledJarTasks = {
allprojects.collectMany { project ->
project.tasks.withType(Jar).findAll { it.enabled }
}
}
def tasksNamedAcrossProjects = { String taskName ->
allprojects.collect { project ->
project.tasks.names.contains(taskName) ? project.tasks.named(taskName) : null
}.findAll { it != null }
}
def manifestEntriesFor = { Collection<File> files ->
files.findAll { it.exists() && it.isFile() }
.collect { file ->
def path = canonicalPath(file)
[
path : path,
size : file.length(),
sha256: sha256(file)
]
}
.sort { left, right -> left.path <=> right.path }
}
def resolveManifestFile = { File manifestPath, String manifestFileName ->
if (manifestPath.file && manifestPath.name.toLowerCase(Locale.ROOT).endsWith('.zip')) {
def matchingEntries = []
def extractedManifest = null
new ZipFile(manifestPath).withCloseable { zipFile ->
zipFile.entries().each { entry ->
if (!entry.directory && (entry.name == manifestFileName || entry.name.endsWith("/${manifestFileName}"))) {
matchingEntries << entry.name
}
}
if (matchingEntries.empty) {
throw new GradleException("No ${manifestFileName} found in ${manifestPath}")
}
if (matchingEntries.size() > 1) {
throw new GradleException(
"Multiple ${manifestFileName} files found in ${manifestPath}:\n" +
matchingEntries.collect { " - ${it}" }.join('\n')
)
}
def extractedDir = new File(
layout.buildDirectory.dir('tmp/manifest-inputs').get().asFile,
Integer.toHexString(manifestPath.canonicalPath.hashCode())
)
project.delete(extractedDir)
extractedDir.mkdirs()
extractedManifest = new File(extractedDir, manifestFileName)
extractedManifest.withOutputStream { output ->
zipFile.getInputStream(zipFile.getEntry(matchingEntries[0])).withCloseable { input ->
output << input
}
}
}
return extractedManifest
}
if (!manifestPath.directory) {
return manifestPath
}
def matchingManifests = fileTree(manifestPath) {
include "**/${manifestFileName}"
}.files.sort { left, right -> left.path <=> right.path }
if (matchingManifests.empty) {
throw new GradleException("No ${manifestFileName} found under ${manifestPath}")
}
if (matchingManifests.size() > 1) {
throw new GradleException(
"Multiple ${manifestFileName} files found under ${manifestPath}:\n" +
matchingManifests.collect { " - ${it}" }.join('\n')
)
}
matchingManifests[0]
}
def resolveReleaseManifestFile = { File manifestPath ->
resolveManifestFile(manifestPath, 'release-manifest.tsv')
}
def resolveInstallerManifestFile = { File manifestPath ->
resolveManifestFile(manifestPath, 'installer-manifest.tsv')
}
def readEvidenceTextFile = { File evidencePath, String evidenceFileName, boolean required ->
def missingMessage = { String location ->
"No ${evidenceFileName} found ${location}"
}
if (evidencePath.file && evidencePath.name.toLowerCase(Locale.ROOT).endsWith('.zip')) {
def matchingEntries = []
def text = null
new ZipFile(evidencePath).withCloseable { zipFile ->
zipFile.entries().each { entry ->
if (!entry.directory && (entry.name == evidenceFileName || entry.name.endsWith("/${evidenceFileName}"))) {
matchingEntries << entry.name
}
}
if (matchingEntries.empty) {
return
} else if (matchingEntries.size() > 1) {
throw new GradleException(
"Multiple ${evidenceFileName} files found in ${evidencePath}:\n" +
matchingEntries.collect { " - ${it}" }.join('\n')
)
} else {
zipFile.getInputStream(zipFile.getEntry(matchingEntries[0])).withCloseable { input ->
text = input.getText(StandardCharsets.UTF_8.name())
}
}
}
if (matchingEntries.empty && required) {
throw new GradleException(missingMessage("in ${evidencePath}"))
}
return text
}
if (evidencePath.directory) {
def matchingFiles = fileTree(evidencePath) {
include "**/${evidenceFileName}"
}.files.sort { left, right -> left.path <=> right.path }
if (matchingFiles.empty) {
if (required) {
throw new GradleException(missingMessage("under ${evidencePath}"))
}
return null
}
if (matchingFiles.size() > 1) {
throw new GradleException(
"Multiple ${evidenceFileName} files found under ${evidencePath}:\n" +
matchingFiles.collect { " - ${it}" }.join('\n')
)
}
return matchingFiles[0].getText(StandardCharsets.UTF_8.name())
}
if (evidencePath.file && evidencePath.name == evidenceFileName) {
return evidencePath.getText(StandardCharsets.UTF_8.name())
}
if (required) {
throw new GradleException(missingMessage("at ${evidencePath}"))
}
null
}
def readReleaseManifest = { File manifestFile ->
if (!manifestFile.file) {
throw new GradleException("Missing release manifest: ${manifestFile}")
}
def lines = manifestFile.readLines(StandardCharsets.UTF_8.name())
if (lines.empty || lines[0] != 'sha256\tsize_bytes\tpath') {
throw new GradleException("Invalid release manifest header in ${manifestFile}. Expected: sha256\\tsize_bytes\\tpath")
}
def entries = new LinkedHashMap<String, Object>()
lines.drop(1).eachWithIndex { line, index ->
if (!line.trim().empty) {
def lineNumber = index + 2
def parts = line.split('\t', -1)
if (parts.length != 3) {
throw new GradleException("Invalid release manifest line ${lineNumber} in ${manifestFile}: ${line}")
}
def hash = parts[0]
def size = parts[1]
def path = parts[2]
if (!(hash ==~ /[0-9a-f]{64}/)) {
throw new GradleException("Invalid SHA-256 value on line ${lineNumber} in ${manifestFile}: ${hash}")
}
if (!(size ==~ /[0-9]+/)) {
throw new GradleException("Invalid file size on line ${lineNumber} in ${manifestFile}: ${size}")
}
if (!path || path.contains('\\')) {
throw new GradleException("Invalid path on line ${lineNumber} in ${manifestFile}: ${path}")
}
if (entries.containsKey(path)) {
throw new GradleException("Duplicate release manifest path on line ${lineNumber} in ${manifestFile}: ${path}")
}
entries[path] = [
sha256: hash,
size : size as Long,
path : path
]
}
}
entries
}
def readInstallerStructureReportRows = { File evidencePath ->
def reportText = readEvidenceTextFile(evidencePath, 'installer-structure-report.tsv', false)
if (reportText == null) {
return [:]
}
def lines = reportText.readLines()
def expectedHeader = 'artifact_path\tartifact_sha256\tformat\tstatus\treport_path\tmessage'
if (lines.empty || lines[0] != expectedHeader) {
throw new GradleException(
"Invalid installer-structure-report.tsv header in ${evidencePath}. Expected: ${expectedHeader.replace('\t', '\\t')}"
)
}
def rows = new LinkedHashMap<String, Object>()
lines.drop(1).eachWithIndex { line, index ->
if (!line.trim().empty) {
def lineNumber = index + 2
def columns = line.split('\t', -1)
if (columns.length != 6) {
throw new GradleException("Invalid installer structure report line ${lineNumber} in ${evidencePath}: ${line}")
}
def artifactPath = columns[0]
if (rows.containsKey(artifactPath)) {
throw new GradleException("Duplicate installer structure artifact path on line ${lineNumber} in ${evidencePath}: ${artifactPath}")
}
rows[artifactPath] = [
artifactPath: artifactPath,
sha256 : columns[1],
format : columns[2],
status : columns[3],
reportPath : columns[4],
message : columns[5]
]
}
}
rows
}
def installerStructureZipEntryFor = { String reportPath ->
def normalizedReportPath = reportPath.replace('\\', '/')
def marker = 'installer-structure/'
if (normalizedReportPath.startsWith(marker)) {
return normalizedReportPath
}
def markerIndex = normalizedReportPath.indexOf("/${marker}")
markerIndex >= 0 ? normalizedReportPath.substring(markerIndex + 1) : null
}
def installerStructureReportReference = { File evidencePath, Map<String, Object> structureRow ->
if (structureRow == null || !structureRow.reportPath) {
return 'none'
}
def structureEntry = installerStructureZipEntryFor(structureRow.reportPath)
if (structureEntry == null) {
return structureRow.reportPath
}
if (evidencePath.file && evidencePath.name.toLowerCase(Locale.ROOT).endsWith('.zip')) {
return "${evidencePath}!${structureEntry}"
}
if (evidencePath.directory) {
return new File(evidencePath, structureEntry).path
}
structureRow.reportPath
}