diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..4e8757b --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,90 @@ +name: CI + +on: [push, pull_request] + +jobs: + build: + name: Build Java Pinning + + runs-on: ubuntu-24.04 + strategy: + matrix: + java: + - 17 + - 21 + env: + PRIMARY_JAVA_VERSION: 21 + + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Set up JDK ${{ matrix.java }} + uses: actions/setup-java@v1 + with: + java-version: ${{ matrix.java }} + + # Caches + - name: Cache Maven + uses: actions/cache@v2 + with: + path: ~/.m2/repository + key: maven-${{ hashFiles('**/build.gradle') }} + restore-keys: | + maven- + - name: Cache Gradle + uses: actions/cache@v2 + with: + path: ~/.gradle/caches + key: gradle-caches-${{ hashFiles('**/build.gradle') }} + restore-keys: + gradle-caches + - name: Cache Android SDK + uses: actions/cache@v2 + with: + path: | + ~/.android/sdk + key: android-${{ hashFiles('build.gradle') }} + restore-keys: | + android- + + # Pre-reqs + - name: Install Android SDK Manager + uses: android-actions/setup-android@v2 + - name: Install Android SDK + run: | + sdkmanager "platforms;android-15" "platforms;android-30" + + # Testing + - name: Gradle Check + run: ./gradlew check --stacktrace + + # Test local publish + - name: Gradle publish + run: ./gradlew publishToMavenLocal --stacktrace + + # Javadoc + - name: Javadoc + if: ${{ matrix.java == env.PRIMARY_JAVA_VERSION }} + run: ./gradlew javadocAll --stacktrace + + # Test Coverage Report + - name: Jacoco Test Coverage + run: ./gradlew java-pinning-java11:testCodeCoverageReport + + # Coveralls + - name: Report coverage stats to Coveralls + if: ${{ matrix.java == env.PRIMARY_JAVA_VERSION }} + uses: coverallsapp/github-action@v2 + with: + format: jacoco + file: java-pinning-java11/build/reports/jacoco/testCodeCoverageReport/testCodeCoverageReport.xml + + # Upload build artifacts + - name: Upload build artifacts + uses: actions/upload-artifact@v4 + with: + name: java-pinning-java-${{ matrix.java }} + path: | + java-pinning-*/build/libs/*.jar + !**/*-test-fixtures.jar + !**/*-tests.jar diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..8aabb0e --- /dev/null +++ b/Makefile @@ -0,0 +1,26 @@ +GRADLE ?= ./gradlew + +.PHONY: all +all: check codecov eclipse javadocAll show-dependency-updates + +.PHONY: codecov +codecov: + $(GRADLE) java-pinning-java11:testCodeCoverageReport + echo "Code coverage report available at file://$(PWD)/java-pinnging-java11/build/reports/jacoco/testCodeCoverageReport/html/index.html" + +.PHONY: check +check: + $(GRADLE) $@ + +.PHONY: eclipse +eclipse: + $(GRADLE) $@ + +.PHONY: javadocAll +javadocAll: + $(GRADLE) $@ + echo "javadoc available at file://$(PWD)/build/javadoc/index.html" + +.PHONY: show-dependency-updates +show-dependency-updates: + $(GRADLE) dependencyUpdates diff --git a/build-logic/build.gradle b/build-logic/build.gradle new file mode 100644 index 0000000..de053e0 --- /dev/null +++ b/build-logic/build.gradle @@ -0,0 +1,16 @@ +plugins { + id 'groovy-gradle-plugin' +} + +repositories { + gradlePluginPortal() + google() +} + +dependencies { + implementation "biz.aQute.bnd:biz.aQute.bnd.gradle:7.0.0" + implementation "net.ltgt.gradle:gradle-errorprone-plugin:4.0.1" + implementation "ru.vyarus:gradle-animalsniffer-plugin:1.7.1" + implementation "com.github.ben-manes:gradle-versions-plugin:0.51.0" + implementation 'com.android.tools.build:gradle:8.7.0' +} diff --git a/build-logic/settings.gradle b/build-logic/settings.gradle new file mode 100644 index 0000000..37e09a3 --- /dev/null +++ b/build-logic/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'javapinning-build-logic' diff --git a/build-logic/src/main/groovy/eu.geekplace.javapinning.android-conventions.gradle b/build-logic/src/main/groovy/eu.geekplace.javapinning.android-conventions.gradle new file mode 100644 index 0000000..2ec5557 --- /dev/null +++ b/build-logic/src/main/groovy/eu.geekplace.javapinning.android-conventions.gradle @@ -0,0 +1,11 @@ +plugins { + id 'ru.vyarus.animalsniffer' + id 'eu.geekplace.javapinning.common-conventions' +} + +dependencies { + signature "net.sf.androidscents.signature:android-api-level-${minAndroidSdk}:4.0.3_r5@signature" +} +animalsniffer { + sourceSets = [sourceSets.main] +} diff --git a/build-logic/src/main/groovy/eu.geekplace.javapinning.common-conventions.gradle b/build-logic/src/main/groovy/eu.geekplace.javapinning.common-conventions.gradle new file mode 100644 index 0000000..e718872 --- /dev/null +++ b/build-logic/src/main/groovy/eu.geekplace.javapinning.common-conventions.gradle @@ -0,0 +1,37 @@ +ext { + javaVersion = JavaVersion.VERSION_11 + javaMajor = javaVersion.getMajorVersion() + minAndroidSdk = 15 + + androidBootClasspath = getAndroidRuntimeJar(minAndroidSdk) + + // Export the function by turning it into a closure. + // https://stackoverflow.com/a/23290820/194894 + getAndroidRuntimeJar = this.&getAndroidRuntimeJar +} + +repositories { + mavenCentral() + google() + mavenLocal() +} + +def getAndroidRuntimeJar(androidApiLevel) { + def androidHome = getAndroidHome() + def androidJar = new File("$androidHome/platforms/android-${androidApiLevel}/android.jar") + if (androidJar.isFile()) { + return androidJar + } else { + throw new Exception("Can't find android.jar for API level ${androidApiLevel}. Please install corresponding SDK platform package") + } +} + +def getAndroidHome() { + def androidHomeEnv = System.getenv("ANDROID_HOME") + if (androidHomeEnv == null) { + throw new Exception("ANDROID_HOME environment variable is not set") + } + def androidHome = new File(androidHomeEnv) + if (!androidHome.isDirectory()) throw new Exception("Environment variable ANDROID_HOME is not pointing to a directory") + return androidHome +} diff --git a/build-logic/src/main/groovy/eu.geekplace.javapinning.java-conventions.gradle b/build-logic/src/main/groovy/eu.geekplace.javapinning.java-conventions.gradle new file mode 100644 index 0000000..d266df1 --- /dev/null +++ b/build-logic/src/main/groovy/eu.geekplace.javapinning.java-conventions.gradle @@ -0,0 +1,261 @@ +plugins { + id 'biz.aQute.bnd.builder' + id 'checkstyle' + id 'eclipse' + id 'idea' + id 'jacoco' + id 'java' + id 'java-library' + id 'maven-publish' + id 'net.ltgt.errorprone' + id 'signing' + id 'com.github.ben-manes.versions' + + id 'jacoco-report-aggregation' + id 'test-report-aggregation' + + id 'eu.geekplace.javapinning.common-conventions' + id 'eu.geekplace.javapinning.javadoc-conventions' +} + +version readVersionFile() + +ext { + isSnapshot = version.endsWith('-SNAPSHOT') + gitCommit = getGitCommit() + documentationDir = new File(projectDir, 'documentation') + releasedocsDir = new File(buildDir, 'releasedocs') + rootConfigDir = new File(rootDir, 'config') + sonatypeCredentialsAvailable = project.hasProperty('sonatypeUsername') && project.hasProperty('sonatypePassword') + isReleaseVersion = !isSnapshot + isContinuousIntegrationEnvironment = Boolean.parseBoolean(System.getenv('CI')) + signingRequired = !(isSnapshot || isContinuousIntegrationEnvironment) + sonatypeSnapshotUrl = 'https://oss.sonatype.org/content/repositories/snapshots' + sonatypeStagingUrl = 'https://oss.sonatype.org/service/local/staging/deploy/maven2' + builtDate = (new java.text.SimpleDateFormat("yyyy-MM-dd")).format(new Date()) + junitVersion = '5.11.3' +} + +group = 'eu.geekplace.javapinning' + +java { + sourceCompatibility = javaVersion + targetCompatibility = sourceCompatibility +} + +ext.sharedManifest = manifest { + attributes('Implementation-Version': version, + 'Implementation-GitRevision': ext.gitCommit, + 'Built-JDK': System.getProperty('java.version'), + 'Built-Gradle': gradle.gradleVersion, + 'Built-By': System.getProperty('user.name') + ) +} + +eclipse { + classpath { + downloadJavadoc = true + } +} + +// Make all project's 'test' target depend on javadoc, so that +// javadoc is also linted. +test.dependsOn javadoc + +tasks.withType(JavaCompile) { + // Some systems may not have set their platform default + // converter to 'utf8', but we use unicode in our source + // files. Therefore ensure that javac uses unicode + options.encoding = "utf8" + options.compilerArgs = [ + '-Xlint:all', + // Set '-options' because a non-java7 javac will emit a + // warning if source/target is set to 1.7 and + // bootclasspath is *not* set. + '-Xlint:-options', + '-Werror', + ] + options.release = Integer.valueOf(javaMajor) +} + +jacoco { + toolVersion = "0.8.12" +} + +jacocoTestReport { + dependsOn test + reports { + xml.required = true + } +} + +dependencies { + testImplementation "org.junit.jupiter:junit-jupiter-api:$junitVersion" + testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junitVersion" + + // https://stackoverflow.com/a/77274251/194894 + testImplementation "org.junit.platform:junit-platform-launcher:1.11.3" + + errorprone 'com.google.errorprone:error_prone_core:2.35.1' +} + +test { + useJUnitPlatform() + + maxParallelForks = Runtime.runtime.availableProcessors().intdiv(2) ?: 1 + + // Enable full stacktraces of failed tests. Especially handy + // for environments like Travis. + testLogging { + events "failed" + exceptionFormat "full" + } +} + +jar { + bundle { + bnd( + '-removeheaders': 'Tool, Bnd-*', + '-exportcontents': 'eu.geekplace.javapinning.*', + ) + } +} +checkstyle { + toolVersion = '10.18.2' +} +task sourcesJar(type: Jar, dependsOn: classes) { + archiveClassifier = 'sources' + from sourceSets.main.allSource +} +task javadocJar(type: Jar, dependsOn: javadoc) { + archiveClassifier = 'javadoc' + from javadoc.destinationDir +} +task testsJar(type: Jar) { + archiveClassifier = 'tests' + from sourceSets.test.output +} +configurations { + testRuntime +} +artifacts { + // Add a 'testRuntime' configuration including the tests so that + // it can be consumed by other projects (smack-omemo-signal for + // example). See http://stackoverflow.com/a/21946676/194894 + testRuntime testsJar +} + +publishing { + publications { + mavenJava(MavenPublication) { + from components.java + artifact sourcesJar + artifact javadocJar + artifact testsJar + pom { + name = 'Java Pinning' + url = 'http://javapinning.geekplace.eu' + afterEvaluate { + description = project.description + } + + scm { + url = 'https://github.com/flowdalic/android-pinning' + connection = 'scm:git@github.com:flowdalic/android-pinning.git' + developerConnection = 'scm:git@github.com:flowdalic/android-pinning.git' + } + + licenses { + license { + name = 'The Apache Software License, Version 2.0' + url = 'http://www.apache.org/licenses/LICENSE-2.0.txt' + distribution = 'repo' + } + } + + developers { + developer { + id = 'flow' + name = 'Florian Schmaus' + email = 'flo@geekplace.eu' + } + } + } + } + } + repositories { + maven { + url isSnapshot ? sonatypeSnapshotUrl : sonatypeStagingUrl + if (sonatypeCredentialsAvailable) { + credentials { + username = sonatypeUsername + password = sonatypePassword + } + } + } + } +} + +// Workaround for gpg signatory not supporting the 'required' option +// See https://github.com/gradle/gradle/issues/5064#issuecomment-381924984 +// Note what we use 'signing.gnupg.keyName' instead of 'signing.keyId'. +tasks.withType(Sign) { + onlyIf { + project.hasProperty('signing.gnupg.keyName') + } +} +signing { + required { signingRequired } + useGpgCmd() + sign publishing.publications.mavenJava +} + +tasks.withType(JavaCompile) { + options.errorprone { + disableWarningsInGeneratedCode = true + excludedPaths = ".*/jmh_generated/.*" + error( + "UnusedVariable", + "UnusedMethod", + "MethodCanBeStatic", + ) + errorproneArgs = [ + // Disable MissingCasesInEnumSwitch error prone check + // because this check is already done by javac as incomplete-switch. + '-Xep:MissingCasesInEnumSwitch:OFF', + '-Xep:StringSplitter:OFF', + '-Xep:JavaTimeDefaultTimeZone:OFF', + '-Xep:InlineMeSuggester:OFF', + ] + } +} + +// TODO: Note sure what this does (did). Was there prior the build-logic conversion. +// dependencies { +// androidProjects.each { project -> +// api project +// } +// } + +def getGitCommit() { + def projectDirFile = new File("$projectDir") + def dotGit = new File(projectDirFile, ".git") + if (!dotGit.isDirectory()) return 'non-git build' + + def cmd = 'git describe --always --tags --dirty=+' + def proc = cmd.execute(null, projectDirFile) + def gitCommit = proc.text.trim() + assert !gitCommit.isEmpty() + gitCommit +} + +def readVersionFile() { + def versionFile = new File(rootDir, 'version') + if (!versionFile.isFile()) { + throw new Exception("Could not find version file") + } + if (versionFile.text.isEmpty()) { + throw new Exception("Version file does not contain a version") + } + versionFile.text.trim() +} diff --git a/build-logic/src/main/groovy/eu.geekplace.javapinning.javadoc-conventions.gradle b/build-logic/src/main/groovy/eu.geekplace.javapinning.javadoc-conventions.gradle new file mode 100644 index 0000000..95fc0b4 --- /dev/null +++ b/build-logic/src/main/groovy/eu.geekplace.javapinning.javadoc-conventions.gradle @@ -0,0 +1,24 @@ +plugins { + // Javadoc linking requires repositories to bet configured. And + // those are declared in common-conventions, hence we add it here. + id 'eu.geekplace.javapinning.common-conventions' +} + + +tasks.withType(Javadoc) { + // The '-quiet' as second argument is actually a hack, + // since the one parameter addStringOption doesn't seem to + // work, we extra add '-quiet', which is added anyway by + // gradle. + // We disable 'missing' as we do most of javadoc checking via checkstyle. + options.addStringOption('Xdoclint:all,-missing', '-quiet') + // Abort on javadoc warnings. + // See JDK-8200363 (https://bugs.openjdk.java.net/browse/JDK-8200363) + // for information about the -Xwerror option. + options.addStringOption('Xwerror', '-quiet') + options.addStringOption('-release', javaMajor) +} + +tasks.withType(Javadoc) { + options.charSet = "UTF-8" +} diff --git a/build-logic/src/main/groovy/eu.geekplace.javapinning.junit4-conventions.gradle b/build-logic/src/main/groovy/eu.geekplace.javapinning.junit4-conventions.gradle new file mode 100644 index 0000000..ffdb90a --- /dev/null +++ b/build-logic/src/main/groovy/eu.geekplace.javapinning.junit4-conventions.gradle @@ -0,0 +1,4 @@ +dependencies { + testImplementation "junit:junit:4.13.2" + testRuntimeOnly "org.junit.vintage:junit-vintage-engine:$junitVersion" +} diff --git a/build.gradle b/build.gradle index 8482c29..2a67998 100644 --- a/build.gradle +++ b/build.gradle @@ -1,209 +1,59 @@ -buildscript { - repositories { - mavenCentral() - jcenter() - google() - } - - dependencies { - classpath 'com.android.tools.build:gradle:3.0.1' - } +plugins { + id 'eu.geekplace.javapinning.javadoc-conventions' } -apply from: 'version.gradle' +// TODO: +// apply from: 'version.gradle' ext { - gitCommit = getGitCommit() - buildDate = getDatestamp() - sonatypeCredentialsAvailable = project.hasProperty('sonatypeUsername') && project.hasProperty('sonatypePassword') - isReleaseVersion = !isSnapshot - signingRequired = isReleaseVersion - sonatypeSnapshotUrl = 'https://oss.sonatype.org/content/repositories/snapshots' - sonatypeStagingUrl = 'https://oss.sonatype.org/service/local/staging/deploy/maven2' - // Returns only the date in yyyy-MM-dd format, as otherwise, with - // hh:mm:ss information, the manifest files would change with every - // build, causing unnecessary rebuilds. - builtDate = (new java.text.SimpleDateFormat("yyyy-MM-dd")).format(new Date()) - oneLineDesc = 'A Java library for TLS pinning' - androidProjects = [ - ':java-pinning-android' - ].collect{ project(it) } - javaProjects = subprojects - androidProjects - javaCompatibility = JavaVersion.VERSION_1_7 - rootConfigDir = new File(rootDir, 'config') -} - -configure(javaProjects) { - apply plugin: 'java' - apply plugin: 'eclipse' - apply plugin: 'osgi' - // We need to apply the 'maven' plugin here too, as otherwise the - // dependencies of java-pinning-java7 won't be set correctly, e.g - // the dependency on java-pinning won't be set. - apply plugin: 'maven' - - sourceCompatibility = javaCompatibility - targetCompatibility = sourceCompatibility - - eclipse { - classpath { - downloadJavadoc = true + javadocAllDir = new File(buildDir, 'javadoc') + noJavadocAllProjects = [ + ':java-pinning-android', + ].collect { project(it) } + javadocAllProjects = subprojects - noJavadocAllProjects +} + + +evaluationDependsOnChildren() +task javadocAll(type: Javadoc) { + source javadocAllProjects.collect {project -> + project.sourceSets.main.allJava.findAll { + // Filter out symbolic links to avoid + // "warning: a package-info.java file has already been seen for package" + // javadoc warnings. + !java.nio.file.Files.isSymbolicLink(it.toPath()) } } - - task sourcesJar(type: Jar, dependsOn: classes) { - classifier = 'sources' - from sourceSets.main.allSource - } - - task javadocJar(type: Jar, dependsOn: javadoc) { - classifier = 'javadoc' - from javadoc.destinationDir - } - - artifacts { - archives sourcesJar - archives javadocJar - } - - uploadArchives { - repositories { - mavenDeployer { - pom { - project { - packaging 'jar' - } + destinationDir = javadocAllDir + // Might need a classpath + classpath = files(javadocAllProjects.collect {project -> + project.sourceSets.main.compileClasspath}) + classpath += files(androidBootClasspath) + options { + linkSource = true + use = true + links = [ + "https://docs.oracle.com/en/java/javase/${javaMajor}/docs/api/", + ] as String[] + overview = "$projectDir/resources/javadoc-overview.html" + } + + // Finally copy the javadoc doc-files from the subprojects, which + // are potentially generated, to the javadocAll directory. Note + // that we use a copy *method* and not a *task* because the inputs + // of copy tasks is determined within the configuration phase. And + // since some of the inputs are generated, they will not get + // picked up if we used a copy method. See also + // https://stackoverflow.com/a/40518516/194894 + doLast { + copy { + javadocAllProjects.each { + from ("${it.projectDir}/src/javadoc") { + include '**/doc-files/*.*' } } - } - } - - jar { - manifest { - attributes( - 'Implementation-Version': version, - 'Implementation-GitRevision': project.gitCommit, - 'Built-Date': project.buildDate, - 'Built-JDK': System.getProperty('java.version'), - 'Built-Gradle': gradle.gradleVersion, - 'Built-By': System.getProperty('user.name') - ) - } - } -} - -allprojects { - apply plugin: 'idea' - group = 'eu.geekplace.javapinning' - version = shortVersion - if (isSnapshot) { - version += '-SNAPSHOT' - } - if (JavaVersion.current().isJava8Compatible()) { - tasks.withType(Javadoc) { - options.addStringOption('Xdoclint:none', '-quiet') + into javadocAllDir } } - -} - -subprojects { - apply plugin: 'maven' - apply plugin: 'signing' - apply plugin: 'checkstyle' - - repositories { - mavenCentral() - } - - uploadArchives { - repositories { - mavenDeployer { - if (signingRequired) { - beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } - } - repository(url: project.sonatypeStagingUrl) { - if (sonatypeCredentialsAvailable) { - authentication(userName: sonatypeUsername, password: sonatypePassword) - } - } - snapshotRepository(url: project.sonatypeSnapshotUrl) { - if (sonatypeCredentialsAvailable) { - authentication(userName: sonatypeUsername, password: sonatypePassword) - } - } - - pom.project { - name 'Java Pinning' - description project.oneLineDesc - url 'http://javapinning.geekplace.eu' - - scm { - url 'https://github.com/flowdalic/android-pinning' - connection 'scm:git@github.com:flowdalic/android-pinning.git' - developerConnection 'scm:git@github.com:flowdalic/android-pinning.git' - } - - licenses { - license { - name 'The Apache Software License, Version 2.0' - url 'http://www.apache.org/licenses/LICENSE-2.0.txt' - distribution 'repo' - } - } - - developers { - developer { - id 'flow' - name 'Florian Schmaus' - } - } - } - } - } - } - - signing { - required { signingRequired } - sign configurations.archives - } - - checkstyle { - configFile = new File(rootConfigDir, 'checkstyle.xml') - toolVersion = '7.7' - } -} - -gradle.taskGraph.whenReady { taskGraph -> - if (signingRequired - && taskGraph.allTasks.any { it instanceof Sign }) { - // Use Java 6's console to read from the console (no good for a CI environment) - def console = System.console() - console.printf '\n\nWe have to sign some things in this build.\n\nPlease enter your signing details.\n\n' - def password = console.readPassword('GnuPG Private Key Password: ') - - allprojects { ext.'signing.password' = password } - - console.printf '\nThanks.\n\n' - } -} - -def getGitCommit() { - def dotGit = new File("$projectDir/.git") - if (!dotGit.isDirectory()) return 'non-git build' - - def cmd = 'git describe --always --tags --dirty=+' - def proc = cmd.execute() - def gitCommit = proc.text.trim() - assert !gitCommit.isEmpty() - gitCommit -} - -// Returns only the date in yyyy-MM-dd format, as otherwise, with -// hh:mm:ss information, the manifest files would change with every -// build, causing unnecessary rebuilds. -def getDatestamp() { - def date = new Date() - return date.format('yyyy-MM-dd') } diff --git a/config/checkstyle.xml b/config/checkstyle/checkstyle.xml similarity index 87% rename from config/checkstyle.xml rename to config/checkstyle/checkstyle.xml index 23156f8..0ff9b31 100644 --- a/config/checkstyle.xml +++ b/config/checkstyle/checkstyle.xml @@ -4,11 +4,10 @@ "http://www.puppycrawl.com/dtds/configuration_1_3.dtd"> - + - - + @@ -64,8 +63,8 @@ --> + - @@ -93,13 +92,9 @@ - - + - - - @@ -189,12 +184,10 @@ , TYPE_EXTENSION_AND "/> - - - - - + + + + diff --git a/config/header.txt b/config/checkstyle/header.txt similarity index 100% rename from config/header.txt rename to config/checkstyle/header.txt diff --git a/config/suppressions.xml b/config/checkstyle/suppressions.xml similarity index 100% rename from config/suppressions.xml rename to config/checkstyle/suppressions.xml diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a4b76b9 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..df97d72 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..f5feea6 --- /dev/null +++ b/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/java-pinning-android/build.gradle b/java-pinning-android/build.gradle index 31c4c2f..9206973 100644 --- a/java-pinning-android/build.gradle +++ b/java-pinning-android/build.gradle @@ -1,16 +1,22 @@ -apply plugin: 'com.android.library' +plugins { + id 'eu.geekplace.javapinning.common-conventions' + id 'com.android.library' +} android { - compileSdkVersion 15 - buildToolsVersion "27.0.3" + compileSdkVersion 30 defaultConfig { - versionCode project.versionCode versionName version - minSdkVersion 1 + // increase versionCode with every release + // versionCode format: + // + versionCode 1030100 + minSdkVersion minAndroidSdk + namespace 'eu.geekplace.javapinning.android' } compileOptions { - sourceCompatibility = javaCompatibility + sourceCompatibility = javaVersion targetCompatibility project.sourceCompatibility } lintOptions { @@ -19,17 +25,5 @@ android { } dependencies { - // implementation project(':java-pinning-core') -} - -uploadArchives { - repositories { - mavenDeployer { - pom { - project { - packaging 'aar' - } - } - } - } + api project(':java-pinning-core') } diff --git a/java-pinning-android/src/main/AndroidManifest.xml b/java-pinning-android/src/main/AndroidManifest.xml index e199708..e8e3bb5 100644 --- a/java-pinning-android/src/main/AndroidManifest.xml +++ b/java-pinning-android/src/main/AndroidManifest.xml @@ -1,4 +1,4 @@ + > diff --git a/java-pinning-core/build.gradle b/java-pinning-core/build.gradle index 13cf555..4c5053c 100644 --- a/java-pinning-core/build.gradle +++ b/java-pinning-core/build.gradle @@ -1,3 +1,8 @@ -dependencies { - testCompile 'junit:junit:4.12' +plugins { + id 'eu.geekplace.javapinning.java-conventions' + id 'eu.geekplace.javapinning.android-conventions' + id 'eu.geekplace.javapinning.junit4-conventions' } + +description = """\ +Java Pinning's Core""" diff --git a/java-pinning-core/src/main/java/eu/geekplace/javapinning/pin/Pin.java b/java-pinning-core/src/main/java/eu/geekplace/javapinning/pin/Pin.java index c603541..8b71a26 100644 --- a/java-pinning-core/src/main/java/eu/geekplace/javapinning/pin/Pin.java +++ b/java-pinning-core/src/main/java/eu/geekplace/javapinning/pin/Pin.java @@ -1,6 +1,6 @@ /** * - * Copyright 2014-2017 Florian Schmaus + * Copyright 2014-2024 Florian Schmaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,8 +58,8 @@ protected Pin(String pinHexString) { /** * Create a new {@link Pin} from the given String. *

