// Copyright 2017 the original author or 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
//
//      http://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.

[[signing_plugin]]
== The Signing Plugin

The signing plugin adds the ability to digitally sign built files and artifacts. These digital signatures can then be used to prove who built the artifact the signature is attached to as well as other information such as when the signature was generated.

The signing plugin currently only provides support for generating https://en.wikipedia.org/wiki/Pretty_Good_Privacy#OpenPGP[OpenPGP signatures] (which is the signature format http://central.sonatype.org/pages/requirements.html#sign-files-with-gpgpgp[required for publication to the Maven Central Repository]).

[[sec:signing_usage]]
=== Usage

To use the Signing plugin, include the following in your build script:

++++
<sample id="useSigningPlugin" dir="signing/maven" title="Using the Signing plugin">
    <sourcefile file="build.gradle" snippet="use-plugin"/>
</sample>
++++

[[sec:signatory_credentials]]
=== Signatory credentials

In order to create OpenPGP signatures, you will need a key pair (instructions on creating a key pair using the https://www.gnupg.org/[GnuPG tools] can be found in the https://www.gnupg.org/documentation/howtos.html[GnuPG HOWTOs]). You need to provide the signing plugin with your key information, which means three things:

* The public key ID (an 8 character hexadecimal string).
* The absolute path to the secret key ring file containing your private key.
* The passphrase used to protect your private key.

These items must be supplied as the values of properties `signing.keyId`, `signing.secretKeyRingFile`, and `signing.password` respectively. Given the personal and private nature of these values, a good practice is to store them in the user `gradle.properties` file (described in <<sec:gradle_properties_and_system_properties>>).

[source,properties]
----
signing.keyId=24875D73
signing.password=secret
signing.secretKeyRingFile=/Users/me/.gnupg/secring.gpg
----

If specifying this information (especially `signing.password`) in the user `gradle.properties` file is not feasible for your environment, you can source the information however you need to and set the project properties manually.

[source,groovy]
----
import org.gradle.plugins.signing.Sign

gradle.taskGraph.whenReady { taskGraph ->
    if (taskGraph.allTasks.any { it instanceof Sign }) {
        // Use Java 6's console to read from the console (no good for
        // a CI environment)
        Console console = System.console()
        console.printf "\n\nWe have to sign some things in this build." +
                       "\n\nPlease enter your signing details.\n\n"

        def id = console.readLine("PGP Key Id: ")
        def file = console.readLine("PGP Secret Key Ring File (absolute path): ")
        def password = console.readPassword("PGP Private Key Password: ")

        allprojects { ext."signing.keyId" = id }
        allprojects { ext."signing.secretKeyRingFile" = file }
        allprojects { ext."signing.password" = password }

        console.printf "\nThanks.\n\n"
    }
}
----

Note that the presence of a null value for any these three properties will cause an exception.

[[sec:subkeys]]
==== Using OpenPGP subkeys

OpenPGP supports subkeys, which are like the normal keys, except they're bound to a master key pair. One feature of OpenPGP subkeys is that they can be revoked independently of the master keys which makes key management easier. A practical case study of how subkeys can be leveraged in software development can be read on the https://wiki.debian.org/Subkeys[Debian wiki].

The signing plugin supports OpenPGP subkeys out of the box. Just specify a subkey ID as the value in the `signing.keyId` property.

[[sec:specifying_what_to_sign]]
=== Specifying what to sign

As well as configuring how things are to be signed (i.e. the signatory configuration), you must also specify what is to be signed. The Signing plugin provides a DSL that allows you to specify the tasks and/or configurations that should be signed.


[[sec:signing_configurations]]
==== Signing Configurations

It is common to want to sign the artifacts of a configuration. For example, the <<java_plugin,Java plugin>> configures a jar to build and this jar artifact is added to the `archives` configuration. Using the Signing DSL, you can specify that all of the artifacts of this configuration should be signed.

++++
<sample id="signingArchives" dir="signing/maven" title="Signing a configuration">
    <sourcefile file="build.gradle" snippet="sign-archives"/>
</sample>
++++

This will create a task (of type api:org.gradle.plugins.signing.Sign[]) in your project named “`signArchives`”, that will build any `archives` artifacts (if needed) and then generate signatures for them. The signature files will be placed alongside the artifacts being signed.

++++
<sample id="signingArchivesOutput" dir="signing/maven" title="Signing a configuration output">
    <output args="signArchives"/>
</sample>
++++

[[sec:signing_tasks]]
==== Signing Tasks

In some cases the artifact that you need to sign may not be part of a configuration. In this case you can directly sign the task that produces the artifact to sign.

++++
<sample id="signingTasks" dir="signing/tasks" title="Signing a task">
    <sourcefile file="build.gradle" snippet="sign-task"/>
</sample>
++++

This will create a task (of type api:org.gradle.plugins.signing.Sign[]) in your project named “`signStuffZip`”, that will build the input task's archive (if needed) and then sign it. The signature file will be placed alongside the artifact being signed.

++++
<sample id="signingTaskOutput" dir="signing/tasks" title="Signing a task output">
    <output args="signStuffZip"/>
</sample>
++++

For a task to be “signable”, it must produce an archive of some type. Tasks that do this are the api:org.gradle.api.tasks.bundling.Tar[], api:org.gradle.api.tasks.bundling.Zip[], api:org.gradle.api.tasks.bundling.Jar[], api:org.gradle.api.tasks.bundling.War[] and api:org.gradle.plugins.ear.Ear[] tasks.

[[sec:conditional_signing]]
==== Conditional Signing

A common usage pattern is to only sign build artifacts under certain conditions. For example, you may not wish to sign artifacts for non-release versions. To achieve this, you can specify that signing is only required under certain conditions.

++++
<sample id="conditionalSigning" dir="signing/conditional" title="Conditional signing">
                <sourcefile file="build.gradle" snippet="conditional-signing"/>
            </sample>
++++

In this example, we only want to require signing if we are building a release version and we are going to publish it. Because we are inspecting the task graph to determine if we are going to be publishing, we must set the `signing.required` property to a closure to defer the evaluation. See api:org.gradle.plugins.signing.SigningExtension#setRequired(java.lang.Object)[] for more information.

[[sec:publishing_the_signatures]]
=== Publishing the signatures

When specifying what is to be signed via the Signing DSL, the resultant signature artifacts are automatically added to the `signatures` and `archives` dependency configurations. This means that if you want to upload your signatures to your distribution repository along with the artifacts you simply execute the `uploadArchives` task as normal.

[[sec:signing_pom_files]]
=== Signing POM files

[NOTE]
====
Signing the generated POM file generated by the <<publishing_maven,Maven Publishing plugin>> is currently not supported. Future versions of Gradle might add this functionality.
====

When deploying signatures for your artifacts to a Maven repository, you will also want to sign the published POM file. The signing plugin adds a `signing.signPom()` (see: api:org.gradle.plugins.signing.SigningExtension#signPom(org.gradle.api.artifacts.maven.MavenDeployment,groovy.lang.Closure)[]) method that can be used in the `beforeDeployment()` block in your upload task configuration.

++++
<sample id="signingMavenPom" dir="signing/maven" title="Signing a POM for deployment">
    <sourcefile file="build.gradle" snippet="sign-pom"/>
</sample>
++++

When signing is not required and the POM cannot be signed due to insufficient configuration (i.e. no credentials for signing) then the `signPom()` method will silently do nothing.
