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.sigstore;
20  
21  import java.io.IOException;
22  import java.io.UncheckedIOException;
23  import java.nio.file.Files;
24  import java.nio.file.Path;
25  import java.security.GeneralSecurityException;
26  import java.security.cert.X509Certificate;
27  import java.time.temporal.ChronoUnit;
28  import java.util.ArrayList;
29  import java.util.Collection;
30  import java.util.Collections;
31  import java.util.List;
32  import java.util.concurrent.atomic.AtomicBoolean;
33  import java.util.function.Predicate;
34  
35  import dev.sigstore.KeylessSigner;
36  import dev.sigstore.KeylessSignerException;
37  import dev.sigstore.bundle.Bundle;
38  import dev.sigstore.encryption.certificates.Certificates;
39  import dev.sigstore.trustroot.SigstoreConfigurationException;
40  import org.eclipse.aether.artifact.Artifact;
41  import org.eclipse.aether.generator.sigstore.internal.FulcioOidHelper;
42  import org.eclipse.aether.spi.artifact.generator.ArtifactGenerator;
43  import org.eclipse.aether.spi.io.PathProcessor;
44  import org.eclipse.aether.util.artifact.SubArtifact;
45  import org.slf4j.Logger;
46  import org.slf4j.LoggerFactory;
47  
48  final class SigstoreSignatureArtifactGenerator implements ArtifactGenerator {
49      private static final String ARTIFACT_EXTENSION = ".sigstore.json";
50      private final Logger logger = LoggerFactory.getLogger(getClass());
51      private final PathProcessor pathProcessor;
52      private final List<Artifact> artifacts;
53      private final Predicate<Artifact> signableArtifactPredicate;
54      private final boolean publicStaging;
55      private final List<Path> signatureTempFiles;
56      private final AtomicBoolean closed;
57  
58      SigstoreSignatureArtifactGenerator(
59              PathProcessor pathProcessor,
60              Collection<Artifact> artifacts,
61              Predicate<Artifact> signableArtifactPredicate,
62              boolean publicStaging) {
63          this.pathProcessor = pathProcessor;
64          this.artifacts = new ArrayList<>(artifacts);
65          this.signableArtifactPredicate = signableArtifactPredicate;
66          this.publicStaging = publicStaging;
67          this.signatureTempFiles = new ArrayList<>();
68          this.closed = new AtomicBoolean(false);
69          logger.debug("Created sigstore generator (publicStaging={})", publicStaging);
70      }
71  
72      @Override
73      public String generatorId() {
74          return SigstoreSignatureArtifactGeneratorFactory.NAME;
75      }
76  
77      @Override
78      public synchronized Collection<? extends Artifact> generate(Collection<? extends Artifact> generatedArtifacts) {
79          if (closed.get()) {
80              throw new IllegalStateException("generator " + generatorId() + " is closed");
81          }
82          try {
83              artifacts.addAll(generatedArtifacts);
84  
85              // Determine, per artifact, which signable artifacts still need a signature. A pre-existing signature
86              // skips only the artifact it covers; it must not disable signing of the whole artifact set, which
87              // would silently publish partially unsigned releases.
88              ArrayList<Artifact> artifactsToSign = new ArrayList<>();
89              for (Artifact artifact : artifacts) {
90                  if (isSignatureArtifact(artifact)) {
91                      continue; // never sign a signature
92                  }
93                  if (!signableArtifactPredicate.test(artifact)) {
94                      continue;
95                  }
96                  if (hasSignature(artifact)) {
97                      logger.debug("Sigstore signature already present for {}, not signing it again", artifact);
98                      continue;
99                  }
100                 artifactsToSign.add(artifact);
101             }
102             if (artifactsToSign.isEmpty()) {
103                 logger.debug("Sigstore signatures are present for all signable artifacts, nothing to sign");
104                 return Collections.emptyList();
105             }
106             if (artifacts.stream().anyMatch(this::isSignatureArtifact)) {
107                 logger.info(
108                         "Sigstore signatures are present for some artifacts only; signing the remaining {} artifact(s)",
109                         artifactsToSign.size());
110             }
111 
112             // sign relevant artifacts
113             ArrayList<Artifact> result = new ArrayList<>();
114             ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
115             Thread.currentThread().setContextClassLoader(KeylessSigner.class.getClassLoader());
116             try (KeylessSigner signer = publicStaging
117                     ? KeylessSigner.builder().sigstoreStagingDefaults().build()
118                     : KeylessSigner.builder().sigstorePublicDefaults().build()) {
119                 for (Artifact artifact : artifactsToSign) {
120                     Path fileToSign = artifact.getPath();
121                     Path signatureTempFile = Files.createTempFile("signer-sigstore", "tmp");
122                     signatureTempFiles.add(signatureTempFile);
123 
124                     logger.debug("Signing " + artifact);
125                     long start = System.currentTimeMillis();
126                     Bundle bundle = signer.signFile(fileToSign);
127 
128                     X509Certificate cert = (X509Certificate)
129                             bundle.getCertPath().getCertificates().get(0);
130                     long durationMinutes = Certificates.validity(cert, ChronoUnit.MINUTES);
131 
132                     logger.debug("  Fulcio certificate (valid for "
133                             + durationMinutes
134                             + " m) obtained for "
135                             + cert.getSubjectAlternativeNames()
136                                     .iterator()
137                                     .next()
138                                     .get(1)
139                             + " (by "
140                             + FulcioOidHelper.getIssuerV2(cert)
141                             + " IdP)");
142 
143                     pathProcessor.write(signatureTempFile, bundle.toJson());
144 
145                     long duration = System.currentTimeMillis() - start;
146                     logger.debug("  > Rekor entry "
147                             + bundle.getEntries().get(0).getLogIndex()
148                             + " obtained in "
149                             + duration
150                             + " ms, saved to "
151                             + signatureTempFile);
152 
153                     result.add(new SubArtifact(
154                             artifact,
155                             artifact.getClassifier(),
156                             artifact.getExtension() + ARTIFACT_EXTENSION,
157                             signatureTempFile.toFile()));
158                 }
159             } finally {
160                 Thread.currentThread().setContextClassLoader(originalClassLoader);
161             }
162             logger.info("Signed {} artifacts with Sigstore", result.size());
163             return result;
164         } catch (SigstoreConfigurationException e) {
165             throw new IllegalArgumentException("Configuration problem", e);
166         } catch (GeneralSecurityException e) {
167             throw new IllegalArgumentException("Preparation problem", e);
168         } catch (KeylessSignerException e) {
169             throw new IllegalStateException("Processing problem", e);
170         } catch (IOException e) {
171             throw new UncheckedIOException("IO problem", e);
172         }
173     }
174 
175     private boolean isSignatureArtifact(Artifact artifact) {
176         return artifact.getExtension().endsWith(ARTIFACT_EXTENSION);
177     }
178 
179     private boolean hasSignature(Artifact artifact) {
180         String signatureExtension = artifact.getExtension() + ARTIFACT_EXTENSION;
181         return artifacts.stream()
182                 .anyMatch(a -> a.getExtension().equals(signatureExtension)
183                         && a.getClassifier().equals(artifact.getClassifier())
184                         && a.getArtifactId().equals(artifact.getArtifactId())
185                         && a.getGroupId().equals(artifact.getGroupId())
186                         && a.getVersion().equals(artifact.getVersion()));
187     }
188 
189     @Override
190     public synchronized void close() {
191         if (closed.compareAndSet(false, true)) {
192             signatureTempFiles.forEach(p -> {
193                 try {
194                     Files.deleteIfExists(p);
195                 } catch (IOException e) {
196                     p.toFile().deleteOnExit();
197                 }
198             });
199         }
200     }
201 }