- * The Pin String must be in the format [type]:[hex-string], where - * type denotes the type of the Pin and hex-string is the + * The Pin String must be in the format [type]:[hex-string], where + * type denotes the type of the Pin and hex-string is the * binary value of the Pin encoded in hex. Currently supported types are *

    *
  • PLAIN
  • @@ -72,7 +72,6 @@ protected Pin(String pinHexString) { * binary representation. First the string is lower-cased, then all * whitespace characters and colons are removed before the string is decoded * to bytes. - *

    * * @param string * the Pin String. diff --git a/java-pinning-core/src/main/java/eu/geekplace/javapinning/pin/PublicKeyPin.java b/java-pinning-core/src/main/java/eu/geekplace/javapinning/pin/PublicKeyPin.java index b00e591..e69959d 100644 --- a/java-pinning-core/src/main/java/eu/geekplace/javapinning/pin/PublicKeyPin.java +++ b/java-pinning-core/src/main/java/eu/geekplace/javapinning/pin/PublicKeyPin.java @@ -34,6 +34,7 @@ public boolean pinsCertificate(X509Certificate x509certificate) { return pinsCertificate(pubkey); } + @Override protected abstract boolean pinsCertificate(byte[] pubkey); } diff --git a/java-pinning-core/src/test/java/eu/geekplace/javapinning/integrationtest/IntegrationTest.java b/java-pinning-core/src/test/java/eu/geekplace/javapinning/integrationtest/IntegrationTest.java index 005e06d..8790403 100644 --- a/java-pinning-core/src/test/java/eu/geekplace/javapinning/integrationtest/IntegrationTest.java +++ b/java-pinning-core/src/test/java/eu/geekplace/javapinning/integrationtest/IntegrationTest.java @@ -1,6 +1,6 @@ /** * - * Copyright 2014-2017 Florian Schmaus + * Copyright 2014-2024 Florian Schmaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ import java.io.IOException; import java.io.OutputStream; import java.net.Socket; +import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; @@ -32,8 +33,9 @@ public class IntegrationTest { @Test + @SuppressWarnings({"AddressSelection"}) public void main() throws NoSuchAlgorithmException, KeyManagementException, IOException { - SSLContext sc = JavaPinning.forPin("SHA256:a4bd7ea9bf474cc459266b82fdb07f648f5ddf4d8162baea895b91c96f831ab5"); + SSLContext sc = JavaPinning.forPin("SHA256:1acf9d4fd9140b5ee70d86571f9da62b31a795453f439992d14aee4d05b71f45"); Socket socket = new Socket("github.com", 443); SSLSocket sslSocket = (SSLSocket) sc.getSocketFactory().createSocket(socket, "github.com", 443, true); @@ -43,7 +45,7 @@ public void main() throws NoSuchAlgorithmException, KeyManagementException, IOE System.out.println(name); // CHECKSTYLE:ON OutputStream os = sslSocket.getOutputStream(); - os.write("GET /".getBytes()); + os.write("GET /".getBytes(StandardCharsets.UTF_8)); os.flush(); } } diff --git a/java-pinning-java7/build.gradle b/java-pinning-java11/build.gradle similarity index 55% rename from java-pinning-java7/build.gradle rename to java-pinning-java11/build.gradle index f4635e9..8fd0197 100644 --- a/java-pinning-java7/build.gradle +++ b/java-pinning-java11/build.gradle @@ -1,3 +1,10 @@ +plugins { + id 'eu.geekplace.javapinning.java-conventions' +} + +description = """\ +Java Pinning's Java API""" + dependencies { api project(':java-pinning-core') testImplementation project(path: ':java-pinning-core', configuration: 'testRuntime') diff --git a/java-pinning-java7/src/main/java/eu/geekplace/javapinning/java7/Java7Pinning.java b/java-pinning-java11/src/main/java/eu/geekplace/javapinning/java7/Java7Pinning.java similarity index 98% rename from java-pinning-java7/src/main/java/eu/geekplace/javapinning/java7/Java7Pinning.java rename to java-pinning-java11/src/main/java/eu/geekplace/javapinning/java7/Java7Pinning.java index 220ed98..f6cb682 100644 --- a/java-pinning-java7/src/main/java/eu/geekplace/javapinning/java7/Java7Pinning.java +++ b/java-pinning-java11/src/main/java/eu/geekplace/javapinning/java7/Java7Pinning.java @@ -1,6 +1,6 @@ /** * - * Copyright 2016-2017 Florian Schmaus + * Copyright 2016-2024 Florian Schmaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/java-pinning-java7/src/main/java/eu/geekplace/javapinning/java7/X509ExtendedTrustManagerWrapper.java b/java-pinning-java11/src/main/java/eu/geekplace/javapinning/java7/X509ExtendedTrustManagerWrapper.java similarity index 100% rename from java-pinning-java7/src/main/java/eu/geekplace/javapinning/java7/X509ExtendedTrustManagerWrapper.java rename to java-pinning-java11/src/main/java/eu/geekplace/javapinning/java7/X509ExtendedTrustManagerWrapper.java diff --git a/settings.gradle b/settings.gradle index 9c16db4..dfe2da5 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,4 +1,11 @@ -include \ - 'java-pinning-core' \ - , 'java-pinning-android' \ - , 'java-pinning-java7' +pluginManagement { + repositories { + gradlePluginPortal() + google() + } + includeBuild('build-logic') +} + +include 'java-pinning-core', + 'java-pinning-android', + 'java-pinning-java11' diff --git a/tools/pin.py b/tools/pin.py index 7102c63..3a3480c 100755 --- a/tools/pin.py +++ b/tools/pin.py @@ -1,14 +1,13 @@ #!/usr/bin/env python from M2Crypto import X509 -import binascii import hashlib import ssl import sys def main(argv): if len(argv) != 1 and len(argv) != 2: - print "Usage: pin.py [ | ]" + print("Usage: pin.py [ | ]") return if (len(argv) == 1): @@ -22,17 +21,17 @@ def main(argv): digest.update(pubkey) sha256 = digest.digest() - print "Calculating PIN for certificate: " + cert.get_subject().as_text() - print "\n" - print "Public Key Pins:" - print "----------------" - print "SHA256:" + binascii.hexlify(sha256) - print "PLAIN:" + binascii.hexlify(pubkey) - print "\n" - print "Certificate Pins:" - print "-----------------" - print "CERTSHA256:" + cert.get_fingerprint('sha256') - print "CERTPLAIN:" + binascii.hexlify(cert.as_der()) + print("Calculating PIN for certificate: " + cert.get_subject().as_text()) + print("\n") + print("Public Key Pins:") + print("----------------") + print("SHA256:" + sha256.hex()) + print("PLAIN:" + pubkey.hex()) + print("\n") + print("Certificate Pins:") + print("-----------------") + print("CERTSHA256:" + cert.get_fingerprint('sha256')) + print("CERTPLAIN:" + cert.as_der().hex()) if __name__ == '__main__': main(sys.argv[1:]) diff --git a/version b/version new file mode 100644 index 0000000..9d7c109 --- /dev/null +++ b/version @@ -0,0 +1 @@ +1.3.0-SNAPSHOT diff --git a/version.gradle b/version.gradle deleted file mode 100644 index 0f0b6a7..0000000 --- a/version.gradle +++ /dev/null @@ -1,10 +0,0 @@ -allprojects { - ext { - shortVersion = '1.2.1' - // increase versionCode with every release - // versionCode format: - // - versionCode = 01020100 - isSnapshot = true - } -}