View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.eclipse.aether.generator.gnupg;
20  
21  import java.io.IOException;
22  import java.io.InputStream;
23  import java.io.OutputStream;
24  import java.io.UncheckedIOException;
25  import java.nio.file.Files;
26  import java.nio.file.Path;
27  import java.util.ArrayList;
28  import java.util.Collection;
29  import java.util.Collections;
30  import java.util.List;
31  import java.util.concurrent.atomic.AtomicBoolean;
32  import java.util.function.Predicate;
33  
34  import org.bouncycastle.bcpg.ArmoredOutputStream;
35  import org.bouncycastle.bcpg.BCPGOutputStream;
36  import org.bouncycastle.bcpg.HashAlgorithmTags;
37  import org.bouncycastle.openpgp.PGPException;
38  import org.bouncycastle.openpgp.PGPPrivateKey;
39  import org.bouncycastle.openpgp.PGPSecretKey;
40  import org.bouncycastle.openpgp.PGPSignature;
41  import org.bouncycastle.openpgp.PGPSignatureGenerator;
42  import org.bouncycastle.openpgp.PGPSignatureSubpacketVector;
43  import org.bouncycastle.openpgp.operator.bc.BcPGPContentSignerBuilder;
44  import org.eclipse.aether.artifact.Artifact;
45  import org.eclipse.aether.spi.artifact.generator.ArtifactGenerator;
46  import org.eclipse.aether.util.artifact.SubArtifact;
47  import org.slf4j.Logger;
48  import org.slf4j.LoggerFactory;
49  
50  final class GnupgSignatureArtifactGenerator implements ArtifactGenerator {
51      private static final String ARTIFACT_EXTENSION = ".asc";
52      private final Logger logger = LoggerFactory.getLogger(getClass());
53      private final List<Artifact> artifacts;
54      private final Predicate<Artifact> signableArtifactPredicate;
55      private final PGPSecretKey secretKey;
56      private final PGPPrivateKey privateKey;
57      private final PGPSignatureSubpacketVector hashSubPackets;
58      private final String keyInfo;
59      private final List<Path> signatureTempFiles;
60      private final AtomicBoolean closed;
61  
62      GnupgSignatureArtifactGenerator(
63              Collection<Artifact> artifacts,
64              Predicate<Artifact> signableArtifactPredicate,
65              PGPSecretKey secretKey,
66              PGPPrivateKey privateKey,
67              PGPSignatureSubpacketVector hashSubPackets,
68              String keyInfo) {
69          this.artifacts = new ArrayList<>(artifacts);
70          this.signableArtifactPredicate = signableArtifactPredicate;
71          this.secretKey = secretKey;
72          this.privateKey = privateKey;
73          this.hashSubPackets = hashSubPackets;
74          this.keyInfo = keyInfo;
75          this.signatureTempFiles = new ArrayList<>();
76          this.closed = new AtomicBoolean(false);
77          logger.debug("Created generator using key {}", keyInfo);
78      }
79  
80      @Override
81      public String generatorId() {
82          return GnupgSignatureArtifactGeneratorFactory.NAME;
83      }
84  
85      @Override
86      public synchronized Collection<? extends Artifact> generate(Collection<? extends Artifact> generatedArtifacts) {
87          if (closed.get()) {
88              throw new IllegalStateException("generator " + generatorId() + " is closed");
89          }
90          try {
91              artifacts.addAll(generatedArtifacts);
92  
93              // Determine, per artifact, which signable artifacts still need a signature. A pre-existing signature
94              // (e.g. produced by maven-gpg-plugin) skips only the artifact it covers; it must not disable signing
95              // of the whole artifact set, which would silently publish partially unsigned releases.
96              ArrayList<Artifact> artifactsToSign = new ArrayList<>();
97              for (Artifact artifact : artifacts) {
98                  if (isSignatureArtifact(artifact)) {
99                      continue; // never sign a signature
100                 }
101                 if (!signableArtifactPredicate.test(artifact)) {
102                     continue;
103                 }
104                 if (hasSignature(artifact)) {
105                     logger.debug("GPG signature already present for {}, not signing it again", artifact);
106                     continue;
107                 }
108                 artifactsToSign.add(artifact);
109             }
110             if (artifactsToSign.isEmpty()) {
111                 logger.debug("GPG signatures are present for all signable artifacts, nothing to sign");
112                 return Collections.emptyList();
113             }
114             if (artifacts.stream().anyMatch(this::isSignatureArtifact)) {
115                 logger.info(
116                         "GPG signatures are present for some artifacts only; signing the remaining {} artifact(s) with key {}",
117                         artifactsToSign.size(),
118                         keyInfo);
119             }
120 
121             // sign relevant artifacts
122             ArrayList<Artifact> result = new ArrayList<>();
123             for (Artifact artifact : artifactsToSign) {
124                 Path signatureTempFile = Files.createTempFile("signer-pgp", "tmp");
125                 signatureTempFiles.add(signatureTempFile);
126                 try (InputStream artifactContent = Files.newInputStream(artifact.getPath());
127                         OutputStream signatureContent = Files.newOutputStream(signatureTempFile)) {
128                     sign(artifactContent, signatureContent);
129                 }
130                 result.add(new SubArtifact(
131                         artifact,
132                         artifact.getClassifier(),
133                         artifact.getExtension() + ARTIFACT_EXTENSION,
134                         signatureTempFile.toFile()));
135             }
136             logger.debug("Signed {} artifacts with key {}", result.size(), keyInfo);
137             return result;
138         } catch (IOException e) {
139             throw new UncheckedIOException(e);
140         }
141     }
142 
143     private boolean isSignatureArtifact(Artifact artifact) {
144         return artifact.getExtension().endsWith(ARTIFACT_EXTENSION);
145     }
146 
147     private boolean hasSignature(Artifact artifact) {
148         String signatureExtension = artifact.getExtension() + ARTIFACT_EXTENSION;
149         return artifacts.stream()
150                 .anyMatch(a -> a.getExtension().equals(signatureExtension)
151                         && a.getClassifier().equals(artifact.getClassifier())
152                         && a.getArtifactId().equals(artifact.getArtifactId())
153                         && a.getGroupId().equals(artifact.getGroupId())
154                         && a.getVersion().equals(artifact.getVersion()));
155     }
156 
157     @Override
158     public synchronized void close() {
159         if (closed.compareAndSet(false, true)) {
160             signatureTempFiles.forEach(p -> {
161                 try {
162                     Files.deleteIfExists(p);
163                 } catch (IOException e) {
164                     p.toFile().deleteOnExit();
165                 }
166             });
167         }
168     }
169 
170     private void sign(InputStream content, OutputStream signature) throws IOException {
171         PGPSignatureGenerator sGen = new PGPSignatureGenerator(
172                 new BcPGPContentSignerBuilder(secretKey.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA512),
173                 secretKey.getPublicKey());
174         try {
175             sGen.init(PGPSignature.BINARY_DOCUMENT, privateKey);
176             sGen.setHashedSubpackets(hashSubPackets);
177             int len;
178             byte[] buffer = new byte[8 * 1024];
179             while ((len = content.read(buffer)) >= 0) {
180                 sGen.update(buffer, 0, len);
181             }
182             try (BCPGOutputStream bcpgOutputStream = new BCPGOutputStream(new ArmoredOutputStream(signature))) {
183                 sGen.generate().encode(bcpgOutputStream);
184             }
185         } catch (PGPException e) {
186             throw new IllegalStateException(e);
187         }
188     }
189 }